以一个简单的示例说明开发的步骤
1.开发步骤
(1)创建hibernate的配置文件hibernate.cfg.xml
<!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="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property> <property name="hibernate.connection.url">jdbc:mysql://localhost/test_hibernate</property> <property name="hibernate.connection.username">root</property> <property name="hibernate.connection.password">root</property> <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> <property name="hibernate.show_sql">true</property> <mapping resource="edu/study/hibernate/User.hbm.xml"/> </session-factory> </hibernate-configuration>
其中要使用的数据库是test_hibernate。
注意:为了调试的方便,引入log4j.properties配置文件
(2)编写实体类---持久化类User
package edu.study.hibernate; public class User { private int no; private String name; private String password; public int getNo() { return no; } public void setNo(int no) { this.no = no; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
(3)创建持久化类User的映射文件User.hbm.xml
<?xml version="1.0"?> <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd"> <hibernate-mapping> <class name="edu.study.hibernate.User"> <id name="no"> <generator class="native"></generator> </id> <property name="name"></property> <property name="password"></property> </class> </hibernate-mapping>
其中class的name属性值是持久化类:包名+类名,从上可以看出no是主键。
(4)将持久化类的映射文件加入到hibernate的配置文件中
<mapping resource="edu/study/hibernate/User.hbm.xml"/>
即把这句话加入到hibernate.cfg.xml文件中。目的是为了让hibernate能够处理User对象的持久化;resource属性指定了映射文件的位置和名称。
(5)编写hbm2ddl工具类,将实体类生成数据库表-----利用SchemaExport工具类
package edu.study.hibernate; import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; public class ObjTODB { public static void main(String[] args) { //读取配置文件 Configuration cfg=new Configuration().configure(); //创建SchemaExport对象 SchemaExport se=new SchemaExport(cfg); //创建数据库表 se.create(true, true); } }
说明:
SchemaExport:Commandline tool to export table schema to the database.
SchemaExport(Configuration cfg) Create a schema exporter for the given Configuration
void create(boolean script, boolean export) Run the schema creation script.
script
- print the DDL to the console
export
- export the script to the database
(6)开发客户端---将对象保存到数据库中
package edu.study.hibernate; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.cfg.Configuration; public class Client { public static void main(String[] args) { //读取hibernate.cfg.xml文件 Configuration cfg=new Configuration().configure(); //创建SessionFactory SessionFactory sf=cfg.buildSessionFactory(); Session session=null; try { session=sf.openSession(); //开启事务 session.beginTransaction(); User u=new User(); u.setName("admin"); u.setPassword("admin"); session.save(u); //提交事务 session.getTransaction().commit(); } catch (Exception e) { e.printStackTrace(); //事务回滚 session.getTransaction().rollback(); }finally{ if(session!=null){ if(session.isOpen()){ session.close(); } } } } }
说明:
A:Configuration
An instance of Configuration allows the application to specify properties and mapping documents to be used when creating a SessionFactory. Usually an application will create a single Configuration, build a single instance of SessionFactory and then instantiate Sessions in threads servicing client requests. The Configuration is meant only as an initialization-time object. SessionFactorys are immutable and do not retain any association back to the Configuration. A new Configuration will use the properties specified in hibernate.properties by default.
即负责管理hibernate的配置信息,默认使用hibernate.properties文件,但这里Configuration cfg=new Configuration().configure();所以读取的是hibernate.cfg.xml文件。
如果读取hibernate.properties文件,则使用Configuration cfg=new Configuration()即可。
里面有一方法
SessionFactory |
buildSessionFactory() Instantiate a new SessionFactory, using the properties and mappings in this configuration.The SessionFactory will be immutable, so changes made to the Configuration after building the SessionFactory will not affect it. |
B:SessionFactory
Creates Sessions. Usually an application has a single SessionFactory. Threads servicing client requests obtain Sessions from the factory. Implementors must be threadsafe. SessionFactorys are immutable. The behaviour of a SessionFactory is controlled by properties supplied at configuration time. These properties are defined on Environment.
提供会话Session。注意SessionFactory是由Configuration对象创建,因此每个hibernate的配置文件实际上是对SessionFactory的配置。
Session |
openSession() Create database connection and open a Session on it. |
C:Session
是线程不安全的,代表着和数据库的一次操作,由SessionFactory打开,用完后要关闭。