mysql duplicate jpa,Spring数据JPA复合键重复键记录插入导致更新

I have one entity having composite key and I am trying to persist it by using spring data jpa repository to mysql databse as given below:

@Embeddable

public class MobileVerificationKey implements Serializable{

private static final long serialVersionUID = 1L;

@Column(name="CUSTOMERID")

private Long customerId;

@Column(name="CUSTOMERTYPE")

private Integer customerType;

@Column(name="MOBILE")

private Long mobile;

@Embeddable

public class MobileVerificationKey implements Serializable{

private static final long serialVersionUID = 1L;

@Column(name="CUSTOMERID")

private Long customerId;

@Column(name="CUSTOMERTYPE")

private Integer customerType;

@Column(name="MOBILE")

private Long mobile;

//getter and setters

}

And Entity as

@Entity

@Table(name="mobileverificationdetails")

public class MobileVerificationDetails {

@EmbeddedId

private MobileVerificationKey key;

@Column(name="MOBILETYPE")

private String mobileType;

@Column(name="MOBILEPIN")

private Integer mobilePin;

//getters and setters

}

My spring data jpa repository look like this:

public interface MobileVerificationDetailsRepository extends

CrudRepository {

@Override

MobileVerificationDetails save(MobileVerificationDetails mobileVerificationDetails);

@Override

MobileVerificationDetails findOne(MobileVerificationKey id);

}

Now if I am trying to add duplicate record with same key for original record and different values for other fields .when i try to insert second record it results in update of existing record with new values instead of throwing exception for violating primary key constraint...can any one please explain me this behavior.

解决方案

The easiest (and least invasive) way to work around this is probably by making sure the id only gets set right before the persist. This can be achieved in a @PrePersist callback:

abstract class MobileVerificationDetails {

@EmbeddedId

private MobileVerificationKey id;

@PrePersist

void initIdentifier() {

if (id == null) {

this.id = … // Create ID instance here.

}

}

}

Alternatively to that you can enforce persist(…) being used by implementing Persistable and implementing isNew() accordingly. Make sure this method returns true on first insert. We usually see people holding a transient boolean flag that is updated in an @PostPersist/@PostLoad annotated method.

abstract class AbstractEntity implements Persistable {

private @Transient boolean isNew = true;

@Override

public boolean isNew() {

return isNew;

}

@PostPersist

@PostLoad

void markNotNew() {

this.isNew = false;

}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值