Hibernate简介:
Hibernate 是一个开放源代码的对象关系映射框架(ORM),对jdbc进行了非常轻量级的对象封装,将pojo与数据库表建立映射关系,是一个全自动的ORM框架,可以自动生成SQL语句,自动执行。
ORM对象关系映射:
创建一个HelloWord:
1、导入需要的jar包
1.1使用maven方式引入。。。。只需在网页上搜索maven仓库,搜索自己所需要的jar包,将代码复制进自己的工程下的pom.xml中
2、配置Hibernate.cfg.xml(配置数据库连接的相关参数)
2.1
<?xmlversion="1.0" encoding="utf-8"?>
<!DOCTYPEhibernate-configuration PUBLIC
"-//Hibernate/HibernateConfiguration DTD 3.0//EN"
配置session-factory
<session-factory>:SessionFactory是Hibernate中的一个类,保存数据库实例相关的配置信息
<!-- 数据库连接配置 -->
<propertyname="connection.driver_class">com.mysql.jdbc.Driver</property>
<propertyname="connection.url">jdbc:mysql://ip:port/hibernate1506</property>
<propertyname="connection.username">username</property>
<propertyname="connection.password">password</property>
<!-- 数据库连接池配置 -->
<propertyname="connection.pool_size">1</property>
<!--数据库方言指定使用数据库,使Hibernate知道在底层如何拼接生成sql语句-->
<propertyname="dialect">org.hibernate.dialect.MySQL5Dialect</property>
3、配置*.hbm.xml(建立bean对象与table之间的映射关系{xml、Annotation})
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping package="com.huanxin.maven.hibernatebase">
<class name="UserInfoBean" table="userInfo">
<id name="uId" type="java.lang.Long">
<generator class="increment"></generator>
</id>
<property name="username"></property>
<property name="password"></property>
</class>
</hibernate-mapping>
创建UserInfoBean 类
public class UserInfoBean implements Serializable {
long uId;
String username;
String password;
public long getuId() {
return uId;
}
public void setuId(long uId) {
this.uId = uId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public UserInfoBean(String username, String password) {
super();
this.username = username;
this.password = password;
}
public UserInfoBean() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "UserInfoBean [uId=" + uId + ", username=" + username + ", password=" + password + "]";
}
4、加载配置文件,创建SessionFactory
Configuration configuration = new Configuration();
Configuration configure = configuration.configure();
// SessionFactory sessionFactory=configure.buildSessionFactory();
StandardServiceRegistryBuilder applySettings = new StandardServiceRegistryBuilder()
.applySettings(configure.getProperties());
StandardServiceRegistry build = applySettings.build();
SessionFactory sessionFactory = configure.buildSessionFactory(build);
session = sessionFactory.openSession();