Spring boot jpa 复合主键
程序员文章站
2022-04-25 07:49:40
...
文章目录
1 创建表
CREATE TABLE "public"."compkeys" (
"p1" varchar(10) COLLATE "pg_catalog"."default" NOT NULL,
"p2" varchar(10) COLLATE "pg_catalog"."default" NOT NULL,
"p3" varchar(10) COLLATE "pg_catalog"."default" NOT NULL,
"d1" varchar(20) COLLATE "pg_catalog"."default",
"d2" varchar(20) COLLATE "pg_catalog"."default",
"d3" varchar(20) COLLATE "pg_catalog"."default",
CONSTRAINT "compkeys_pkey" PRIMARY KEY ("p1", "p2", "p3")
)
;
ALTER TABLE "public"."compkeys"
OWNER TO "postgres";
2 entity 源代码
2.1 主键 CompkeysPkeyDo 源代码
@Embeddable
public class CompkeysPkeyDo implements Serializable {
private static final long serialVersionUID = -2381527359237990252L;
@Column(name = "p1", nullable = false, length = 10)
private String p1;
@Column(name = "p2", nullable = false, length = 10)
private String p2;
@Column(name = "p3", nullable = false, length = 10)
private String p3;
}
2.2 表 CompkeysDo 源代码
@Entity
@Table(name = "compkeys")
public class CompkeysDo implements Serializable {
private static final long serialVersionUID = -5680302008759310410L;
/**
* 复合主键
*/
@EmbeddedId
private CompkeysPkeyDo compkeysPkeyDo;
@Column(name = "d1", nullable = false, length = 20)
private String d1;
@Column(name = "d2", nullable = false, length = 20)
private String d2;
@Column(name = "d3", nullable = false, length = 20)
private String d3;
}
3 Repository 源代码
public interface CompkeysRepository extends JpaRepository<CompkeysDo , CompkeysPkeyDo >, JpaSpecificationExecutor<CompkeysDo > {
@Override
Page<CompkeysDo > findAll(Specification<CompkeysDo > spc, Pageable page);
}
4 Specification源代码
public class SpecificationCompkeysDoPageImpl implements Specification<CompkeysDo > {
private static final long serialVersionUID = -3283028185591662363L;
/**
* 请求参数
* */
private final CompkeysDoRqDto rq;
public SpecificationBKOPidPageImpl(CompkeysDoRqDto rq) {
this.rq = rq;
}
@Override
public Predicate toPredicate(Root<CompkeysDo > root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder criteriaBuilder) {
//查询条件
List<Predicate> predicateList = new ArrayList<>();
Predicate ptmp = criteriaBuilder.like(criteriaBuilder.lower(root.get("compkeysPkeyDo").get("p1")),"%"+rq.getP1().toLowerCase()+"%" );
predicateList.add(ptmp);
//避免重复数据
criteriaQuery.distinct(true);
return criteriaBuilder.and(predicateList.toArray(new Predicate[0]));
}
}
5 服务使用
Sort sort=new Sort(Sort.Direction.DESC, "p1");
Pageable pageable = PageRequest.of(0, 10, sort);
Page<CompkeysDo > all = this.compkeysRepository .findAll(new SpecificationCompkeysDoPageImpl (request), pageable);
推荐阅读
-
Spring Data JPA例子代码[基于Spring Boot、Mysql]
-
spring boot配置文件application.properties配置JPA以及数据源
-
Spring Boot和Thymeleaf整合结合JPA实现分页效果(实例代码)
-
Spring Boot 中 spring.jpa.open-in-view 使用注意点
-
spring boot整合mybatis利用Mysql实现主键UUID的方法
-
在Spring Boot中使用Spring-data-jpa实现分页查询
-
spring boot,JPA和Atomikos实现分布式事务
-
spring boot,hibernate jpa,Mysql集成【原创】
-
spring boot,hibernate jpa,Mysql集成【原创】
-
spring boot 整合JPA bean注入失败