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

JPA 联合主键配置

程序员文章站 2022-03-02 15:33:13
...

JPA 联合主键的配置,自己找了网上的一些写法,参考https://www.cnblogs.com/boywwj/p/8031106.htmlhttps://baijiahao.baidu.com/s?id=1617918647119711819&wfr=spider&for=pc,有两种实现方式:1. 使用 @Embeddable   @EmbedId 注解   2. @IdClass  @Id  。第一种,需要在主实体类里面 声明一个被@Embeddable注释的类的对象 字段,并且此字段上需要加上  @EmbedId

@Embeddable
public class PeopleKey implements Serializable  {
     
    @Column(name = "name")
    private String name;
     
    @Column(name = "idcardno")
    private String idcardno;
    // 省略setter,getter方法
 
    @Override
    public String toString() {
        return "PeopleKey [name=" + name + ", idcardno=" + idcardno + "]";
    }
} 



@Entity
@Table(name = "people")
public class People extends PeopleKey{
    // 复合主键要用这个注解
    @EmbeddedId
    private PeopleKey id;
 
    @Column(name = "age")
    private int age;

}

#摘自他人博客

编码过程中涉及到,对象dto 之间的copy ,上面写法就不友好了,自己摸索的写法,用@IdClass:

@MappedSuperclass
public class JobStatisticsKey implements Serializable{

    @Id
    @Column(name = "job_date")
    private String jobDate;

    @Id
    @Column(name = "worker_group")
    private String workerGroup;

   ##getter & setter 
   ## 参考别人博客要重写 hashCode & equals 方法,为什么,还有些疑问
}

@Entity
@Table(name = "t_job_statistics")
@IdClass(JobStatisticsKey.class)
public class JobStatistics extends JobStatisticsKey{

    @Column(name = "avg_exec_time")
    private BigDecimal avgExecTime;

    @Column(name = "avg_wait_time")
    private BigDecimal avgWaitTime;

    @Column(name = "max_exec_time")
    private Integer maxExecTime;
## getter  & setter 
}

还有一个需要注意就是 ,JpaRepository 的Id 泛型,写主键类JobStatisticsKey,我开始写的Long 也没报错,是没用到他的getOne或者deleteById方法:

@Repository
public interface JobStatisticsRepository extends JpaRepository<JobStatistics, JobStatisticsKey> {

    void deleteByJobDate(String jobDate);

    List<JobStatistics> findByJobDateBetween(String startTime ,String endTime);
}