ORM框架之Spring Data JPA(三)高级查询---复杂查询
一、spring data jpa高级查询
1.1Specifications动态查询
有时我们在查询某个实体的时候,给定的条件是不固定的,这时就需要动态构建相应的查询语句,在Spring Data JPA中可以通过JpaSpecificationExecutor接口查询。相比JPQL,其优势是类型安全,更加的面向对象。
import java.util.List;import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;/*** JpaSpecificationExecutor中定义的方法**/public interface JpaSpecificationExecutor<T> {//根据条件查询一个对象T findOne(Specification<T> spec); //根据条件查询集合List<T> findAll(Specification<T> spec);//根据条件分页查询Page<T> findAll(Specification<T> spec, Pageable pageable);//排序查询查询List<T> findAll(Specification<T> spec, Sort sort);//统计查询long count(Specification<T> spec);
}
对于JpaSpecificationExecutor,这个接口基本是围绕着Specification接口来定义的。我们可以简单的理解为,Specification构造的就是查询条件。
Specification接口中只定义了如下一个方法:
//构造查询条件/*** root :Root接口,代表查询的根对象,可以通过root获取实体中的属性* query :代表一个顶层查询对象,用来自定义查询* cb :用来构建查询,此对象里有很多条件方法**/public Predicate toPredicate(Root<T> root, CriteriaQuery<?> query, CriteriaBuilder cb);
1.2 maven建立spec项目,pom依赖:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>cn.xiaomifeng1010</groupId><artifactId>jpa-day3-spec</artifactId><version>1.0-SNAPSHOT</version><properties><spring.version>5.0.2.RELEASE</spring.version><hibernate.version>5.0.7.Final</hibernate.version><slf4j.version>1.6.6</slf4j.version><log4j.version>1.2.12</log4j.version><c3p0.version>0.9.1.2</c3p0.version><mysql.version>5.1.6</mysql.version></properties><dependencies><!-- junit单元测试 --><dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version><scope>test</scope></dependency><!-- spring beg --><dependency><groupId>org.aspectj</groupId><artifactId>aspectjweaver</artifactId><version>1.6.8</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-aop</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-context-support</artifactId><version>${spring.version}</version></dependency><!-- spring对orm框架的支持包--><dependency><groupId>org.springframework</groupId><artifactId>spring-orm</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-beans</artifactId><version>${spring.version}</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-core</artifactId><version>${spring.version}</version></dependency><!-- spring end --><!-- hibernate beg --><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-core</artifactId><version>${hibernate.version}</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-entitymanager</artifactId><version>${hibernate.version}</version></dependency><dependency><groupId>org.hibernate</groupId><artifactId>hibernate-validator</artifactId><version>5.2.1.Final</version></dependency><!-- hibernate end --><!-- c3p0 beg --><dependency><groupId>c3p0</groupId><artifactId>c3p0</artifactId><version>${c3p0.version}</version></dependency><!-- c3p0 end --><!-- log end --><dependency><groupId>log4j</groupId><artifactId>log4j</artifactId><version>${log4j.version}</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-api</artifactId><version>${slf4j.version}</version></dependency><dependency><groupId>org.slf4j</groupId><artifactId>slf4j-log4j12</artifactId><version>${slf4j.version}</version></dependency><!-- log end --><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>${mysql.version}</version></dependency><!-- spring data jpa 的坐标--><dependency><groupId>org.springframework.data</groupId><artifactId>spring-data-jpa</artifactId><version>1.9.0.RELEASE</version></dependency><dependency><groupId>org.springframework</groupId><artifactId>spring-test</artifactId><version>${spring.version}</version></dependency><!-- el beg 使用spring data jpa 必须引入 --><dependency><groupId>javax.el</groupId><artifactId>javax.el-api</artifactId><version>2.2.4</version></dependency><dependency><groupId>org.glassfish.web</groupId><artifactId>javax.el</artifactId><version>2.2.4</version></dependency><!-- el end --></dependencies></project>
1.3 spring data jpa项目配置文件(同第二篇实例中的配置)
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"xmlns:context="http://www.springframework.org/schema/context"xmlns:jdbc="http://www.springframework.org/schema/jdbc" xmlns:tx="http://www.springframework.org/schema/tx"xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:task="http://www.springframework.org/schema/task"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsdhttp://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsdhttp://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsdhttp://www.springframework.org/schema/data/jpahttp://www.springframework.org/schema/data/jpa/spring-jpa.xsd"><!--spring 和 spring data jpa的配置--><!-- 1.创建entityManagerFactory对象交给spring容器管理--><bean id="entityManagerFactoty" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"><property name="dataSource" ref="dataSource" /><!--配置的扫描的包(实体类所在的包) --><property name="packagesToScan" value="cn.xiaomifeng1010.domain" /><!-- jpa的实现厂家 --><property name="persistenceProvider"><bean class="org.hibernate.jpa.HibernatePersistenceProvider"/></property><!--jpa的供应商适配器 --><property name="jpaVendorAdapter"><bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"><!--配置是否自动创建数据库表 --><property name="generateDdl" value="false" /><!--指定数据库类型 --><property name="database" value="MYSQL" /><!--数据库方言:支持的特有语法 --><property name="databasePlatform" value="org.hibernate.dialect.MySQLDialect" /><!--是否显示sql --><property name="showSql" value="true" /></bean></property><!--jpa的方言 :高级的特性 --><property name="jpaDialect" ><bean class="org.springframework.orm.jpa.vendor.HibernateJpaDialect" /></property></bean><!--2.创建数据库连接池 --><bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"><property name="user" value="root"></property><property name="password" value="123456"></property><property name="jdbcUrl" value="jdbc:mysql://localhost:3306/jpa" ></property><property name="driverClass" value="com.mysql.jdbc.Driver"></property></bean><!--3.整合spring dataJpa--><jpa:repositories base-package="cn.xiaomifeng1010.dao" transaction-manager-ref="transactionManager"entity-manager-factory-ref="entityManagerFactoty" ></jpa:repositories><!--4.配置事务管理器 --><bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"><property name="entityManagerFactory" ref="entityManagerFactoty"></property></bean><!-- 4.txAdvice--><tx:advice id="txAdvice" transaction-manager="transactionManager"><tx:attributes><tx:method name="save*" propagation="REQUIRED"/><tx:method name="insert*" propagation="REQUIRED"/><tx:method name="update*" propagation="REQUIRED"/><tx:method name="delete*" propagation="REQUIRED"/><tx:method name="get*" read-only="true"/><tx:method name="find*" read-only="true"/><tx:method name="*" propagation="REQUIRED"/></tx:attributes></tx:advice><!-- 5.aop--><aop:config><aop:pointcut id="pointcut" expression="execution(* cn.xiaomifeng1010.service.*.*(..))" /><aop:advisor advice-ref="txAdvice" pointcut-ref="pointcut" /></aop:config><!--5.声明式事务 --><!-- 6. 配置包扫描--><context:component-scan base-package="cn.xiaomifeng1010" ></context:component-scan>
</beans>
1.4 实体类customer和dao
package cn.xiaomifeng1010.domain;import javax.persistence.*;/*** 1.实体类和表的映射关系* @Eitity* @Table* 2.类中属性和表中字段的映射关系* @Id* @GeneratedValue* @Column*/
@Entity
@Table(name="cst_customer")
public class Customer {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name="cust_id")private Long custId;@Column(name="cust_address")private String custAddress;@Column(name="cust_industry")private String custIndustry;@Column(name="cust_level")private String custLevel;@Column(name="cust_name")private String custName;@Column(name="cust_phone")private String custPhone;@Column(name="cust_source")private String custSource;public Long getCustId() {return custId;}public void setCustId(Long custId) {this.custId = custId;}public String getCustAddress() {return custAddress;}public void setCustAddress(String custAddress) {this.custAddress = custAddress;}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 getCustName() {return custName;}public void setCustName(String custName) {this.custName = custName;}public String getCustPhone() {return custPhone;}public void setCustPhone(String custPhone) {this.custPhone = custPhone;}public String getCustSource() {return custSource;}public void setCustSource(String custSource) {this.custSource = custSource;}@Overridepublic String toString() {return "Customer{" +"custId=" + custId +", custAddress='" + custAddress + '\'' +", custIndustry='" + custIndustry + '\'' +", custLevel='" + custLevel + '\'' +", custName='" + custName + '\'' +", custPhone='" + custPhone + '\'' +", custSource='" + custSource + '\'' +'}';}
}
package cn.xiaomifeng1010.dao;import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;import cn.xiaomifeng1010.domain.Customer;import java.util.List;/*** 符合SpringDataJpa的dao层接口规范* JpaRepository<操作的实体类类型,实体类中主键属性的类型>* * 封装了基本CRUD操作* JpaSpecificationExecutor<操作的实体类类型>* * 封装了复杂查询(分页)*/
public interface CustomerDao extends JpaRepository<Customer,Long> ,JpaSpecificationExecutor<Customer> {/*** 案例:根据客户名称查询客户* 使用jpql的形式查询* jpql:from Customer where custName = ?** 配置jpql语句,使用的@Query注解*/@Query(value="from Customer where custName = ?")public Customer findJpql(String custName);/*** 案例:根据客户名称和客户id查询客户* jpql: from Customer where custName = ? and custId = ?** 对于多个占位符参数* 赋值的时候,默认的情况下,占位符的位置需要和方法参数中的位置保持一致** 可以指定占位符参数的位置* ? 索引的方式,指定此占位的取值来源*/@Query(value = "from Customer where custName = ?2 and custId = ?1")public Customer findCustNameAndId(Long id, String name);/*** 使用jpql完成更新操作* 案例 : 根据id更新,客户的名称* 更新4号客户的名称,将名称改为“黑马程序员”** sql :update cst_customer set cust_name = ? where cust_id = ?* jpql : update Customer set custName = ? where custId = ?** @Query : 代表的是进行查询* * 声明此方法是用来进行更新操作* @Modifying* * 当前执行的是一个更新操作**/@Query(value = " update Customer set custName = ?2 where custId = ?1 ")@Modifyingpublic void updateCustomer(long custId, String custName);/*** 使用sql的形式查询:* 查询全部的客户* sql : select * from cst_customer;* Query : 配置sql查询* value : sql语句* nativeQuery : 查询方式* true : sql查询* false:jpql查询**///@Query(value = " select * from cst_customer" ,nativeQuery = true)@Query(value="select * from cst_customer where cust_name like ?1",nativeQuery = true)public List<Object [] > findSql(String name);/*** 方法名的约定:* findBy : 查询* 对象中的属性名(首字母大写) : 查询的条件* CustName* * 默认情况 : 使用 等于的方式查询* 特殊的查询方式** findByCustName -- 根据客户名称查询** 再springdataJpa的运行阶段* 会根据方法名称进行解析 findBy from xxx(实体类)* 属性名称 where custName =** 1.findBy + 属性名称 (根据属性名称进行完成匹配的查询=)* 2.findBy + 属性名称 + “查询方式(Like | isnull)”* findByCustNameLike* 3.多条件查询* findBy + 属性名 + “查询方式” + “多条件的连接符(and|or)” + 属性名 + “查询方式”*/public Customer findByCustName(String custName);public List<Customer> findByCustNameLike(String custName);//使用客户名称模糊匹配和客户所属行业精准匹配的查询public Customer findByCustNameLikeAndCustIndustry(String custName, String custIndustry);
}
1.5 使用Specifications完成条件查询和分页查询
package cn.xiaomifeng1010.test;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;import cn.xiaomifeng1010.dao.CustomerDao;
import cn.xiaomifeng1010.domain.Customer;import javax.persistence.criteria.*;
import java.util.List;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class SpecTest {@Autowiredprivate CustomerDao customerDao;/*** 根据条件,查询单个对象**/@Testpublic void testSpec() {//匿名内部类/*** 自定义查询条件* 1.实现Specification接口(提供泛型:查询的对象类型)* 2.实现toPredicate方法(构造查询条件)* 3.需要借助方法参数中的两个参数(* root:获取需要查询的对象属性* CriteriaBuilder:构造查询条件的,内部封装了很多的查询条件(模糊匹配,精准匹配)* )* 案例:根据客户名称查询,查询客户名为周杰的客户* 查询条件* 1.查询方式* cb对象* 2.比较的属性名称* root对象**/Specification<Customer> spec = new Specification<Customer>() {public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {//1.获取比较的属性Path<Object> custName = root.get("custId");//2.构造查询条件 : select * from cst_customer where cust_name = '周杰'/*** 第一个参数:需要比较的属性(path对象)* 第二个参数:当前需要比较的取值*/Predicate predicate = cb.equal(custName, "周杰");//进行精准的匹配 (比较的属性,比较的属性的取值)return predicate;}};Customer customer = customerDao.findOne(spec);System.out.println(customer);}/*** 多条件查询* 案例:根据客户名(周杰)和客户所属行业查询(it教育)**/@Testpublic void testSpec1() {/*** root:获取属性* 客户名* 所属行业* cb:构造查询* 1.构造客户名的精准匹配查询* 2.构造所属行业的精准匹配查询* 3.将以上两个查询联系起来*/Specification<Customer> spec = new Specification<Customer>() {public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {Path<Object> custName = root.get("custName");//客户名Path<Object> custIndustry = root.get("custIndustry");//所属行业//构造查询//1.构造客户名的精准匹配查询Predicate p1 = cb.equal(custName, "周杰");//第一个参数,path(属性),第二个参数,属性的取值//2..构造所属行业的精准匹配查询Predicate p2 = cb.equal(custIndustry, "it教育");//3.将多个查询条件组合到一起:组合(满足条件一并且满足条件二:与关系,满足条件一或满足条件二即可:或关系)Predicate and = cb.and(p1, p2);//以与的形式拼接多个查询条件// cb.or();//以或的形式拼接多个查询条件return and;}};Customer customer = customerDao.findOne(spec);System.out.println(customer);}/*** 案例:完成根据客户名称的模糊匹配,返回客户列表* 客户名称以 ’周杰‘ 开头** equal :直接的到path对象(属性),然后进行比较即可* gt,lt,ge,le,like : 得到path对象,根据path指定比较的参数类型,再去进行比较* 指定参数类型:path.as(类型的字节码对象)*/@Testpublic void testSpec3() {//构造查询条件Specification<Customer> spec = new Specification<Customer>() {public Predicate toPredicate(Root<Customer> root, CriteriaQuery<?> query, CriteriaBuilder cb) {//查询属性:客户名Path<Object> custName = root.get("custName");//查询方式:模糊匹配Predicate like = cb.like(custName.as(String.class), "周杰%");return like;}};
// List<Customer> list = customerDao.findAll(spec);
// for (Customer customer : list) {
// System.out.println(customer);
// }//添加排序//创建排序对象,需要调用构造方法实例化sort对象//第一个参数:排序的顺序(倒序,正序)// Sort.Direction.DESC:倒序// Sort.Direction.ASC : 升序//第二个参数:排序的属性名称Sort sort = new Sort(Sort.Direction.DESC,"custId");List<Customer> list = customerDao.findAll(spec, sort);for (Customer customer : list) {System.out.println(customer);}}/*** 分页查询* Specification: 查询条件* Pageable:分页参数* 分页参数:查询的页码,每页查询的条数* findAll(Specification,Pageable):带有条件的分页* findAll(Pageable):没有条件的分页* 返回:Page(springDataJpa为我们封装好的pageBean对象,数据列表,共条数)*/@Testpublic void testSpec4() {Specification spec = null;//PageRequest对象是Pageable接口的实现类/*** 创建PageRequest的过程中,需要调用他的构造方法传入两个参数* 第一个参数:当前查询的页数(从0开始)* 第二个参数:每页查询的数量*/Pageable pageable = new PageRequest(0,2);//分页查询Page<Customer> page = customerDao.findAll(null, pageable);System.out.println(page.getContent()); //得到数据集合列表System.out.println(page.getTotalElements());//得到总条数System.out.println(page.getTotalPages());//得到总页数}
}
1.6 方法对应关系
方法名称 |
Sql对应关系 |
equle |
filed = value |
gt(greaterThan ) |
filed > value |
lt(lessThan ) |
filed < value |
ge(greaterThanOrEqualTo ) |
filed >= value |
le( lessThanOrEqualTo) |
filed <= value |
notEqule |
filed != value |
like |
filed like value |
notLike |
filed not like value |
二、多表设计及多表查询
2.1表之间关系的划分
数据库中多表之间存在着三种关系,如图所示。
从图可以看出,系统设计的三种实体关系分别为:多对多、一对多和一对一关系。注意:一对多关系可以看为两种: 即一对多,多对一。所以说四种更精确。
明确: 我们今天只涉及实际开发中常用的关联关系,一对多和多对多。而一对一的情况,在实际开发中几乎不用。
2.2 在JPA框架中表关系的分析步骤
在实际开发中,我们数据库的表难免会有相互的关联关系,在操作表的时候就有可能会涉及到多张表的操作。而在这种实现了ORM思想的框架中(如JPA),可以让我们通过操作实体类就实现对数据库表的操作。所以今天我们的学习重点是:掌握配置实体之间的关联关系。
第一步:首先确定两张表之间的关系。
如果关系确定错了,后面做的所有操作就都不可能正确。
第二步:在数据库中实现两张表的关系
第三步:在实体类中描述出两个实体的关系
第四步:配置出实体类和数据库表的关系映射(重点)
三、JPA中的一对多
3.1 示例分析
我们采用的示例为客户和联系人。
客户:指的是一家公司,我们记为A。
联系人:指的是A公司中的员工。
在不考虑兼职的情况下,公司和员工的关系即为一对多。
3.2 表关系的建立
在一对多关系中,我们习惯把一的一方称之为主表,把多的一方称之为从表。在数据库中建立一对多的关系,需要使用数据库的外键约束。
什么是外键?
指的是从表中有一列,取值参照主表的主键,这一列就是外键。
一对多数据库关系的建立,如下图所示
3.3实体类关系建立以及映射配置
cst_customer表对应的实体类
package cn.xiaomifeng1010.domain;import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
import cn.xiaomifeng1010.domain.LinkMan;/*** 客户的实体类* 明确使用的注解都是JPA规范的* 所以导包都要导入javax.persistence包下的*/
@Entity//表示当前类是一个实体类
@Table(name="cst_customer")//建立当前实体类和表之间的对应关系
public class Customer implements Serializable {@Id//表明当前私有属性是主键@GeneratedValue(strategy=GenerationType.IDENTITY)//指定主键的生成策略@Column(name="cust_id")//指定和数据库表中的cust_id列对应private Long custId;@Column(name="cust_name")//指定和数据库表中的cust_name列对应private String custName;@Column(name="cust_source")//指定和数据库表中的cust_source列对应private String custSource;@Column(name="cust_industry")//指定和数据库表中的cust_industry列对应private String custIndustry;@Column(name="cust_level")//指定和数据库表中的cust_level列对应private String custLevel;@Column(name="cust_address")//指定和数据库表中的cust_address列对应private String custAddress;@Column(name="cust_phone")//指定和数据库表中的cust_phone列对应private String custPhone;//配置客户和联系人的一对多关系@OneToMany(targetEntity=LinkMan.class)@JoinColumn(name="lkm_cust_id",referencedColumnName="cust_id")private Set<LinkMan> linkmans = new HashSet<LinkMan>(0);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 getCustAddress() {return custAddress;}public void setCustAddress(String custAddress) {this.custAddress = custAddress;}public String getCustPhone() {return custPhone;}public void setCustPhone(String custPhone) {this.custPhone = custPhone;}public Set<LinkMan> getLinkmans() {return linkmans;}public void setLinkmans(Set<LinkMan> linkmans) {this.linkmans = linkmans;}@Overridepublic String toString() {return "Customer [custId=" + custId + ", custName=" + custName + ", custSource=" + custSource+ ", custIndustry=" + custIndustry + ", custLevel=" + custLevel + ", custAddress=" + custAddress+ ", custPhone=" + custPhone + "]";}
}
还需要创建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_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=3 DEFAULT CHARSET=utf8;
由于联系人是多的一方,在实体类中要体现出,每个联系人只能对应一个客户,代码如下,对应的实体类:、
package cn.xiaomifeng1010.domain;import javax.persistence.*;
import cn.xiaomifeng1010.domain.Customer;@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_position")private String lkmPosition;//联系人职位@Column(name = "lkm_memo")private String lkmMemo;//联系人备注/*** 配置联系人到客户的多对一关系* 使用注解的形式配置多对一关系* 1.配置表关系* @ManyToOne : 配置多对一关系* targetEntity:对方的实体类字节码* 2.配置外键(中间表)** * 配置外键的过程,配置到了多的一方,就会在多的一方维护外键**/@ManyToOne(targetEntity = Customer.class,fetch = FetchType.LAZY)@JoinColumn(name = "lkm_cust_id",referencedColumnName = "cust_id")private Customer customer;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 getLkmPosition() {return lkmPosition;}public void setLkmPosition(String lkmPosition) {this.lkmPosition = lkmPosition;}public String getLkmMemo() {return lkmMemo;}public void setLkmMemo(String lkmMemo) {this.lkmMemo = lkmMemo;}public Customer getCustomer() {return customer;}public void setCustomer(Customer customer) {this.customer = customer;}@Overridepublic String toString() {return "LinkMan{" +"lkmId=" + lkmId +", lkmName='" + lkmName + '\'' +", lkmGender='" + lkmGender + '\'' +", lkmPhone='" + lkmPhone + '\'' +", lkmMobile='" + lkmMobile + '\'' +", lkmEmail='" + lkmEmail + '\'' +", lkmPosition='" + lkmPosition + '\'' +", lkmMemo='" + lkmMemo + '\'' +'}';}
}
3.4 映射的注解说明
@OneToMany:
作用:建立一对多的关系映射
属性:
targetEntityClass:指定多的多方的类的字节码
mappedBy:指定从表实体类中引用主表对象的名称。
cascade:指定要使用的级联操作
fetch:指定是否采用延迟加载
orphanRemoval:是否使用孤儿删除
@ManyToOne
作用:建立多对一的关系
属性:
targetEntityClass:指定一的一方实体类字节码
cascade:指定要使用的级联操作
fetch:指定是否采用延迟加载
optional:关联是否可选。如果设置为false,则必须始终存在非空关系。
@JoinColumn
作用:用于定义主键字段和外键字段的对应关系。
属性:
name:指定外键字段的名称
referencedColumnName:指定引用主表的主键字段名称
unique:是否唯一。默认值不唯一
nullable:是否允许为空。默认值允许。
insertable:是否允许插入。默认值允许。
updatable:是否允许更新。默认值允许。
columnDefinition:列的定义信息
3.5 一对多的操作
3.5.1 添加以及删除操作
package cn.xiaomifeng1010.test;import cn.xiaomifeng1010.dao.CustomerDao;
import cn.xiaomifeng1010.dao.LinkManDao;
import cn.xiaomifeng1010.domain.Customer;
import cn.xiaomifeng1010.domain.LinkMan;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class OneToManyTest {@Autowiredprivate CustomerDao customerDao;@Autowiredprivate LinkManDao linkManDao;/*** 保存一个客户,保存一个联系人* 效果:客户和联系人作为独立的数据保存到数据库中* 联系人的外键为空* 原因?* 实体类中没有配置关系*/@Test@Transactional //配置事务@Rollback(false) //不自动回滚public void testAdd() {//创建一个客户,创建一个联系人Customer customer = new Customer();customer.setCustName("百度");LinkMan linkMan = new LinkMan();linkMan.setLkmName("小李");/*** 配置了客户到联系人的关系* 从客户的角度上:发送两条insert语句,发送一条更新语句更新数据库(更新外键)* 由于我们配置了客户到联系人的关系:客户可以对外键进行维护*/customer.getLinkMans().add(linkMan);customerDao.save(customer);linkManDao.save(linkMan);}@Test@Transactional //配置事务@Rollback(false) //不自动回滚public void testAdd1() {//创建一个客户,创建一个联系人Customer customer = new Customer();customer.setCustName("百度");LinkMan linkMan = new LinkMan();linkMan.setLkmName("小李");/*** 配置联系人到客户的关系(多对一)* 只发送了两条insert语句* 由于配置了联系人到客户的映射关系(多对一)***/linkMan.setCustomer(customer);customerDao.save(customer);linkManDao.save(linkMan);}/*** 会有一条多余的update语句* * 由于一的一方可以维护外键:会发送update语句* * 解决此问题:只需要在一的一方放弃维护权即可**/@Test@Transactional //配置事务@Rollback(false) //不自动回滚public void testAdd2() {//创建一个客户,创建一个联系人Customer customer = new Customer();customer.setCustName("百度");LinkMan linkMan = new LinkMan();linkMan.setLkmName("小李");linkMan.setCustomer(customer);//由于配置了多的一方到一的一方的关联关系(当保存的时候,就已经对外键赋值)customer.getLinkMans().add(linkMan);//由于配置了一的一方到多的一方的关联关系(发送一条update语句)customerDao.save(customer);linkManDao.save(linkMan);}/*** 级联添加:保存一个客户的同时,保存客户的所有联系人* 需要在操作主体的实体类上,配置casacde属性*/@Test@Transactional //配置事务@Rollback(false) //不自动回滚public void testCascadeAdd() {Customer customer = new Customer();customer.setCustName("百度1");LinkMan linkMan = new LinkMan();linkMan.setLkmName("小李1");linkMan.setCustomer(customer);customer.getLinkMans().add(linkMan);customerDao.save(customer);}/*** 级联删除:* 删除1号客户的同时,删除1号客户的所有联系人*/@Test@Transactional //配置事务@Rollback(false) //不自动回滚public void testCascadeRemove() {//1.查询1号客户Customer customer = customerDao.findOne(1L);//2.删除1号客户customerDao.delete(customer);}
}
删除操作的说明如下:
删除从表数据:可以随时任意删除。
删除主表数据:
- 有从表数据
1、在默认情况下,它会把外键字段置为null,然后删除主表数据。如果在数据库的表 结构上,外键字段有非空约束,默认情况就会报错了。
2、如果配置了放弃维护关联关系的权利,则不能删除(与外键字段是否允许为null, 没有关系)因为在删除时,它根本不会去更新从表的外键字段了。
3、如果还想删除,使用级联删除引用
- 没有从表数据引用:随便删
在实际开发中,级联删除请慎用!(在一对多的情况下)
3.5.3 级联操作
级联操作:指操作一个对象同时操作它的关联对象
使用方法:只需要在操作主体的注解上配置cascade
/*** cascade:配置级联操作* CascadeType.MERGE 级联更新* CascadeType.PERSIST 级联保存:* CascadeType.REFRESH 级联刷新:* CascadeType.REMOVE 级联删除:* CascadeType.ALL 包含所有*/@OneToMany(mappedBy="customer",cascade=CascadeType.ALL)
四、JPA中处理多对多数据关系
4.1 示例分析
我们采用的示例为用户和角色。
用户:指的是咱们班的每一个同学。
角色:指的是咱们班同学的身份信息。
比如A同学,它是我的学生,其中有个身份就是学生,还是家里的孩子,那么他还有个身份是子女。
同时B同学,它也具有学生和子女的身份。
那么任何一个同学都可能具有多个身份。同时学生这个身份可以被多个同学所具有。
所以我们说,用户和角色之间的关系是多对多
4.2 表关系建立
多对多的表关系建立靠的是中间表,其中用户表和中间表的关系是一对多,角色表和中间表的关系也是一对多,如下图所示:
4.3 实体类关系建立以及映射配置
一个用户可以具有多个角色,所以在用户实体类中应该包含多个角色的信息,代码如下:
/*** 用户的数据模型*/
package cn.xiaomifeng1010.domain;import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;@Entity
@Table(name = "sys_user")
public class User {@Id@GeneratedValue(strategy = GenerationType.IDENTITY)@Column(name="user_id")private Long userId;@Column(name="user_name")private String userName;@Column(name="age")private Integer age;/*** 配置用户到角色的多对多关系* 配置多对多的映射关系* 1.声明表关系的配置* @ManyToMany(targetEntity = Role.class) //多对多* targetEntity:代表对方的实体类字节码* 2.配置中间表(包含两个外键)* @JoinTable* name : 中间表的名称* joinColumns:配置当前对象在中间表的外键* @JoinColumn的数组* name:外键名* referencedColumnName:参照的主表的主键名* inverseJoinColumns:配置对方对象在中间表的外键*/@ManyToMany(targetEntity = Role.class,cascade = CascadeType.ALL)@JoinTable(name = "sys_user_role",//joinColumns,当前对象在中间表中的外键joinColumns = {@JoinColumn(name = "sys_user_id",referencedColumnName = "user_id")},//inverseJoinColumns,对方对象在中间表的外键inverseJoinColumns = {@JoinColumn(name = "sys_role_id",referencedColumnName = "role_id")})private Set<Role> roles = new HashSet<Role>();public Long getUserId() {return userId;}public void setUserId(Long userId) {this.userId = userId;}public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public Integer getAge() {return age;}public void setAge(Integer age) {this.age = age;}public Set<Role> getRoles() {return roles;}public void setRoles(Set<Role> roles) {this.roles = roles;}
}
一个角色可以赋予多个用户,所以在角色实体类中应该包含多个用户的信息,代码如下:
package cn.xiaomifeng1010.domain;import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;@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;//配置多对多@ManyToMany(mappedBy = "roles") //配置多表关系private Set<User> users = new HashSet<User>();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 Set<User> getUsers() {return users;}public void setUsers(Set<User> users) {this.users = users;}
}
4.4 映射的注解说明
@ManyToMany
作用:用于映射多对多关系
属性:
cascade:配置级联操作。
fetch:配置是否采用延迟加载。
targetEntity:配置目标的实体类。映射多对多的时候不用写。
@JoinTable
作用:针对中间表的配置
属性:
nam:配置中间表的名称
joinColumns:中间表的外键字段关联当前实体类所对应表的主键字段
inverseJoinColumn:中间表的外键字段关联对方表的主键字段
@JoinColumn
作用:用于定义主键字段和外键字段的对应关系。
属性:
name:指定外键字段的名称
referencedColumnName:指定引用主表的主键字段名称
unique:是否唯一。默认值不唯一
nullable:是否允许为空。默认值允许。
insertable:是否允许插入。默认值允许。
updatable:是否允许更新。默认值允许。
columnDefinition:列的定义信息。
4.5 多对多的操作:
UserDao接口:
import cn.itcast.domain.User;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;public interface UserDao extends JpaRepository<User,Long> ,JpaSpecificationExecutor<User> {
}
RoleDao接口 :
import cn.itcast.domain.Role;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;public interface RoleDao extends JpaRepository<Role,Long> ,JpaSpecificationExecutor<Role> {
}
4.5.1 保存操作与删除操作:
package cn.xiaomifeng1010.test;import cn.xiaomifeng1010.dao.RoleDao;
import cn.xiaomifeng1010.dao.UserDao;
import cn.xiaomifeng1010.domain.Role;
import cn.xiaomifeng1010.domain.User;import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.Rollback;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.transaction.annotation.Transactional;@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:applicationContext.xml")
public class ManyToManyTest {@Autowiredprivate UserDao userDao;@Autowiredprivate RoleDao roleDao;/*** 保存一个用户,保存一个角色** 多对多放弃维护权:被动的一方放弃*/@Test@Transactional@Rollback(false)public void testAdd() {User user = new User();user.setUserName("小李");Role role = new Role();role.setRoleName("java程序员");//配置用户到角色关系,可以对中间表中的数据进行维护 1-1user.getRoles().add(role);//配置角色到用户的关系,可以对中间表的数据进行维护 1-1role.getUsers().add(user);userDao.save(user);roleDao.save(role);}//测试级联添加(保存一个用户的同时保存用户的关联角色)@Test@Transactional@Rollback(false)public void testCasCadeAdd() {User user = new User();user.setUserName("小李");Role role = new Role();role.setRoleName("java程序员");//配置用户到角色关系,可以对中间表中的数据进行维护 1-1user.getRoles().add(role);//配置角色到用户的关系,可以对中间表的数据进行维护 1-1role.getUsers().add(user);userDao.save(user);}/*** 案例:删除id为1的用户,同时删除他的关联对象*/@Test@Transactional@Rollback(false)public void testCasCadeRemove() {//查询1号用户User user = userDao.findOne(1l);//删除1号用户userDao.delete(user);}
}
在多对多(保存)中,如果双向都设置关系,意味着双方都维护中间表,都会往中间表插入数据,中间表的2个字段又作为联合主键,所以报错,主键重复,解决保存失败的问题:只需要在任意一方放弃对中间表的维护权即可,推荐在被动的一方放弃,配置如下:
//放弃对中间表的维护权,解决保存中主键冲突的问题@ManyToMany(mappedBy="roles")private Set<SysUser> users = new HashSet<SysUser>(0);
五、Spring Data JPA中的多表查询
5.1 对象导航查询
对象图导航检索方式是根据已经加载的对象,导航到他的关联对象。它利用类与类之间的关系来检索对象。例如:我们通过ID查询方式查出一个客户,可以调用Customer类中的getLinkMans()方法来获取该客户的所有联系人。对象导航查询的使用要求是:两个对象之间必须存在关联关系。
查询一个客户,获取该客户下的所有联系人
@Autowiredprivate CustomerDao customerDao;@Test//由于是在java代码中测试,为了解决no session问题,将操作配置到同一个事务中@Transactional public void testFind() {Customer customer = customerDao.findOne(5l);Set<LinkMan> linkMans = customer.getLinkMans();//对象导航查询for(LinkMan linkMan : linkMans) {System.out.println(linkMan);}}
查询一个联系人,获取该联系人的所有客户
@Autowiredprivate LinkManDao linkManDao;@Testpublic void testFind() {LinkMan linkMan = linkManDao.findOne(4l);Customer customer = linkMan.getCustomer(); //对象导航查询System.out.println(customer);}
对象导航查询的问题分析
问题1:我们查询客户时,要不要把联系人查询出来?
分析:如果我们不查的话,在用的时候还要自己写代码,调用方法去查询。如果我们查出来的,不使用时又会白白的浪费了服务器内存。
解决:采用延迟加载的思想。通过配置的方式来设定当我们在需要使用时,发起真正的查询。
配置方式:
/*** 在客户对象的@OneToMany注解中添加fetch属性* FetchType.EAGER :立即加载* FetchType.LAZY :延迟加载*/@OneToMany(mappedBy="customer",fetch=FetchType.EAGER)private Set<LinkMan> linkMans = new HashSet<>(0);
问题2:我们查询联系人时,要不要把客户查询出来?
分析:例如:查询联系人详情时,肯定会看看该联系人的所属客户。如果我们不查的话,在用的时候还要自己写代码,调用方法去查询。如果我们查出来的话,一个对象不会消耗太多的内存。而且多数情况下我们都是要使用的。
解决: 采用立即加载的思想。通过配置的方式来设定,只要查询从表实体,就把主表实体对象同时查出来
配置方式
/*** 在联系人对象的@ManyToOne注解中添加fetch属性* FetchType.EAGER :立即加载* FetchType.LAZY :延迟加载*/@ManyToOne(targetEntity=Customer.class,fetch=FetchType.EAGER)@JoinColumn(name="cst_lkm_id",referencedColumnName="cust_id")private Customer customer;
5.2 使用Specification查询
/*** Specification的多表查询*/@Testpublic void testFind() {Specification<LinkMan> spec = new Specification<LinkMan>() {public Predicate toPredicate(Root<LinkMan> root, CriteriaQuery<?> query, CriteriaBuilder cb) {//Join代表链接查询,通过root对象获取//创建的过程中,第一个参数为关联对象的属性名称,第二个参数为连接查询的方式(left,inner,right)//JoinType.LEFT : 左外连接,JoinType.INNER:内连接,JoinType.RIGHT:右外连接Join<LinkMan, Customer> join = root.join("customer",JoinType.INNER);return cb.like(join.get("custName").as(String.class),"xiaomifeng1010");}};List<LinkMan> list = linkManDao.findAll(spec);for (LinkMan linkMan : list) {System.out.println(linkMan);}}
ORM框架之Spring Data JPA(三)高级查询---复杂查询相关推荐
- ORM框架之Spring Data JPA(二)spring data jpa方式的基础增删改查
上一篇主要在介绍hibernate实现jpa规范,如何实现数据增删改查,这一篇将会着重spring data jpa 一.Spring Data JPA 1.1 Spring Data JPA介绍: ...
- ORM框架之Spring Data JPA(一)Hibernate实现JPA规范
一.ORM简述 ORM(Object-Relational Mapping) 表示对象关系映射.在面向对象的软件开发中,通过ORM,就可以把对象映射到关系型数据库中.只要有一套程序能够做到建立对象与数 ...
- Spring Data JPA 实现多表关联查询
原文链接:https://blog.csdn.net/johnf_nash/article/details/80587204 多表查询在spring data jpa中有两种实现方式,第一种是利用hi ...
- Spring Data JPA 从入门到精通~查询结果的处理
参数选择(Sort/Pageable)分页和排序 特定类型的参数,Pageable 并动态 Sort 地将分页和排序应用于查询 案例:在查询方法中使用 Pageable.Slice 和 Sort. P ...
- Spring Data JPA 多条件判空查询
Spring Data JPA虽然大大的简化了持久层的开发,但是在实际开发中,很多地方都需要高级动态查询. 使用@Query注解,这种方式可以直接在Repository里面写sql,但是这种方式的问题 ...
- Spring Data Jpa多表联合分页查询
参考:https://blog.csdn.net/qq_36144258/article/details/80298354 近期一个项目用到Spring Data Jpa,Jpa用来做单表查询非常的简 ...
- Spring Data JPA 从入门到精通~查询方法的创建
查询方法的创建 内部基础架构中有个根据方法名的查询生成器机制,对于在存储库的实体上构建约束查询很有用,该机制方法的前缀 find-By.read-By.query-By.count-By 和 get- ...
- Spring Data JPA Specification多表关联查询
需求:有一个流量计的设备,流量计有一个所属罐区id,想要通过所属罐区查到所关联的这个罐区的编码以及名称. 1.流量计实体类: 主要是给流量计实体添加了以下属性,通过tank_area_id关联: pa ...
- 【Spring Data JPA自学笔记三】Spring Data JPA的基础和高级查询方法
文章目录 调用接口的基础方法查询 Repository CrudRepository PagingAndSortingRepository JPARepository JpaSpecification ...
最新文章
- 新浪微博登录接口实例
- swift_015(Swift 的函数)
- js操作HTML的select
- 【FI学习笔记】AR部分快速IMG配置
- 百练 1363.Rails
- 用户登录提交前,密码加密传输
- VC++访问HTTPS服务器(不受限制)
- Oracle锁表处理
- pix4d无人机影像处理_让无人机创造更大价值?你还差一个Pix4D培训会!
- 使用信号灯法,标志位解决测试生产者消费者问题(源码解析、建议收藏)
- Photoshop 入门教程「6」如何更改图像大小?
- PIC单片机软件平台----MPLAB IDE和MPLAB X IDE
- 量子力学 计算机应用,有了九章计算机:但我们离量子力学还很远~
- 科创板发行上市审核44个问题解答汇编(总11期)
- Classification-Driven Dynamic Image Enhancement
- DNS服务器解析问题
- Android Studio获取数字签名(SHA1)
- 基于微信小程序Map标签及高德地图开源方法实现路径导航
- jQuery的jsTree入门使用
- 机器学习中的数学——粒子群算法(Particle Swarm Optimization, PSO)(三):改进的粒子群算法