天天看点

Hibernate配置文件笔记

public  class Demo{

<!--创建Configuration实例,并加载对应的配置文件(hibernate.cfg.xml)-->

Configuration config=new Configuration().configure();

<!--通过Configuration获取SessionFactory(获取对应的需要操作的数据库的配置息,是

Hibernate4之前的写法,是与应用程序的生命周期一致,并为每个应用程序服务(在多个线程之间共

享))-->

SessionFactory factory=config.buildSessionFactory();

<!--通过SessionFactory获取Session,即是与数据库的一次交互(仅在一次操作)->

Session session=factory.openSession();

<!--在使用Hibernate时,进行增加,删除,修改的时候需要事务-->

Transaction tx=session.beginTransaction();

<!----创建需要持久化的对象,并设置属性操作>

Person person=new Person();

person.setName("tom");

<!--以Hibernate的方式进行持久化操作-->

session.save(person);

<!--关闭事务-->

tx.commit();

<!--关闭session-->

session.close();

}

//一个重要的配置文件

//自动创建映射表

<hibernate-configuration>

<session-factory>

<!--显示执行sql语句-->

<propery name="show_sql">true</property>

<!--驱动-->

<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>

<!--数据库URL-->

<propery name="hibernate.connection_url">jdbc:mysql:///test</property>

<!--数据库用户名-->

<property name="hibernate.connection.username">root</property>

<!--数据库密码-->

<property name="hibernate.connection.password">123</property>

<!--方言-->

<property name="hibernate_dialect">org.hibernate.dialect.MySQl5InnoDBDialect

</propery>

<!--自动创建表结构-->

<property name="hibernate.hbm2ddl.auto">update</property>

<!--引用对应的持久化类的配置文件-->

<mapping resource="xxx"/>

</session-factory>

</hibernate-configuration>

<!--MySQL不支持事务,MySQLInnoDBDialect支持事务-->

create-drop:在程序启动的时候创建对应数据库表结构,当SessionFactory关闭的时候,表结构删除(测试时使用)

create:在每次程序启动的时候先删除上次创建创建的数据库表结构,然后在创建新的对应的数据库表 结构

update:在每次启动的时候会追加修改表结构,但是不会影响原来的数据(通常使用最多)

validate:在每次启动的时候都会验证并修改表结构

--Hibernate4之后的方式

ServiceRegister sr=new 

ServiceRegistryBuilder().applySettings(cfg.getProperties()).buildServieceRegistry();

SessionFactory factory=new 

cfg.buildSessionFactory(sr);

继续阅读