Hibernate是个对象关系框架
使用上以session为核心,一般用框架里面的session工厂来得到session
session工厂则需要configuration来build得到
Configuration configuration = new Configuration();
configuration.configure();
SessionFactory sessionFactory = configuration.buildSessionFactory();
Session session = sessionFactory.openSession();
框架里的工厂是线程安全的, 可以一个系统只build一个工厂
Hibernate XML配置文件
hibernate.cfg.xml
配置文件默认在 CLASSPATH的根目录, 名字则为 hibernate.cfg.xml
里面配置jdbc用到的一些参数
也配置Hibernate的运行特性及持久对象的配置文件
<?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="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://127.0.0.1:3306/mydb</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="show_sql">true</property>
<property name="hbm2ddl.auto">update</property>
<mapping resource="cn/domain/Person.hbm.xml" />
</session-factory>
</hibernate-configuration>
mapping
配置类和表的对应关系
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="cn.domain.Person" table="persons">
<id name="id" type="long">
<generator class="increment"></generator>
</id>
<property name="name" type="string"></property>
<property name="sex" type="string"></property>
</class>
</hibernate-mapping>