1.通过Configuration().configure();读取并解析hibernate.cfg.xml配置文件
2.由hibernate.cfg.xml中的<mapping resource="com/xx/User.hbm.xml"/>读取并解析映射信息
3.通过config.buildSessionFactory();//创建SessionFactory
4.sessionFactory.openSession();//打开Sesssion
5.session.beginTransaction();//创建事务Transation
6.persistent operate持久化操作
7.session.getTransaction().commit();//提交事务
8.关闭Session
9.关闭SesstionFactory
第一步:建立一个java project的项目。导入关于hibernate的jar包。
第二步:建立hibernate.cfg.xml 配置数据库的内容及映射信息。
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- 数据库连接设置 -->
<!-- 展示SQL语句 -->
<property name="show_sql">true</property><!-- 方言-->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- 数据库驱动-->
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<!-- 数据库连接地址-->
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/myhib</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.connection.password">1234</property>
<!-- 数据库创建模式-->
<property name="hbm2ddl.auto">create</property>
<!-- 映射信息-->
<mapping resource="com/bjsxt/user/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
第三步:建立一个类。类名为User 所在的包是com.bjsxt.user
package com.bjsxt.user;
public class User {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
private String birthday;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBirthday() {
return birthday;
}
public void setBirthday(String birthday) {
this.birthday = birthday;
}
public User(String name ,String birthday){
super();
this.name=name;
this.birthday=birthday;
}
//空的构造器
public User(){
}
}
第四步:建立一个关于类和数据库的xml文件,名叫User.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping package="com.bjsxt.user" >
<class name="User" table="_user" >
<id name="id" unsaved-value="null" >
<generator class="native"/><!-- 本地生成 -->
</id>
<property name="name" type="string" />
<property name="birthday" type="string"></property>
</class>
</hibernate-mapping>
第五步:建立一个main函数进行测试
import com.bjsxt.user.User;
public class Test {
public static void main(String[] args) {
Configuration conf=new Configuration();
conf.configure();
SessionFactory sessionFactory=conf.buildSessionFactory();
Session session=sessionFactory.openSession();
Transaction tx=session.beginTransaction();
User u=new User("aaa","bbbb");
session.save(u);
tx.commit();
session.close();
}
检查数据库,数据库成功插入一条数据。