Srinivas
Srinivas

Reputation: 364

Hibernate exception while inserting

I have two tables Application, MR. I am using JPA, Hibernate for ORM mapping. I have a problem while inserting the records. Please help me.

* Mr_id in application table is a foreign key

* code in mr table is unique key

* mr_id in MR table is primary key

Application Table:

(id, mr_id)

(1, null)

(2, null)

MR TABLE:

(mr_id, code, name)

(1, code1, mr1)

(2, code2, mr2)

I have a jpa repository :   ApplicationRepository

application = Application(1)

application.mr = MR(1,code1,mr1)

when I run  : applicationRepository.save(applications[0])
it causes a problem

Reason: Mr record with (1,code1,mr1) alredy present in mr table. 

How to solve this problem with JPA, Hibernate annotation

---------------------------------
    Application {
       @Id
       var id: Int;

       @ManyToOne(cascade = [(CascadeType.PERSIST)])
       @JoinColumn(name = "mr_id")
       var mr: MR? = null
    }

Upvotes: 0

Views: 101

Answers (1)

Anatoly Samoylenko
Anatoly Samoylenko

Reputation: 701

I think this happens because JPA is trying to persist MR (because they detached) after persist Application, but MR with mr_id = 1 already exists. Try to find mr with mr_id = 1 (not create) and set this mr to application.mr

Upvotes: 1

Related Questions