我有2個表格:User
和Loan
。用戶有3個字段:id
(PK),first_name
和last_name
。 Loan
表有場user_id
是外鍵User
表: JPA多對一關係CascadeType行爲
我的應用程序的邏輯:當我創造新的Loan
對象,並設置有相應的user
應建立新的獨特的用戶一個新的或設置id
user
納入現有用戶的user_id
。
爲此,我的數據庫在first_name
,last_name
上有一個唯一索引。
的Loan
類使用User
與@ManyToOne
關係:
public class Loan {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne(cascade = {CascadeType.PERSIST, CascadeType.MERGE})
@JoinColumn(name = "user_id")
private User user;
... methods ...
當我添加新用戶,一切都很好,它堅持用新的PK爲DB。但是,當我嘗試添加一個現有的我和異常:
javax.servlet.ServletException: org.springframework.transaction.TransactionSystemException: Could not commit JPA transaction; nested exception is javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.0.v20150309-bf26070): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: java.sql.SQLIntegrityConstraintViolationException: The statement was aborted because it would have caused a duplicate key value in a unique or primary key constraint or unique index identified by 'FIRST_LAST_NAME' defined on 'USER'.
Error Code: 20000
當我再次把@ManyToOne(cascade = CascadeType.MERGE)
我只能夠進入現有的用戶,因爲只有我通過未在DB我堅持一個新的得到一個例外:
javax.servlet.ServletException: org.springframework.dao.InvalidDataAccessApiUsageException: During synchronization a new object was found through a relationship that was not marked cascade PERSIST: User{id=null, firstName='a', lastName='a'}.;
@ManyToOne(cascade = CascadeType.ALL)
沒有工作。
UPDATE
插入代碼的新Loan
是:
user = userService.findByName(firstName, lastName);
if (user == null) {
user = new User(firstName, lastName);
}
loan.setUser(user);
loanService.save(loan);
findByName()
和save()
方法是:
private EntityManager em;
public User findByName(String firstName, String lastName) {
TypedQuery<User> query = em.createQuery(
"SELECT u FROM User u WHERE u.firstName = :firstName " +
"AND u.lastName = :lastName", User.class)
.setParameter("firstName", firstName).setParameter("lastName", lastName);
List<User> users = query.getResultList();
if (!users.isEmpty()) {
return users.iterator().next();
} else {
return null;
}
}
public void save(User user) {
if (user.getId() == null) {
em.persist(user);
} else {
em.merge(user);
}
}
向我們顯示您的代碼插入。 –
請張貼用戶類的代碼。 – LearningPhase
我更新了問題,謝謝 – DimaSan