学习Hibernate5 JPA这一篇就够了

   日期:2020-09-28     浏览:91    评论:0    
核心提示:目录第一章 Hibernate5 JPA快速入门1.1、Hibernate5 JPA概述1.2、Hibernate5 JPA下载1.3、Hibernate5 JPA工程搭建1.4、Hibernate5 JPA增删改查1.5、Hibernate5 JPA工具类第二章 Hibernate5 JPA核心对象2.1、Persistence2.2、EntityManagerFactory2.3、EntityManager2.4、EntityTransaction第三章 Hibernate5 JPA映射配置3.1、一

目录

    • 第一章 Hibernate5 JPA快速入门
      • 1.1、Hibernate5 JPA概述
      • 1.2、Hibernate5 JPA下载
      • 1.3、Hibernate5 JPA工程搭建
      • 1.4、Hibernate5 JPA增删改查
      • 1.5、Hibernate5 JPA工具类
    • 第二章 Hibernate5 JPA核心对象
      • 2.1、Persistence
      • 2.2、EntityManagerFactory
      • 2.3、EntityManager
      • 2.4、EntityTransaction
    • 第三章 Hibernate5 JPA映射配置
      • 3.1、一对多关联
        • 3.1.1、修改实体
        • 3.1.2、测试代码
      • 3.2、多对多关联
        • 3.2.1、创建实体
        • 3.2.2、测试代码
      • 3.3、一对一关联
        • 3.3.1、创建实体
        • 3.3.2、测试代码
    • 第四章 Hibernate5 JPA的JPQL查询
      • 4.1、简单查询
      • 4.2、别名查询
      • 4.3、排序查询
      • 4.4、条件查询
      • 4.5、投影查询
      • 4.6、分页查询
      • 4.7、分组查询
      • 4.8、多表查询

配套资料,免费下载
链接:https://pan.baidu.com/s/1YvoPpZGrZfqHspGUPKtn0w
提取码:nsmt
复制这段内容后打开百度网盘手机App,操作更方便哦

第一章 Hibernate5 JPA快速入门

1.1、Hibernate5 JPA概述

JPA的全称是Java Persistence API, 即Java 持久化API,是SUN公司推出的一套基于ORM的规范,内部是由一系列的接口和抽象类构成。JPA通过JDK 5.0注解描述对象-关系表的映射关系,并将运行期的实体对象持久化到数据库中

但是JPA仅仅只是一套接口规范和抽象类,并不能真正的去干活,因此,就有很多厂商实现了JPA的规范,提供了相应的技术支持,就类似实现了JDBC的MySQL驱动,而本节课程将采用Hibernate实现作为驱动使用,因此我称之为Hibernate5 JPA

1.2、Hibernate5 JPA下载

官方网址:hibernate orm

目录介绍:

hibernate-release-5.0.7.Final文件夹介绍:

hibernate-release-5.0.7.Final\lib文件夹介绍:

1.3、Hibernate5 JPA工程搭建

前边学习的Hibernate,接下来进行工程搭建,根Hibernate相比,它只需要再多加入一个包就行

把下面四个文件夹的内容全部拷贝到lib中

  • hibernate-release-5.0.7.Final\lib\required

  • hibernate-release-5.0.7.Final\lib\optional\c3p0

  • hibernate-release-5.0.7.Final\lib\jpa

  • 日志记录包

  • 数据库驱动

把下面五个文件夹的内容全部拷贝到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 = "cst_customer")
public class Customer { 

	
	@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 + "]";
	}

}

1.4、Hibernate5 JPA增删改查

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 { 

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

}

1.5、Hibernate5 JPA工具类

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();
	}

}

第二章 Hibernate5 JPA核心对象

2.1、Persistence

Persistence对象主要作用是用于获取EntityManagerFactory对象的 。通过调用该类的createEntityManagerFactory静态方法,根据配置文件中持久化单元名称创建EntityManagerFactory。

2.2、EntityManagerFactory

EntityManagerFactory 接口主要用来创建 EntityManager 实例。

2.3、EntityManager

在 JPA 规范中,EntityManager是完成持久化操作的核心对象。实体类作为普通 java对象,只有在调用 EntityManager将其持久化后才会变成持久化对象。EntityManager对象在一组实体类与底层数据源之间进行 O/R 映射的管理。它可以用来管理和更新 Entity Bean,根椐主键查找 Entity Bean, 还可以通过JPQL语句查询实体。我们可以通过调用EntityManager的方法完成获取事务,以及持久化数据库的操作,例如:

  • getTransaction:获取事务对象
  • persist:保存操作
  • merge:更新操作
  • remove:删除操作
  • find/getReference:根据id查询

2.4、EntityTransaction

在 JPA 规范中,EntityTransaction是完成事务操作的核心对象,对于EntityTransaction在我们的Java代码中承接的功能比较简单。

  • begin:开启事务
  • commit:提交事务
  • rollback:回滚事务

第三章 Hibernate5 JPA映射配置

3.1、一对多关联

3.1.1、修改实体

修改Customer.java(全路径:/hibernate_jpa/src/com/caochenlei/hibernate/jpa/Customer.java)

在toString方法的下面添加多的集合


@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.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;
}

3.1.2、测试代码

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 { 

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

}

3.2、多对多关联

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;

3.2.1、创建实体

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.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.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;
	}

}

3.2.2、测试代码

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 { 

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

}

3.3、一对一关联

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;

3.3.1、创建实体

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.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.EAGER, cascade = CascadeType.ALL)
	@JoinColumn(name = "stu_id")
	private StuBaseInfo stuBaseInfo ;

	public StuBaseInfo getStuBaseInfo() { 
		return stuBaseInfo;
	}

	public void setStuBaseInfo(StuBaseInfo stuBaseInfo) { 
		this.stuBaseInfo = stuBaseInfo;
	}

}

3.3.2、测试代码

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 { 

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

	
	@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();
	}

}

第四章 Hibernate5 JPA的JPQL查询

初始化数据,运行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 { 

	
	@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)

4.1、简单查询

@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();
}

4.2、别名查询

@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();
}

4.3、排序查询

@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();
}

4.4、条件查询

@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();
}

4.5、投影查询

@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();
}

4.6、分页查询

@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();
}

4.7、分组查询

@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();
}

4.8、多表查询

@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();
}
 
打赏
 本文转载自:网络 
所有权利归属于原作者,如文章来源标示错误或侵犯了您的权利请联系微信13520258486
更多>最近资讯中心
更多>最新资讯中心
0相关评论

推荐图文
推荐资讯中心
点击排行
最新信息
新手指南
采购商服务
供应商服务
交易安全
关注我们
手机网站:
新浪微博:
微信关注:

13520258486

周一至周五 9:00-18:00
(其他时间联系在线客服)

24小时在线客服