hibernate -- hibernate笔记1
hibernate笔记1
2016年1月20日
13:33
hibernate配置
导入hibernate的jar包
编写hibernate配置文件
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
<?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> <!– 数据库的方言,每个数据库都有自己的方言 –> <property name=”dialect”>org.hibernate.dialect.MySQLDialect</property> <property name=”connection.url”>jdbc:mysql://127.0.0.1:3306/hibernate</property> <property name=”connection.username”>root</property> <property name=”connection.password”></property> <property name=”connection.driver_class”>com.mysql.jdbc.Driver</property> <!– 是否在控制台输出对应的sql语句 –> <property name=”show_sql”>true</property> <!– 数据库更新方案,update是更新,还有覆盖之类的东西,用到时候去查找 –> <property name=”hbm2ddl.auto”>update</property> <!– 加载映射文件 –> <mapping resource=”com/firefly/hibernate/domain/First.hbm.xml”/> </session-factory> </hibernate-configuration> |
以上的hbm2ddl.auto项有几个选择:
create-drop 在程序启动的时候创建对应的数据库表结构。当sessionFactory关闭时会将创建的表结构删除
create 在每次启动的时候都会去删除上次创建的表结构,然后再创建新的表结构
update在每次启动的时候都会追加修改的表结构,但是不会影响原来的数据(这个是常用的)
validate在每次启动的时候会验证并修改表结构
编写实体类,并未实体类加载映射文件,记得倒回去修改配置文件中的加载映射文件语句。
编写java文件对数据库进行操作
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 |
package com.firefly.hibernate.hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import com.firefly.hibernate.domain.First; public class News { public static void main(String[] args) throws Exception { //获得configuration对象 Configuration conf = new Configuration().configure(); //创建session工厂 SessionFactory sf = conf.buildSessionFactory(); //打开session Session sess = sf.openSession(); //开始事务 Transaction tx =sess.beginTransaction(); First f = new First(); f.setId(1); f.setTitle(“我是第一条数据!”); f.setContent(“I’m content”); sess.save(f); //提交事务 tx.commit(); //关闭session sess.close(); //关闭session工厂 sf.close(); } } |
以上是向数据库中添加一条数据
sessionFactory是在应用程序开始的时候创建的,可以被多个线程同时使用
hibernate4之后SessionFactory的闯将方法有一些不同,以上的buildSessionFactory属于是已经过时的方法,我们在使用的时候会有一条横杠将他划上,表示不推荐使用,高逼格的方法为:
在获得configuration之后 ServiceRegistry sr = new ServiceRegistryBuilder().applySettings(configuration.getProperties()).buildServiceRegistry();
SessionFactory sf = configuratioin.buildSesionFactory(sr);
关于事务:用 beginTransaction(); 是开始事务,还有另一个方法是 getTransaction 表示获得与当前session关联的事务
关于hibernate运行流程:
hibernate的思想是将对关系型数据库的操作改变为符合java面向对象编程思想的操作。
hibernate将数据库中的数据映射成为对象通过与实体类对应的映射文件实现;而对对象的操作是放在session容器中的,而session对象的获取是通过session工厂生产的,session工厂是通过configuration对象的来的,在获得configuration对象过程中关联了相关的实体类映射文件。
hibernate的javabean的几个通用的要求:
1.要有一个id,建议要使用封装类
2.这个类不能是被final修饰
3.需要有一个无参的构造器
4.需要给所有属性提供getting/setting方法
已使用 Microsoft OneNote 2016 创建。
