JPA 联合主键配置

本文详细介绍了在Java持久化API (JPA)中配置联合主键的两种方法:使用@Embeddable和@EmbedId注解,以及使用@IdClass和@Id注解。通过具体代码示例,展示了如何在实体类中实现复合主键,并强调了在使用复合主键时,JpaRepository泛型参数的重要性。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >


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

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值