01、Hibernate 的配置文件
在 Hibernate 的配置文件中,需要指定连接数据库的信息,包括数据库 URL,用户名和口令,JDBC驱动程序等。
hibernate.cfg.xml
<hibernate-configuration> <session-factory > <property name="dialect"> org.hibernate.dialect.MySQL8Dialect </property> <property name="connection.driver_class"> com.mysql.jdbc.Driver </property> <property name="connection.url"> jdbc:mysql://localhost:3306/sampledb?useSSL=false </property> <property name="connection.username"> root </property> <property name="connection.password"> 1234 </property> <!-- 指定是否在运行时在控制台显示执行的SQL语句 --> <property name="show_sql">true</property> <!-- 在启动时删除并重创建数据库Schema --> <property name="hbm2ddl.auto">create</property> <!-- Names the annotated entity class --> <mapping class="mypack.Customer"/> </session-factory></hibernate-configuration>
复制代码
以上配置文件通过元素设定本范例包含 Customer 实体类,Hibernate 在初始化时,会根据这个配置信息去读取 Customer 类的描述对象-关系映射信息的注解,把这些元数据加载到内存中。
02、JPA API 的基本用法
Hibernate API 和 JPA API 中主要接口之间有一些对应关系,例如:
JPA API ----------------------- Hibernate API
EntityManagerFactory ----- SessionFactory
EntityManager ---------------- Session
EntityTransaction ------------- Transaction
SessionFactory 接口在 JPA API 中的对等接口是 javax.persistence.EntityManagerFactory;Session 接口在 JPA API 中的对等接口是 javax.persistence.EntityManager;Transaction 接口在 JPA API 中的对等接口是 javax.persistence.EntityTransaction。Query 接口在 JPA API 中的对等接口是 javax.persistence.Query。
EntityManager 接口提供了操纵数据库的各种方法,如:
(1) persist()方法:把 Java 对象保存到数据库中。等价于 Session 接口的 persist()方法。
(2) merge()方法:保存或更新数据库中的 Java 对象。等价于 Session 接口的 merge()方法。
(3) remove()方法:把特定的 Java 对象从数据库中删除。类似于 Session 接口的 delete()方法。EntityManager 接口的 remove()方法只能删除持久化状态的对象,而 Session 接口的 delete()方法可以删除持久化状态或游离状态的对象。。
(4) find()方法:从数据库中加载 Java 对象。等价于 Session 接口的 get()方法。
下面这个 BusinessService 类通过 JPA API 来访问数据库。
直接上源码。
package mypack; import javax.persistence.EntityManager;import javax.persistence.EntityManagerFactory;import javax.persistence.Persistence;import javax.persistence.EntityTransaction;import javax.persistence.Query;import java.io.*;import java.sql.Date;import java.sql.Timestamp;import java.util.*; public class BusinessService{ public static EntityManagerFactory entityManagerFactory; /** 初始化JPA,创建EntityManagerFactory实例 */ static{ try{ entityManagerFactory= Persistence.createEntityManagerFactory( "myunit" ); }catch(Exception e){ e.printStackTrace(); throw e; } } /** 查询所有的Customer对象, 然后调用printCustomer()方法打印Customer对象信息 */ public void findAllCustomers(PrintWriter out)throws Exception{ EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction tx = null; try { tx = entityManager.getTransaction(); tx.begin(); //开始一个事务 Query query=entityManager.createQuery( "from Customer as c order by c.name asc"); List customers=query.getResultList(); for (Iterator it = customers.iterator(); it.hasNext();) { printCustomer(out,(Customer) it.next()); } tx.commit(); //提交事务 }catch (RuntimeException e) { if (tx != null) { tx.rollback(); } throw e; } finally { entityManager.close(); } } /** 持久化一个Customer对象 */ public void saveCustomer(Customer customer){ EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction tx = null; try { tx = entityManager.getTransaction(); tx.begin(); entityManager.persist(customer); tx.commit(); }catch (RuntimeException e) { if (tx != null) { tx.rollback(); } throw e; } finally { entityManager.close(); } } /** 按照OID加载一个Customer对象,然后修改它的属性 */ public void loadAndUpdateCustomer(Long customer_id,String address){ EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction tx = null; try { tx = entityManager.getTransaction(); tx.begin(); Customer c=entityManager .find(Customer.class,customer_id); c.setAddress(address); tx.commit(); }catch (RuntimeException e) { if (tx != null) { tx.rollback(); } throw e; } finally { entityManager.close(); } } /**删除Customer对象 */ public void deleteCustomer(Customer customer){ EntityManager entityManager = entityManagerFactory.createEntityManager(); EntityTransaction tx = null; try { tx = entityManager.getTransaction(); tx.begin(); //获得持久化状态的Customer对象 Customer c=entityManager .find(Customer.class,customer.getId()); entityManager.remove(c); tx.commit(); }catch (RuntimeException e) { if (tx != null) { tx.rollback(); } throw e; } finally { entityManager.close(); } } /** 把Customer对象的信息输出到控制台,如DOS 控制台*/ private void printCustomer(PrintWriter out,Customer customer) throws Exception{……} public void test(PrintWriter out) throws Exception{……} public static void main(String args[]) throws Exception{ new BusinessService2().test(new PrintWriter(System.out,true)); entityManagerFactory.close(); }}
复制代码
对 JPA 的初始化非常简单,只要通过 javax.persistence.Persistence 的静态方法 createEntityManagerFactory()来创建 EntityManagerFactory 对象:
entityManagerFactory= Persistence.createEntityManagerFactory( "myunit" );
复制代码
以上 Persistence.createEntityManagerFactory( “myunit” )方法中的参数“myunit”指定持久化单元包的名字。JPA 会到 persistence.xml 配置文件中读取相应的持久化单元包中的配置信息。所有访问数据库的操作都使用以下流程:
EntityManager entityManager = entityManagerFactory.createEntityManager();EntityTransaction tx = null;try { tx = entityManager.getTransaction(); tx.begin(); //声明开始事务 //执行查询、保存、更新和删除等各种数据访问操作 …… tx.commit(); //提交事务}catch (RuntimeException e) { if (tx != null) tx.rollback(); throw e;} finally { entityManager.close();}
复制代码
评论