1. Hibernate 配置文档
1.1 hibernate.cfg.xml
- 创建
src–>other–>hibernate–>cfg.xml - 参数解释
- 示例如下
<hibernate-configuration>
<session-factory>
<property name="connection.username">root</property>
<property name="connection.password">admin</property>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql:///hibernate?useUnicode=true&characterEncoding=UTF-8</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<property name="hbm2ddl.auto">creat</property>
<mapping resource="students.hbm.xml"/>//注意路径问题,最好放到相同下。
</session-factory>
</hibernate-configuration>
1.2 session
- session 对象的创建有如下两种方法
Session session = faction.openSession();
Session session = faction.getCurrentSession();
但是使用getCurrentSession时候要进行配置,一般使用jdbc,如下图:
- 两者的区别
openSession()是创建的session是不同的对象。需要手动关闭session。
getCurrentSession()是创建的同一个session对象。类似于单例。自动关闭session。
1.3 Transaction 事务
封装heibernate对数据库操作的一些方法
- 需要在初始化以及结束时进行打来以及关闭设置
public void init (){
...
//开启事务
transaction = session.beginTransaction();
}
public void destory(){
//提交事务
transaction.commit();
}
- 如果不使用事务的提交(transaction.commit();),则设置jdbc的提交方式为自动提交。
@Test
public void TestSaveStudent(){
students stu = new students(1,"icanactnow","female",new java.util.Date(),"韩城");
//关闭事务提交,后打开hibernate的 自动提交
session.doWork(new Work() {
@Override
public void execute(Connection arg0) throws SQLException {
// TODO Auto-generated method stub
//arg0就是jdbc链接对象,设置这个链接对象的提交方式为自动提交。
arg0.setAutoCommit(true);//设置jdbc 的提交方式为自动提交。这样就不用打开transaction.commit();
}
});
session.save(stu);
session.flush();//jdbc的自动提交需要设置为自动提交。
}
2. 创建关系映射文档&数据库
2.1 首先创建要持久化的类(students)
2.2 sec右键–>new–>other–>hibernate–>Hibernate XML Mapping file(hbm.xml)–>选择要持久化的类
2.3 在hibernate cfg.xml中添加持久化路径<mapping resource="students.hbm.xml"/>
2.4 这样就通过hibernate tool 自动创建了持久化类与数据库对应的映射关系。
自动生成表结构
示例程序
依据JAVABean的映射文档自动在数据库中创建表。
// 创建配置对象
Configuration configuration = new Configuration().configure();
// 创建服务注册对象
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder()
.applySettings(configuration.getProperties())
.buildServiceRegistry();
// 创建SessionFactory对象
SessionFactory sessionFactory = configuration
.buildSessionFactory(serviceRegistry);
// 创建SchemaExport对象
SchemaExport schemaExport = new SchemaExport(configuration);
schemaExport.create(true, true);// 自动依据映射文件生成对应的数据库表。