Configuration是hibernate 核心配置文件种类
hibernate.cfg.xml 通常使用xml配置文件,可以配置内容更丰富 <session-factory> <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql:///contacts</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <!-- 方言:为不同的数据库,不同的版本, 生成sql语句(DQL查询语句)提供依据 * mysql 字符串 varchar * orcale 字符串 varchar2 --> <property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect </property> <!--是否显示sql语句 --> <property name="show_sql">true</property> <property name="hibernate.format_sql">true</property> <!-- 自动创建表(了解) ,学习中使用,开发不使用的。 * 取值: update:【】 如果表不存在,将创建表。 如果表已经存在,通过hbm映射文件更新表(添加)。(映射文件必须是数据库对应) 表中的列可以多,不负责删除。 create :如果表存在,先删除,再创建。程序结束时,之前创建的表不删除。【】 create-drop:与create几乎一样。如果factory.close()执行,将在JVM关闭同时,将创建的表删除了。(测试) validate:校验 hbm映射文件 和 表的列是否对应,如果对应正常执行,如果不对应抛出异常。(测试) --> <property name="hbm2ddl.auto">update</property> <!-- 添加映射文件 --> <mapping resource="com/test/hibernate/User.hbm.xml"/> </session-factory>User.hbm.xml
<class name="com.test.hibernate.User" table="user"> <id name="uid" column="id"> <generator class="native"/> </id> <property name="username" column="name"></property> <property name="password" column="pwd"></property> </class> Configuration的其他方法: 通过file创建Configuration对象:new Configuration().configure(file) 通过路径创建Configuration对象: new Configuration().configure(path) 通过代码向Configuation中添加mapping resource :new Configuration().addClass(User.class)SessionFactory线程安全,可以是成员变量,多个线程同时访问时,不会出现线程并发访问问题。
提供api:
//打开一个新的会话 session factory.openSession(); //获得当前线程中绑定的会话session,当事务中有多个数据库操作的时候,需要保证操作数据库的session是 同一个 factory.getCurrentSession();注意:要使用factory.getCurrentSession方法,需要在hibernate.cfg.xml添加一条配置
<!-- 与本地线程绑定 --> <property name=" hibernate.current_session_context_class ">thread</property>