几乎一整天,我都面临着一个涉及 JPA/Eclipselink 和 MySql 的问题。在我的 MySQL 数据库中,我通过以下方式配置了两个表:
Table: Member
memberID int(11) PK AI
desiresID int(11)
email
firstName
lastName
password
Table: MemberDesire
desireID int(11) PK AI
with ForeignKey constraint between Member and MemberDesire
using Member.desireID and MemberDesire.desireID
在 Eclipse 中,我让这些表自动导入,它可以完美地识别链接。这两个类如下所示:
@Entity
public class Member implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private int memberID;
private String email;
private String firstName;
private String lastName;
private String password;
//bi-directional many-to-one association to MemberDesire
@ManyToOne(cascade=CascadeType.PERSIST)
@JoinColumn(name="desiresID")
private MemberDesire memberDesire;
和:
@Entity
@Table(name="MemberDesires")
public class MemberDesire implements Serializable {
private static final long serialVersionUID = 1L;
@Id
private int desireID;
private int maximumAge;
private int minimumAge;
//bi-directional many-to-one association to Member
@OneToMany(mappedBy="memberDesire")
private List<Member> members;
现在,当我尝试将包含 MemberDesire 的新成员持久保存到数据库时,会出现以下错误:
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Cannot add or update a child row: a foreign key constraint fails (`test`.`member`, CONSTRAINT `desireKey` FOREIGN KEY (`desiresID`) REFERENCES `MemberDesires` (`desireID`) ON DELETE NO ACTION ON UPDATE NO ACTION)
Error Code: 1452
Call: INSERT INTO MEMBER (EMAIL, FIRSTNAME, LASTNAME, PASSWORD, desiresID) VALUES (?, ?, ?, ?, ?,)
bind => [5 parameters bound]
持久化本身是通过这种方式完成的:
EntityManager em = Persistence
.createEntityManagerFactory("TestProject")
.createEntityManager();
EntityTransaction entityTransaction = em.getTransaction();
entityTransaction.begin();
member = new Member();
member.setFirstName(firstName);
member.setLastName(lastName);
member.setEmail(email);
member.setPassword(password);
MemberDesire desire = new MemberDesire();
member.setMemberDesire(desire);
List<Member> members = new ArrayList<Member>();
members.add(member);
desire.setMembers(members);
em.persist(member);
entityTransaction.commit();
em.close();
我将非常感谢您能给我的任何帮助!!谢谢 :)
塞巴斯蒂安