我有USER(id)和CONTACT(user_id,first,last)表。CONTACT.user_id是用户表的外键。
在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) 我做错什么了?谢谢!
发布于 2015-02-24 07:14:39
问题可能出在您的id生成策略上(假设您正确地初始化了联系人)。必须将user对象插入到DB中以设置其id,但同时联系人需要此id为有效对象。它们都必须发生在同一事务中。
如果您将JPA的日志记录级别切换为fine (在perstitance.xml中),您将很可能看到插入用户和联系人的顺序,但是联系人的user_id为0。
因此,a)确保您在联系人中显式设置用户(正如您所说的,关系由联系人管理。b)在用户上设置联系人。c)持久化(在一个事务中)。取决于您的JPA实现,它可能仍然不起作用(检查发出的查询,最有可能的是在联系时插入,然后更新)。将生成策略更改为TABLE,使用TABLE JPA获取下一个空闲ID,将其分配给对象并执行插入,以便在插入之前是“已知的”。
https://stackoverflow.com/questions/28683427
复制相似问题