配套資料,免費下載
連接:https://pan.baidu.com/s/158JkczSacADez-fEMDXSYQ
提取碼:2ce1
複製這段內容後打開百度網盤手機App,操做更方便哦java
JPA的全稱是Java Persistence API, 即Java 持久化API,是SUN公司推出的一套基於ORM的規範,內部是由一系列的接口和抽象類構成。JPA經過JDK 5.0註解描述對象-關係表的映射關係,並將運行期的實體對象持久化到數據庫中mysql
可是JPA僅僅只是一套接口規範和抽象類,並不能真正的去幹活,所以,就有不少廠商實現了JPA的規範,提供了相應的技術支持,就相似實現了JDBC的MySQL驅動,而本節課程將採用Hibernate實現做爲驅動使用,所以我稱之爲Hibernate5 JPAsql
官方網址:hibernate orm數據庫
目錄介紹:數組
hibernate-release-5.0.7.Final文件夾介紹:網絡
hibernate-release-5.0.7.Final\lib文件夾介紹:session
前邊學習的Hibernate,接下來進行工程搭建,根Hibernate相比,它只須要再多加入一個包就行oracle
把下面四個文件夾的內容所有拷貝到lib中app
把下面五個文件夾的內容所有拷貝到lib中後,所有選中,右鍵Build Path一下分佈式
Java工程搭建好了之後,咱們須要有一個數據庫(hibernate_jpa)和兩張表用於測試:
crm_cst_customer(客戶表)
CREATE TABLE `cst_customer` ( `cust_id` BIGINT(32) NOT NULL AUTO_INCREMENT COMMENT '客戶編號(主鍵)', `cust_name` VARCHAR(32) DEFAULT NULL COMMENT '客戶名稱', `cust_source` VARCHAR(32) DEFAULT NULL COMMENT '客戶信息來源', `cust_industry` VARCHAR(32) DEFAULT NULL COMMENT '客戶所屬行業', `cust_level` VARCHAR(32) DEFAULT NULL COMMENT '客戶級別', `cust_phone` VARCHAR(64) DEFAULT NULL COMMENT '固定電話', `cust_mobile` VARCHAR(16) DEFAULT NULL COMMENT '移動電話', PRIMARY KEY (`cust_id`) ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
crm_cst_linkman(聯繫人表)
CREATE TABLE `cst_linkman` ( `lkm_id` BIGINT(32) NOT NULL AUTO_INCREMENT COMMENT '聯繫人編號(主鍵)', `lkm_name` VARCHAR(16) DEFAULT NULL COMMENT '聯繫人姓名', `lkm_gender` CHAR(1) DEFAULT NULL COMMENT '聯繫人性別', `lkm_phone` VARCHAR(16) DEFAULT NULL COMMENT '聯繫人辦公電話', `lkm_mobile` VARCHAR(16) DEFAULT NULL COMMENT '聯繫人手機', `lkm_email` VARCHAR(64) DEFAULT NULL COMMENT '聯繫人郵箱', `lkm_qq` VARCHAR(16) DEFAULT NULL COMMENT '聯繫人qq', `lkm_position` VARCHAR(16) DEFAULT NULL COMMENT '聯繫人職位', `lkm_memo` VARCHAR(512) DEFAULT NULL COMMENT '聯繫人備註', `lkm_cust_id` BIGINT(32) NOT NULL COMMENT '客戶id', PRIMARY KEY (`lkm_id`), KEY `FK_cst_linkman_lkm_cust_id` (`lkm_cust_id`), CONSTRAINT `FK_cst_linkman_lkm_cust_id` FOREIGN KEY (`lkm_cust_id`) REFERENCES `cst_customer` (`cust_id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;
在Java工程的src路徑下建立一個名爲META-INF的文件夾,在此文件夾下建立一個名爲persistence.xml的配置文件
通用配置文件(掌握):
persistence.xml(全路徑:/hibernate_jpa/src/META-INF/persistence.xml)
<?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0"> <!-- 配置持久化單元 * name :持久化單元名稱 * transaction-type :持久化單元事務類型 JTA :開啓JTA分佈式事務 RESOURCE_LOCAL :開啓本地事務 --> <persistence-unit name="myJpa" transaction-type="RESOURCE_LOCAL"> <!-- 配置JPA服務提供商 --> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <!-- 配置JPA的基本參數 --> <properties> <!-- 配置數據庫驅動 --> <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" /> <!-- 配置數據庫地址 --> <property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/hibernate_jpa" /> <!-- 配置數據庫帳戶 --> <property name="javax.persistence.jdbc.user" value="root" /> <!-- 配置數據庫密碼 --> <property name="javax.persistence.jdbc.password" value="root" /> <!-- 配置JPA服務提供商可選參數 --> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.format_sql" value="true" /> <property name="hibernate.hbm2ddl.auto" value="create" /> </properties> </persistence-unit> </persistence>
整合C3P0鏈接池版本配置文件(瞭解):
<?xml version="1.0" encoding="UTF-8"?> <persistence xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd" version="2.0"> <!-- 配置持久化單元 * name :持久化單元名稱 * transaction-type :持久化單元事務類型 JTA :開啓JTA分佈式事務 RESOURCE_LOCAL :開啓本地事務 --> <persistence-unit name="myJpa" transaction-type="RESOURCE_LOCAL"> <!-- 配置JPA服務提供商 --> <provider>org.hibernate.jpa.HibernatePersistenceProvider</provider> <!-- 配置JPA的基本參數 --> <properties> <!-- Hibernate JPA基本配置 --> <property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" /> <property name="hibernate.connection.url" value="jdbc:mysql://127.0.0.1:3306/hibernate_jpa" /> <property name="hibernate.connection.username" value="root" /> <property name="hibernate.connection.password" value="root" /> <property name="hibernate.connection.isolation" value="4" /> <property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" /> <property name="hibernate.current_session_context_class" value="thread" /> <!-- Hibernate JPA可選配置 --> <property name="hibernate.show_sql" value="true" /> <property name="hibernate.format_sql" value="true" /> <property name="hibernate.hbm2ddl.auto" value="create" /> <!-- Hibernate JPA整合C3P0數據庫鏈接池 --> <property name="hibernate.connection.provider_class" value="org.hibernate.connection.C3P0ConnectionProvider" /> <!-- 數據庫鏈接池的最小鏈接數 --> <property name="c3p0.min_size" value="5" /> <!-- 數據庫鏈接池的最大鏈接數 --> <property name="c3p0.max_size" value="30" /> <!-- 最大空閒時間,60秒內未使用則鏈接被丟棄。若爲0則永不丟棄。Default: 0 --> <property name="c3p0.maxIdleTime" value="60" /> <!-- 得到鏈接的超時時間,若是超過這個時間,會拋出異常,單位毫秒 --> <property name="c3p0.timeout" value="1800" /> <!-- 最大的PreparedStatement的數量 --> <property name="c3p0.max_statements" value="50" /> <!-- 每隔120秒檢查鏈接池裏的空閒鏈接,單位是秒 --> <property name="c3p0.idle_test_period" value="120" /> <!-- 當鏈接池裏面的鏈接用完的時候,C3P0一下獲取的新的鏈接數 --> <property name="c3p0.acquire_increment" value="1" /> <!-- 是否每次都驗證鏈接是否可用 --> <property name="c3p0.validate" value="false" /> </properties> </persistence-unit> </persistence>
對於本節課程來講,使用哪個均可以,可是第一個更通用,更簡單,咱們採用第一個,配置文件有了之後,咱們須要編寫實體類跟數據庫表的映射關係
Customer.java(全路徑:/hibernate_jpa/src/com/caochenlei/hibernate/jpa/Customer.java)
package com.caochenlei.hibernate.jpa; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Table; /** * @Entity :聲明是一個實體類 * @Table :配置實體類和表的映射關係 * * name :配置數據庫表的名稱 */ @Entity @Table(name = "cst_customer") public class Customer { /** * @Id :聲明主鍵的配置 * @GeneratedValue :配置主鍵的生成策略 * strategy: * GenerationType.IDENTITY :自增(底層數據庫必須支持自動增加),mysql * GenerationType.SEQUENCE :序列(底層數據庫必須支持序列),oracle * GenerationType.TABLE :JPA提供的一種機制,經過一張數據庫表的形式幫助咱們完成主鍵自增 * GenerationType.AUTO :由程序自動的幫助咱們選擇主鍵生成策略 * @Column :配置屬性和字段的映射關係 * name :數據庫表中字段的名稱 */ @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "cust_id") private Long custId; @Column(name = "cust_name") private String custName; @Column(name = "cust_source") private String custSource; @Column(name = "cust_industry") private String custIndustry; @Column(name = "cust_level") private String custLevel; @Column(name = "cust_phone") private String custPhone; @Column(name = "cust_mobile") private String custMobile; public Long getCustId() { return custId; } public void setCustId(Long custId) { this.custId = custId; } public String getCustName() { return custName; } public void setCustName(String custName) { this.custName = custName; } public String getCustSource() { return custSource; } public void setCustSource(String custSource) { this.custSource = custSource; } public String getCustIndustry() { return custIndustry; } public void setCustIndustry(String custIndustry) { this.custIndustry = custIndustry; } public String getCustLevel() { return custLevel; } public void setCustLevel(String custLevel) { this.custLevel = custLevel; } public String getCustPhone() { return custPhone; } public void setCustPhone(String custPhone) { this.custPhone = custPhone; } public String getCustMobile() { return custMobile; } public void setCustMobile(String custMobile) { this.custMobile = custMobile; } @Override public String toString() { return "Customer [custId=" + custId + ", custName=" + custName + ", custSource=" + custSource + ", custIndustry=" + custIndustry + ", custLevel=" + custLevel + ", custPhone=" + custPhone + ", custMobile=" + custMobile + "]"; } }
LinkMan.java(全路徑:/hibernate_jpa/src/com/caochenlei/hibernate/jpa/LinkMan.java)
package com.caochenlei.hibernate.jpa; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; @Entity @Table(name = "cst_linkman") public class LinkMan { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "lkm_id") private Long lkmId; @Column(name = "lkm_name") private String lkmName; @Column(name = "lkm_gender") private String lkmGender; @Column(name = "lkm_phone") private String lkmPhone; @Column(name = "lkm_mobile") private String lkmMobile; @Column(name = "lkm_email") private String lkmEmail; @Column(name = "lkm_qq") private String lkmQq; @Column(name = "lkm_position") private String lkmPosition; @Column(name = "lkm_memo") private String lkmMemo; public Long getLkmId() { return lkmId; } public void setLkmId(Long lkmId) { this.lkmId = lkmId; } public String getLkmName() { return lkmName; } public void setLkmName(String lkmName) { this.lkmName = lkmName; } public String getLkmGender() { return lkmGender; } public void setLkmGender(String lkmGender) { this.lkmGender = lkmGender; } public String getLkmPhone() { return lkmPhone; } public void setLkmPhone(String lkmPhone) { this.lkmPhone = lkmPhone; } public String getLkmMobile() { return lkmMobile; } public void setLkmMobile(String lkmMobile) { this.lkmMobile = lkmMobile; } public String getLkmEmail() { return lkmEmail; } public void setLkmEmail(String lkmEmail) { this.lkmEmail = lkmEmail; } public String getLkmQq() { return lkmQq; } public void setLkmQq(String lkmQq) { this.lkmQq = lkmQq; } public String getLkmPosition() { return lkmPosition; } public void setLkmPosition(String lkmPosition) { this.lkmPosition = lkmPosition; } public String getLkmMemo() { return lkmMemo; } public void setLkmMemo(String lkmMemo) { this.lkmMemo = lkmMemo; } @Override public String toString() { return "LinkMan [lkmId=" + lkmId + ", lkmName=" + lkmName + ", lkmGender=" + lkmGender + ", lkmPhone=" + lkmPhone + ", lkmMobile=" + lkmMobile + ", lkmEmail=" + lkmEmail + ", lkmQq=" + lkmQq + ", lkmPosition=" + lkmPosition + ", lkmMemo=" + lkmMemo + "]"; } }
CustomerJPATest.java(全路徑:/hibernate_jpa/src/com/caochenlei/hibernate/jpa/CustomerJPATest.java)
package com.caochenlei.hibernate.jpa; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.EntityTransaction; import javax.persistence.Persistence; import org.junit.Test; public class CustomerJPATest { /** * 運行以前,修改hibernate.hbm2ddl.auto=create * 保存操做 */ @Test public void testSave() { // 獲取實體管理器工廠 EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("myJpa"); // 獲取實體管理器 EntityManager entityManager = entityManagerFactory.createEntityManager(); // 獲取事務 EntityTransaction transaction = entityManager.getTransaction(); // 開啓事務 transaction.begin(); // 建立實體對象並保存 Customer customer1 = new Customer(); customer1.setCustName("張三"); entityManager.persist(customer1); Customer customer2 = new Customer(); customer2.setCustName("李四"); entityManager.persist(customer2); Customer customer3 = new Customer(); customer3.setCustName("王五"); entityManager.persist(customer3); // 提交事務 transaction.commit(); // 釋放資源 entityManager.close(); entityManagerFactory.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 當即查詢操做 */ @Test public void testQuery1() { // 獲取實體管理器工廠 EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("myJpa"); // 獲取實體管理器 EntityManager entityManager = entityManagerFactory.createEntityManager(); // 獲取事務 EntityTransaction transaction = entityManager.getTransaction(); // 開啓事務 transaction.begin(); // 查詢實體並輸出 Customer customer = entityManager.find(Customer.class, 2L); System.out.println(customer); // 提交事務 transaction.commit(); // 釋放資源 entityManager.close(); entityManagerFactory.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 延遲查詢操做 */ @Test public void testQuery2() { // 獲取實體管理器工廠 EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("myJpa"); // 獲取實體管理器 EntityManager entityManager = entityManagerFactory.createEntityManager(); // 獲取事務 EntityTransaction transaction = entityManager.getTransaction(); // 開啓事務 transaction.begin(); // 查詢實體並輸出 Customer customer = entityManager.getReference(Customer.class, 2L); System.out.println(customer); // 提交事務 transaction.commit(); // 釋放資源 entityManager.close(); entityManagerFactory.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 刪除操做 */ @Test public void testDelete() { // 獲取實體管理器工廠 EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("myJpa"); // 獲取實體管理器 EntityManager entityManager = entityManagerFactory.createEntityManager(); // 獲取事務 EntityTransaction transaction = entityManager.getTransaction(); // 開啓事務 transaction.begin(); // 查詢實體並刪除 Customer customer = entityManager.find(Customer.class, 1L); entityManager.remove(customer); // 提交事務 transaction.commit(); // 釋放資源 entityManager.close(); entityManagerFactory.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 更新操做 */ @Test public void testUpdate() { // 獲取實體管理器工廠 EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("myJpa"); // 獲取實體管理器 EntityManager entityManager = entityManagerFactory.createEntityManager(); // 獲取事務 EntityTransaction transaction = entityManager.getTransaction(); // 開啓事務 transaction.begin(); // 查詢實體並更新 Customer customer = entityManager.find(Customer.class, 2L); customer.setCustSource("電視廣告"); entityManager.merge(customer); // 提交事務 transaction.commit(); // 釋放資源 entityManager.close(); entityManagerFactory.close(); } }
JPAUtil.java(全路徑:/hibernate_jpa/src/com/caochenlei/hibernate/jpa/JPAUtil.java)
package com.caochenlei.hibernate.jpa; import javax.persistence.EntityManager; import javax.persistence.EntityManagerFactory; import javax.persistence.Persistence; public class JPAUtil { private static EntityManagerFactory entityManagerFactory; static { entityManagerFactory = Persistence.createEntityManagerFactory("myJpa"); } public static EntityManager getEntityManager() { return entityManagerFactory.createEntityManager(); } }
Persistence對象主要做用是用於獲取EntityManagerFactory對象的 。經過調用該類的createEntityManagerFactory靜態方法,根據配置文件中持久化單元名稱建立EntityManagerFactory。
EntityManagerFactory 接口主要用來建立 EntityManager 實例。
在 JPA 規範中,EntityManager是完成持久化操做的核心對象。實體類做爲普通 java對象,只有在調用 EntityManager將其持久化後纔會變成持久化對象。EntityManager對象在一組實體類與底層數據源之間進行 O/R 映射的管理。它能夠用來管理和更新 Entity Bean,根椐主鍵查找 Entity Bean, 還能夠經過JPQL語句查詢實體。咱們能夠經過調用EntityManager的方法完成獲取事務,以及持久化數據庫的操做,例如:
在 JPA 規範中,EntityTransaction是完成事務操做的核心對象,對於EntityTransaction在咱們的Java代碼中承接的功能比較簡單。
修改Customer.java(全路徑:/hibernate_jpa/src/com/caochenlei/hibernate/jpa/Customer.java)
在toString方法的下面添加多的集合
/** * 一對多:一的一方配置多的集合 * @OneToMany :映射一對多 * * fetch :抓取策略 * FetchType.LAZY :延遲加載(默認) * FetchType.EAGER :迫切查詢(多表鏈接查詢) * * cascade :級聯操做 * CascadeType.PERSIST :級聯保存 * CascadeType.MERGE :級聯更新 * CascadeType.REMOVE :級聯刪除 * CascadeType.ALL :所有支持 * * mappedBy :放棄外鍵維護 */ @OneToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "customer") private Set<LinkMan> linkMans = new HashSet<LinkMan>(); public Set<LinkMan> getLinkMans() { return linkMans; } public void setLinkMans(Set<LinkMan> linkMans) { this.linkMans = linkMans; }
修改LinkMan.java(全路徑:/hibernate_jpa/src/com/caochenlei/hibernate/jpa/LinkMan.java)
在toString方法的下面添加一的對象
/** * 多對一:多的一方配置一的對象 * @ManyToOne :映射多對一 * * fetch :抓取策略 * FetchType.LAZY :延遲加載(默認) * FetchType.EAGER :迫切查詢(多表鏈接查詢) * * cascade :級聯操做 * CascadeType.PERSIST :級聯保存 * CascadeType.MERGE :級聯更新 * CascadeType.REMOVE :級聯刪除 * CascadeType.ALL :所有支持 * @JoinColumn :設置兩張表之間外鍵列 * name ;外鍵的名稱 */ @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinColumn(name = "lkm_cust_id") private Customer customer = new Customer(); public Customer getCustomer() { return customer; } public void setCustomer(Customer customer) { this.customer = customer; }
OneToManyTest.java(全路徑:/hibernate_jpa/src/com/caochenlei/hibernate/jpa/OneToManyTest.java)
package com.caochenlei.hibernate.jpa; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import org.junit.Test; public class OneToManyTest { /** * 運行以前,修改hibernate.hbm2ddl.auto=create * 保存客戶級聯保存聯繫人 */ @Test public void test1() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); // 建立兩個客戶 Customer customer1 = new Customer(); customer1.setCustName("張三"); Customer customer2 = new Customer(); customer2.setCustName("李四"); // 建立三個聯繫人 LinkMan linkMan1 = new LinkMan(); linkMan1.setLkmName("鳳姐"); LinkMan linkMan2 = new LinkMan(); linkMan2.setLkmName("如花"); LinkMan linkMan3 = new LinkMan(); linkMan3.setLkmName("旺財"); customer1.getLinkMans().add(linkMan1); customer1.getLinkMans().add(linkMan2); customer2.getLinkMans().add(linkMan3); linkMan1.setCustomer(customer1); linkMan2.setCustomer(customer1); linkMan3.setCustomer(customer2); entityManager.persist(customer1); entityManager.persist(customer2); transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=create * 保存聯繫人級聯保存客戶 */ @Test public void test2() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); // 建立兩個客戶 Customer customer1 = new Customer(); customer1.setCustName("張三"); Customer customer2 = new Customer(); customer2.setCustName("李四"); // 建立三個聯繫人 LinkMan linkMan1 = new LinkMan(); linkMan1.setLkmName("鳳姐"); LinkMan linkMan2 = new LinkMan(); linkMan2.setLkmName("如花"); LinkMan linkMan3 = new LinkMan(); linkMan3.setLkmName("旺財"); customer1.getLinkMans().add(linkMan1); customer1.getLinkMans().add(linkMan2); customer2.getLinkMans().add(linkMan3); linkMan1.setCustomer(customer1); linkMan2.setCustomer(customer1); linkMan3.setCustomer(customer2); entityManager.persist(linkMan1); entityManager.persist(linkMan2); entityManager.persist(linkMan3); transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 查詢客戶級聯查詢聯繫人 */ @Test public void test3() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); Customer customer = entityManager.find(Customer.class, 1L); System.out.println(customer); Set<LinkMan> linkMans = customer.getLinkMans(); for (LinkMan linkMan : linkMans) { System.out.println(linkMan); } transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 查詢聯繫人級聯查詢客戶 */ @Test public void test4() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); LinkMan linkMan = entityManager.find(LinkMan.class, 1L); System.out.println(linkMan); Customer customer = linkMan.getCustomer(); System.out.println(customer); transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 修改客戶、修改聯繫人,保存客戶級聯保存聯繫人 */ @Test public void test5() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); Customer customer = entityManager.find(Customer.class, 1L); customer.setCustSource("電視廣告"); Set<LinkMan> linkMans = customer.getLinkMans(); for (LinkMan linkMan : linkMans) { linkMan.setLkmMobile("15633029014"); } entityManager.persist(customer); transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 修改客戶、修改聯繫人,保存聯繫人級聯保存客戶 */ @Test public void test6() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); LinkMan linkMan = entityManager.find(LinkMan.class, 1L); linkMan.setLkmMobile("110"); Customer customer = linkMan.getCustomer(); customer.setCustMobile("110"); entityManager.persist(linkMan); transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 刪除客戶級聯刪除聯繫人 */ @Test public void test7() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); Customer customer = entityManager.find(Customer.class, 1L); entityManager.remove(customer); transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 刪除聯繫人級聯刪除客戶 */ @Test public void test8() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); LinkMan linkMan = entityManager.find(LinkMan.class, 3L); entityManager.remove(linkMan); transaction.commit(); entityManager.close(); } }
sys_user(用戶表)
CREATE TABLE `sys_user` ( `user_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '用戶id', `user_code` varchar(32) DEFAULT NULL COMMENT '用戶帳號', `user_name` varchar(64) DEFAULT NULL COMMENT '用戶名稱', `user_password` varchar(32) DEFAULT NULL COMMENT '用戶密碼', `user_state` char(1) DEFAULT NULL COMMENT '用戶狀態', PRIMARY KEY (`user_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
sys_role(角色表)
CREATE TABLE `sys_role` ( `role_id` bigint(32) NOT NULL AUTO_INCREMENT COMMENT '角色id', `role_name` varchar(32) DEFAULT NULL COMMENT '角色名稱', `role_memo` varchar(128) DEFAULT NULL COMMENT '角色備註', PRIMARY KEY (`role_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
sys_user_role(中間表)
CREATE TABLE `sys_user_role` ( `role_id` bigint(32) NOT NULL COMMENT '角色id', `user_id` bigint(32) NOT NULL COMMENT '用戶id', PRIMARY KEY (`role_id`,`user_id`), KEY `FK_user_role_user_id` (`user_id`), CONSTRAINT `FK_user_role_role_id` FOREIGN KEY (`role_id`) REFERENCES `sys_role` (`role_id`) ON DELETE NO ACTION ON UPDATE NO ACTION, CONSTRAINT `FK_user_role_user_id` FOREIGN KEY (`user_id`) REFERENCES `sys_user` (`user_id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
User.java(全路徑:/hibernate_jpa/src/com/caochenlei/hibernate/jpa/User.java)
package com.caochenlei.hibernate.jpa; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name = "sys_user") public class User { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "user_id") private Long userId; @Column(name = "user_code") private String userCode; @Column(name = "user_name") private String userName; @Column(name = "user_password") private String userPassword; @Column(name = "user_state") private String userState; public Long getUserId() { return userId; } public void setUserId(Long userId) { this.userId = userId; } public String getUserCode() { return userCode; } public void setUserCode(String userCode) { this.userCode = userCode; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName; } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword; } public String getUserState() { return userState; } public void setUserState(String userState) { this.userState = userState; } @Override public String toString() { return "User [userId=" + userId + ", userCode=" + userCode + ", userName=" + userName + ", userPassword=" + userPassword + ", userState=" + userState + "]"; } /** * 多對多:另外一方的集合對象 * @ManyToMany :映射多對多 * * fetch :抓取策略 * FetchType.LAZY :延遲加載(默認) * FetchType.EAGER :迫切查詢(多表鏈接查詢) * * cascade :級聯操做 * CascadeType.PERSIST :級聯保存 * CascadeType.MERGE :級聯更新 * CascadeType.REMOVE :級聯刪除 * CascadeType.ALL :所有支持 * @JoinTable :用於對應中間表的設置 * * name :中間表名稱 * * joinColumns :設置中間表與本表關聯的外鍵 * * inverseJoinColumns:設置中間表與關聯表對應的外鍵 */ @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinTable(name = "sys_user_role", joinColumns = @JoinColumn(name = "user_id"), inverseJoinColumns = @JoinColumn(name = "role_id")) private Set<Role> roles = new HashSet<Role>(); public Set<Role> getRoles() { return roles; } public void setRoles(Set<Role> roles) { this.roles = roles; } }
Role.java(全路徑:/hibernate_jpa/src/com/caochenlei/hibernate/jpa/Role.java)
package com.caochenlei.hibernate.jpa; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.ManyToMany; import javax.persistence.Table; @Entity @Table(name = "sys_role") public class Role { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "role_id") private Long roleId; @Column(name = "role_name") private String roleName; @Column(name = "role_memo") private String roleMemo; public Long getRoleId() { return roleId; } public void setRoleId(Long roleId) { this.roleId = roleId; } public String getRoleName() { return roleName; } public void setRoleName(String roleName) { this.roleName = roleName; } public String getRoleMemo() { return roleMemo; } public void setRoleMemo(String roleMemo) { this.roleMemo = roleMemo; } @Override public String toString() { return "Role [roleId=" + roleId + ", roleName=" + roleName + ", roleMemo=" + roleMemo + "]"; } /** * 多對多:另外一方的集合對象 * @ManyToMany :映射多對多 * * fetch :抓取策略 * FetchType.LAZY :延遲加載(默認) * FetchType.EAGER :迫切查詢(多表鏈接查詢) * * cascade :級聯操做 * CascadeType.PERSIST :級聯保存 * CascadeType.MERGE :級聯更新 * CascadeType.REMOVE :級聯刪除 * CascadeType.ALL :所有支持 * * mappedBy :放棄外鍵維護 */ @ManyToMany(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "roles") private Set<User> users = new HashSet<User>(); public Set<User> getUsers() { return users; } public void setUsers(Set<User> users) { this.users = users; } }
ManyToManyTest.java(全路徑:/hibernate_jpa/src/com/caochenlei/hibernate/jpa/ManyToManyTest.java)
package com.caochenlei.hibernate.jpa; import java.util.Set; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import org.junit.Test; public class ManyToManyTest { /** * 運行以前,修改hibernate.hbm2ddl.auto=create * 保存用戶級聯保存角色 */ @Test public void test1() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); // 建立兩個用戶 User user1 = new User(); user1.setUserName("曹晨磊"); User user2 = new User(); user2.setUserName("曹晨旭"); // 建立三個角色 Role role1 = new Role(); role1.setRoleName("呂布"); Role role2 = new Role(); role2.setRoleName("東皇"); Role role3 = new Role(); role3.setRoleName("趙雲"); user1.getRoles().add(role1); user1.getRoles().add(role2); user2.getRoles().add(role3); role1.getUsers().add(user1); role2.getUsers().add(user1); role3.getUsers().add(user2); entityManager.persist(user1); entityManager.persist(user2); transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=create * 保存角色級聯保存用戶 */ @Test public void test2() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); // 建立兩個用戶 User user1 = new User(); user1.setUserName("曹晨磊"); User user2 = new User(); user2.setUserName("曹晨旭"); // 建立三個角色 Role role1 = new Role(); role1.setRoleName("呂布"); Role role2 = new Role(); role2.setRoleName("東皇"); Role role3 = new Role(); role3.setRoleName("趙雲"); user1.getRoles().add(role1); user1.getRoles().add(role2); user2.getRoles().add(role3); role1.getUsers().add(user1); role2.getUsers().add(user1); role3.getUsers().add(user2); entityManager.persist(role1); entityManager.persist(role2); entityManager.persist(role3); transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 查詢用戶級聯查詢角色 */ @Test public void test3() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); User user = entityManager.find(User.class, 1L); System.out.println(user); Set<Role> roles = user.getRoles(); for (Role role : roles) { System.out.println(role); } transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 查詢角色級聯查詢用戶 */ @Test public void test4() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); Role role = entityManager.find(Role.class, 3L); System.out.println(role); Set<User> users = role.getUsers(); for (User user : users) { System.out.println(user); } transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 修改用戶、修改角色,更新用戶級聯更新角色 */ @Test public void test5() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); User user = entityManager.find(User.class, 1L); user.setUserPassword("123456"); Set<Role> roles = user.getRoles(); for (Role role : roles) { role.setRoleMemo("123456"); } entityManager.merge(user); transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 修改用戶、修改角色,更新角色級聯更新用戶 */ @Test public void test6() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); Role role = entityManager.find(Role.class, 3L); role.setRoleMemo("123456"); Set<User> users = role.getUsers(); for (User user : users) { user.setUserPassword("123456"); } entityManager.merge(role); transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 刪除用戶級聯刪除角色 */ @Test public void test7() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); User user = entityManager.find(User.class, 1L); entityManager.remove(user); transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 刪除角色級聯刪除用戶 */ @Test public void test8() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); Role role = entityManager.find(Role.class, 3L); entityManager.remove(role); transaction.commit(); entityManager.close(); } }
student_base_info(學生信息基本表)
CREATE TABLE `student_base_info` ( `stu_id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '學生id', `stu_name` varchar(20) DEFAULT NULL COMMENT '學生姓名', `stu_sex` varchar(20) DEFAULT NULL COMMENT '學生性別', PRIMARY KEY (`stu_id`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
student_other_info(學生信息拓展表)
CREATE TABLE `student_other_info` ( `stu_id` bigint(20) NOT NULL COMMENT '學生id', `stu_img` varchar(255) DEFAULT NULL COMMENT '學生頭像', `stu_address` varchar(255) DEFAULT NULL COMMENT '學生地址', PRIMARY KEY (`stu_id`), CONSTRAINT `FK_stu_id` FOREIGN KEY (`stu_id`) REFERENCES `student_base_info` (`stu_id`) ON DELETE NO ACTION ON UPDATE NO ACTION ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
StuBaseInfo.java(全路徑:/hibernate_jpa/src/com/caochenlei/hibernate/jpa/StuBaseInfo.java)
package com.caochenlei.hibernate.jpa; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "student_base_info") public class StuBaseInfo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "stu_id") private Long stuId; @Column(name = "stu_name") private String stuName; @Column(name = "stu_sex") private String stuSex; public Long getStuId() { return stuId; } public void setStuId(Long stuId) { this.stuId = stuId; } public String getStuName() { return stuName; } public void setStuName(String stuName) { this.stuName = stuName; } public String getStuSex() { return stuSex; } public void setStuSex(String stuSex) { this.stuSex = stuSex; } @Override public String toString() { return "StuBaseInfo [stuId=" + stuId + ", stuName=" + stuName + ", stuSex=" + stuSex + "]"; } /** * 一對一:另外一方的對象 * @OneToOne :映射一對一 * * fetch :抓取策略 * FetchType.LAZY :延遲加載(默認) * FetchType.EAGER :迫切查詢(多表鏈接查詢) * * cascade :級聯操做 * CascadeType.PERSIST :級聯保存 * CascadeType.MERGE :級聯更新 * CascadeType.REMOVE :級聯刪除 * CascadeType.ALL :所有支持 * * mappedBy :放棄外鍵維護 */ @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, mappedBy = "stuBaseInfo") private StuOtherInfo stuOtherInfo; public StuOtherInfo getStuOtherInfo() { return stuOtherInfo; } public void setStuOtherInfo(StuOtherInfo stuOtherInfo) { this.stuOtherInfo = stuOtherInfo; } }
StuOtherInfo.java(全路徑:/hibernate_jpa/src/com/caochenlei/hibernate/jpa/StuOtherInfo.java)
package com.caochenlei.hibernate.jpa; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.OneToOne; import javax.persistence.Table; @Entity @Table(name = "student_other_info") public class StuOtherInfo { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) @Column(name = "stu_id") private Long stuId; @Column(name = "stu_img") private String stuImg; @Column(name = "stu_address") private String stuAddress; public Long getStuId() { return stuId; } public void setStuId(Long stuId) { this.stuId = stuId; } public String getStuImg() { return stuImg; } public void setStuImg(String stuImg) { this.stuImg = stuImg; } public String getStuAddress() { return stuAddress; } public void setStuAddress(String stuAddress) { this.stuAddress = stuAddress; } @Override public String toString() { return "StuOtherInfo [stuId=" + stuId + ", stuImg=" + stuImg + ", stuAddress=" + stuAddress + "]"; } /** * 一對一:另外一方的對象 * @OneToOne :映射一對一 * * fetch :抓取策略 * FetchType.LAZY :延遲加載(默認) * FetchType.EAGER :迫切查詢(多表鏈接查詢) * * cascade :級聯操做 * CascadeType.PERSIST :級聯保存 * CascadeType.MERGE :級聯更新 * CascadeType.REMOVE :級聯刪除 * CascadeType.ALL :所有支持 * @JoinColumn :設置兩張表之間外鍵列 * name ;外鍵的名稱 */ @OneToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL) @JoinColumn(name = "stu_id") private StuBaseInfo stuBaseInfo ; public StuBaseInfo getStuBaseInfo() { return stuBaseInfo; } public void setStuBaseInfo(StuBaseInfo stuBaseInfo) { this.stuBaseInfo = stuBaseInfo; } }
OneToOneTest.java(全路徑:/hibernate_jpa/src/com/caochenlei/hibernate/jpa/OneToOneTest.java)
package com.caochenlei.hibernate.jpa; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import org.junit.Test; public class OneToOneTest { /** * 運行以前,修改hibernate.hbm2ddl.auto=create * 保存學生基本信息級聯保存學生拓展信息 */ @Test public void test1() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); // 建立兩個學生基本信息 StuBaseInfo stuBaseInfo1 = new StuBaseInfo(); stuBaseInfo1.setStuName("張三"); StuBaseInfo stuBaseInfo2 = new StuBaseInfo(); stuBaseInfo2.setStuName("李四"); // 建立兩個學生拓展信息 StuOtherInfo stuOtherInfo1 = new StuOtherInfo(); stuOtherInfo1.setStuImg("http:img.caochenlei.com/001.png"); StuOtherInfo stuOtherInfo2 = new StuOtherInfo(); stuOtherInfo2.setStuImg("http:img.caochenlei.com/002.png"); stuBaseInfo1.setStuOtherInfo(stuOtherInfo1); stuBaseInfo2.setStuOtherInfo(stuOtherInfo2); stuOtherInfo1.setStuBaseInfo(stuBaseInfo1); stuOtherInfo2.setStuBaseInfo(stuBaseInfo2); entityManager.persist(stuBaseInfo1); entityManager.persist(stuBaseInfo2); transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=create * 保存學生拓展信息級聯保存學生基本信息 */ @Test public void test2() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); // 建立兩個學生基本信息 StuBaseInfo stuBaseInfo1 = new StuBaseInfo(); stuBaseInfo1.setStuName("張三"); StuBaseInfo stuBaseInfo2 = new StuBaseInfo(); stuBaseInfo2.setStuName("李四"); // 建立兩個學生拓展信息 StuOtherInfo stuOtherInfo1 = new StuOtherInfo(); stuOtherInfo1.setStuImg("http:img.caochenlei.com/001.png"); StuOtherInfo stuOtherInfo2 = new StuOtherInfo(); stuOtherInfo2.setStuImg("http:img.caochenlei.com/002.png"); stuBaseInfo1.setStuOtherInfo(stuOtherInfo1); stuBaseInfo2.setStuOtherInfo(stuOtherInfo2); stuOtherInfo1.setStuBaseInfo(stuBaseInfo1); stuOtherInfo2.setStuBaseInfo(stuBaseInfo2); entityManager.persist(stuOtherInfo1); entityManager.persist(stuOtherInfo2); transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 查詢學生基本信息級聯查詢學生拓展信息 */ @Test public void test3() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); StuBaseInfo stuBaseInfo = entityManager.find(StuBaseInfo.class, 1L); System.out.println(stuBaseInfo); StuOtherInfo stuOtherInfo = stuBaseInfo.getStuOtherInfo(); System.out.println(stuOtherInfo); transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 查詢學生拓展信息級聯查詢學生基本信息 */ @Test public void test4() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); StuOtherInfo stuOtherInfo = entityManager.find(StuOtherInfo.class, 1L); System.out.println(stuOtherInfo); StuBaseInfo stuBaseInfo = stuOtherInfo.getStuBaseInfo(); System.out.println(stuBaseInfo); transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 更新學生基本信息級聯更新學生拓展信息 */ @Test public void test5() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); StuBaseInfo stuBaseInfo = entityManager.find(StuBaseInfo.class, 1L); stuBaseInfo.setStuSex("男"); StuOtherInfo stuOtherInfo = stuBaseInfo.getStuOtherInfo(); stuOtherInfo.setStuAddress("河北省"); entityManager.merge(stuBaseInfo); transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 更新學生拓展信息級聯更新學生基本信息 */ @Test public void test6() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); StuOtherInfo stuOtherInfo = entityManager.find(StuOtherInfo.class, 2L); stuOtherInfo.setStuAddress("河南省"); StuBaseInfo stuBaseInfo = stuOtherInfo.getStuBaseInfo(); stuBaseInfo.setStuSex("女"); entityManager.merge(stuOtherInfo); transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 刪除學生基本信息級聯刪除學生拓展信息 */ @Test public void test7() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); StuBaseInfo stuBaseInfo = entityManager.find(StuBaseInfo.class, 1L); entityManager.remove(stuBaseInfo); transaction.commit(); entityManager.close(); } /** * 運行以前,修改hibernate.hbm2ddl.auto=update * 刪除學生拓展信息級聯刪除學生基本信息 */ @Test public void test8() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); StuOtherInfo stuOtherInfo = entityManager.find(StuOtherInfo.class, 2L); entityManager.remove(stuOtherInfo); transaction.commit(); entityManager.close(); } }
初始化數據,運行init方法:
InitQueryData.java(全路徑:/hibernate_jpa/src/com/caochenlei/hibernate/jpa/InitQueryData.java)
package com.caochenlei.hibernate.jpa; import javax.persistence.EntityManager; import javax.persistence.EntityTransaction; import org.junit.Test; public class InitQueryData { /** * 執行前:修改hibernate.hbm2ddl.auto=create * 執行此方法 * 執行後:修改hibernate.hbm2ddl.auto=update */ @Test public void init() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); // 建立一個客戶 Customer customer1 = new Customer(); customer1.setCustName("張三"); customer1.setCustSource("電視廣告"); // 建立十個聯繫人 for (int i = 1; i <= 10; i++) { LinkMan linkMan = new LinkMan(); linkMan.setLkmName("張三的聯繫人" + i); linkMan.setCustomer(customer1); customer1.getLinkMans().add(linkMan); entityManager.persist(linkMan); } entityManager.persist(customer1); // 建立一個客戶 Customer customer2 = new Customer(); customer2.setCustName("李四"); customer2.setCustSource("網絡論壇"); // 建立十個聯繫人 for (int i = 1; i <= 10; i++) { LinkMan linkMan = new LinkMan(); linkMan.setLkmName("李四的聯繫人" + i); linkMan.setCustomer(customer2); customer2.getLinkMans().add(linkMan); entityManager.persist(linkMan); } entityManager.persist(customer2); // 建立一個客戶 Customer customer3 = new Customer(); customer3.setCustName("王五"); customer3.setCustSource("街邊告示"); // 建立十個聯繫人 for (int i = 1; i <= 10; i++) { LinkMan linkMan = new LinkMan(); linkMan.setLkmName("王五的聯繫人" + i); linkMan.setCustomer(customer3); customer3.getLinkMans().add(linkMan); entityManager.persist(linkMan); } entityManager.persist(customer3); // 建立一個客戶 Customer customer4 = new Customer(); customer4.setCustName("王五"); customer4.setCustSource("電視廣告"); entityManager.persist(customer4); transaction.commit(); entityManager.close(); } }
如下的方法,均在下邊文件進行測試:
JPQLTest.java(全路徑:/hibernate_jpa/src/com/caochenlei/hibernate/jpa/JPQLTest.java)
@Test public void test1() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); // 查詢全部客戶 Query query = entityManager.createQuery("from Customer"); List<Customer> list = query.getResultList(); for (Customer customer : list) { System.out.println(customer); } System.err.println("--------------------------------------------------"); transaction.commit(); entityManager.close(); }
@Test public void test2() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); // 查詢全部客戶 Query query1 = entityManager.createQuery("from Customer c"); List<Customer> list1 = query1.getResultList(); for (Customer customer : list1) { System.out.println(customer); } System.err.println("--------------------------------------------------"); // 查詢全部客戶 Query query2 = entityManager.createQuery("select c from Customer c"); List<Customer> list2 = query2.getResultList(); for (Customer customer : list2) { System.out.println(customer); } System.err.println("--------------------------------------------------"); transaction.commit(); entityManager.close(); }
@Test public void test3() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); // 採用鏈式調用,默認狀況(升序) List<Customer> list1 = entityManager.createQuery("from Customer order by cust_id").getResultList(); for (Customer customer : list1) { System.out.println(customer); } System.err.println("--------------------------------------------------"); // 採用鏈式調用,升序狀況 List<Customer> list2 = entityManager.createQuery("from Customer order by cust_id asc").getResultList(); for (Customer customer : list2) { System.out.println(customer); } System.err.println("--------------------------------------------------"); // 採用鏈式調用,降序狀況 List<Customer> list3 = entityManager.createQuery("from Customer order by cust_id desc").getResultList(); for (Customer customer : list3) { System.out.println(customer); } System.err.println("--------------------------------------------------"); transaction.commit(); entityManager.close(); }
@Test public void test4() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); // 條件查詢:按參數位置綁定 Query query1 = entityManager.createQuery("from Customer where cust_source = ? and cust_name like ?"); query1.setParameter(1, "電視廣告"); query1.setParameter(2, "王%"); List<Customer> list1 = query1.getResultList(); for (Customer customer : list1) { System.out.println(customer); } System.err.println("--------------------------------------------------"); // 條件查詢:按參數名稱綁定 Query query2 = entityManager.createQuery("from Customer where cust_source = :aaa and cust_name like :bbb"); query2.setParameter("aaa", "電視廣告"); query2.setParameter("bbb", "王%"); List<Customer> list2 = query2.getResultList(); for (Customer customer : list2) { System.out.println(customer); } System.err.println("--------------------------------------------------"); transaction.commit(); entityManager.close(); }
@Test public void test5() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); // 查詢全部客戶名稱:單個字段查詢 Query query1 = entityManager.createQuery("select c.custName from Customer c"); List<Object> list1 = query1.getResultList(); for (Object cust_name : list1) { System.out.println(cust_name); } System.err.println("--------------------------------------------------"); // 查詢全部客戶名稱、客戶來源:多個字段查詢,封裝到數組中 Query query2 = entityManager.createQuery("select c.custName,c.custSource from Customer c"); List<Object[]> list2 = query2.getResultList(); for (Object[] objects : list2) { System.out.println(Arrays.toString(objects)); } System.err.println("--------------------------------------------------"); // 查詢全部客戶名稱、客戶來源:多個字段查詢,封裝到對象中 // 請在Customer.java添加如下兩個構造方法,不然會執行失敗 // public Customer() // public Customer(String custName, String custSource) Query query3 = entityManager.createQuery("select new Customer(c.custName,c.custSource) from Customer c"); List<Customer> list3 = query3.getResultList(); for (Customer customer : list3) { System.out.println(customer); } System.err.println("--------------------------------------------------"); transaction.commit(); entityManager.close(); }
@Test public void test6() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); // 分頁查詢 Query query = entityManager.createQuery("from LinkMan"); query.setFirstResult(0); query.setMaxResults(10); List<LinkMan> list = query.getResultList(); for (LinkMan linkMan : list) { System.out.println(linkMan); } System.err.println("--------------------------------------------------"); transaction.commit(); entityManager.close(); }
@Test public void test7() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); // 聚合函數:count(),max(),min(),avg(),sum() Object object = entityManager.createQuery("select count(*) from Customer").getSingleResult(); System.out.println(object); System.err.println("--------------------------------------------------"); // 分組統計: List<Object[]> list = entityManager.createQuery("select custSource,count(*) from Customer group by cust_source").getResultList(); for (Object[] objects : list) { System.out.println(Arrays.toString(objects)); } System.err.println("--------------------------------------------------"); transaction.commit(); entityManager.close(); }
@Test public void test8() { EntityManager entityManager = JPAUtil.getEntityManager(); EntityTransaction transaction = entityManager.getTransaction(); transaction.begin(); // 內鏈接 List<Object[]> list1 = entityManager.createQuery("from Customer c inner join c.linkMans").getResultList(); for (Object[] objects : list1) { System.out.println(Arrays.toString(objects)); } System.err.println("--------------------------------------------------"); // 迫切內鏈接(hibernate獨有,將另外一個對象的數據封裝到該對象中) List<Customer> list2 = entityManager.createQuery("select distinct c from Customer c inner join fetch c.linkMans").getResultList(); for (Customer customer : list2) { System.out.println(customer); } System.err.println("--------------------------------------------------"); // 左外鏈接 List<Object[]> list3 = entityManager.createQuery("from Customer c left outer join c.linkMans").getResultList(); for (Object[] objects : list3) { System.out.println(Arrays.toString(objects)); } System.err.println("--------------------------------------------------"); // 迫切左外鏈接(hibernate獨有,將另外一個對象的數據封裝到該對象中) List<Customer> list4 = entityManager.createQuery("select distinct c from Customer c left outer join fetch c.linkMans").getResultList(); for (Customer customer : list4) { System.out.println(customer); } System.err.println("--------------------------------------------------"); // 右外鏈接 List<Object[]> list5 = entityManager.createQuery("from Customer c right outer join c.linkMans").getResultList(); for (Object[] objects : list5) { System.out.println(Arrays.toString(objects)); } System.err.println("--------------------------------------------------"); transaction.commit(); entityManager.close(); }