我有USER(id)和CONTACT(user_id,first,last)表。 CONTACT.user_id是USER表的外鍵。SpringDataJPA保存OneToOne關係獲取無法添加或更新子行:外鍵約束失敗
在User.java:
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
//bi-directional one-to-one association to Contact
@OneToOne(mappedBy="user", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private Contact contact;
在Contact.java:
@Id
// @GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name="USER_ID")
private int userId;
//bi-directional one-to-one association to User
@OneToOne(cascade = CascadeType.ALL)
@PrimaryKeyJoinColumn(name = "User_id")
private User user;
當我運行userRepository.save(用戶),我得到:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.5.0.v20130507-3faac2b): org.eclipse.persistence.exceptions.DatabaseException Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`mysite`.`contact`, CONSTRAINT `fk_CONTACT_USER1` FOREIGN KEY (`USER_ID`) REFERENCES `user` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION)
什麼我做錯了嗎?謝謝!
你可以顯示你的代碼中包含'userRepository.save(user)'的部分嗎? – jfun 2015-02-23 21:17:03