一、准备Hibernate环境
- 导入Hibernate必须的jar包:导入hibernate-release-5.0.2.Final\lib\required下的jar包
- 加入数据库驱动的jar包
二、创建持久化Java类
- 提供一个无参的构造器:使Hibernate可以使用Constructor.newInstance() 来实例化持久化类
2.提供一个标识属性(identifier property): 通常映射为数据库表的主键字段. 如果没有该属性,一些功能将不起作用,如:Session.saveOrUpdate()
3. 为类的持久化类字段声明访问方法(get/set): Hibernate对JavaBeans 风格的属性实行持久化。
4. 使用非 final 类: 在运行时生成代理是 Hibernate 的一个重要的功能. 如果持久化类没有实现任何接口, Hibnernate 使用 CGLIB 生成代理. 如果使用的是 final 类, 则无法生成 CGLIB 代理.
5. 重写 eqauls 和 hashCode 方法: 如果需要把持久化类的实例放到 Set 中(当需要进行关联映射时), 则应该重写这两个方法
6.Hibernate 不要求持久化类继承任何父类或实现接口,这可以保证代码不被污染。这就是Hibernate被称为低侵入式设计的原因。
三、创建对象-关系映射文件
1. Hibernate 采用 XML 格式的文件来指定对象和关系数据之间的映射. 在运行时 Hibernate 将根据这个映射文件来生成各种 SQL 语句。
2. 映射文件的扩展名为 .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"> <!-- Generated 2017-11-24 19:16:29 by Hibernate Tools 3.5.0.Final --> <hibernate-mapping> <class name="helloWorld.customer" table="CUSTOMER"> <id name="id" type="java.lang.Integer"> <column name="ID" /> <!-- 指定主键的生成方式, native: 使用数据库本地方式 --> <generator class="native" /> </id> <property name="name" type="java.lang.String"> <column name="NAME" /> </property> <property name="age" type="java.lang.String"> <column name="AGE" /> </property> </class> </hibernate-mapping>
四、创建 Hibernate 配置文件
- Hibernate 从其配置文件中读取和数据库连接的有关信息, 这个文件应该位于应用的 classpath 下.
- 如何查找指定数据库所使用的 SQL 方言:
> 找到并且打开\hibernate-release-5.2.12.Final\project\etc目录下的 hibernate.properties文件,在这里我选择的是图中的指定项
## MySQL
#hibernate.dialect org.hibernate.dialect.MySQLDialect
#hibernate.dialect org.hibernate.dialect.MySQLInnoDBDialect
#hibernate.dialect org.hibernate.dialect.MySQLMyISAMDialect
#hibernate.connection.driver_class com.mysql.jdbc.Driver
#hibernate.connection.url jdbc:mysql:///test
#hibernate.connection.username gavin
#hibernate.connection.password
## Oracle
#hibernate.dialect org.hibernate.dialect.Oracle8iDialect
#hibernate.dialect org.hibernate.dialect.Oracle9iDialect
#hibernate.dialect org.hibernate.dialect.Oracle10gDialect
#hibernate.connection.driver_class oracle.jdbc.driver.OracleDriver
#hibernate.connection.username ora
#hibernate.connection.password ora
#hibernate.connection.url jdbc:oracle:thin:@localhost:1521:orcl
#hibernate.connection.url jdbc:oracle:thin:@localhost:1522:XE
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- 配置连接数据库的基本信息 --> <property name="connection.username">root</property> <property name="connection.password">ds756953242</property> <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <property name="connection.url">jdbc:mysql:///hibernate</property> <!-- 配置 hibernate 的基本信息 --> <!-- hibernate 所使用的数据库方言 <property name="dialect">org.hibernate.dialect.MySQLMyISAMDialect</property> <property name="dialect">org.hibernate.dialect.MySQLDialect</property> --> <property name="dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property> <!-- 执行操作时是否在控制台打印 SQL --> <property name="show_sql">true</property> <!-- 是否对 SQL 进行格式化 --> <property name="format_sql">true</property> <!-- 指定自动生成数据表的策略 --> <property name="hbm2ddl.auto">update</property> <!-- 指定关联的 .hbm.xml 文件 --> <mapping resource="helloWorld/customer.hbm.xml"/> </session-factory> </hibernate-configuration>
五、通过 Hibernate API 编写访问数据库的代码
//1. 创建一个 SessionFactory 对象 ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder().configure().build(); SessionFactory sessionFactory = new MetadataSources(serviceRegistry) .buildMetadata().buildSessionFactory(); //2. 创建一个 Session 对象 Session session = sessionFactory.openSession(); //3. 开启事务 Transaction transaction = session.beginTransaction(); customer s = new customer("55", "小红"); //4. 执行保存操作 session.save(s); //5. 提交事务 transaction.commit(); //6. 关闭 Session session.close(); //7. 关闭 SessionFactory 对象 sessionFactory.close();
六、此过程中出现的两个错误
- org.hibernate.tool.schema.spi.SchemaManagementException: Unable to execute schema management to JDBC target [create table CUSTOMER (ID integer not null auto_increment, NAME varchar(255), AGE varchar(255), primary key (ID)) type=InnoDB]
这个错误主要是所使用方言方面的错误,如果用的mysql版本是5.5版本以上的就需要把org.hibernate.dialect.MySQLInnoDBDialect改为org.hibernate.dialect.MySQL5InnoDBDialect才能用,或者直接使用org.hibernate.dialect.MySQLDialect,用了之后就可以成功建表了,如果没改的话就需要手动建对应的表。
2. org.hibernate.MappingException: Unknown entity: helloWorld.customer
这个错误主要是创建SessionFactory时错误,如果用的Hibernate时5.0版本以上的话就需要这样创建按照 五 中的代码那样创建。
// Configuration config = new Configuration().configure(); // //区别之处 // ServiceRegistry serviceRegistry = new ServiceRegistryBuilder() // .applySettings(config.getProperties()).buildServiceRegistry(); // // SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); // Session session = sessionFactory.openSession(); // Transaction transaction = session.beginTransaction(); // Student s = new Student(1, "小明"); // session.save(s); // transaction.commit();
这个版本是之前Hibernate4.14的时候可以用的,到了Hibernate5之后就会出现代码错误,因为4.1.2中的ServiceRegistryBuilder类在5.0.2中被删除了,取而代之的是StandardServiceRegistryBuilder。
// Configuration config = new Configuration().configure(); // //区别之处 // ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder() // .applySettings(config.getProperties()).build(); // // SessionFactory sessionFactory = config.buildSessionFactory(serviceRegistry); // Session session = sessionFactory.openSession(); // Transaction transaction = session.beginTransaction(); // customer s = new customer("小明", "12"); // session.save(s);
这个版本不会出现代码错误,但是跑的时候就会出现org.hibernate.MappingException: Unknown entity: helloWorld.customer错误。