欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

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