我目前正在开展一个学校项目,我们必须创建自己的“Twitter”应用程序,并且我在域对象的持久性方面遇到了一些麻烦.
我的帐户类(为便于阅读而简化):
@Entity
public class Account implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
@Column(unique = true)
private String email;
@OneToMany
private final List following = new ArrayList<>();
@OneToMany(mappedBy = "tweetedBy", cascade = ALL)
private final List tweets = new ArrayList<>();
我的推文类(为便于阅读而简化):
@Entity
public class Tweet implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
private String content;
@ManyToOne
private Account tweetedBy;
@OneToMany(cascade = CascadeType.PERSIST)
@JoinTable(name = "tweet_likes")
private final List likedBy = new ArrayList<>();
@OneToMany(cascade = CascadeType.PERSIST)
@JoinTable(name = "tweet_mentions")
private final List mentions = new ArrayList<>();
持久代码(简化):
Account a1 = new Account("user1@gmail.com", "password1");
Account a2 = new Account("user2@gmail.com", "password2");
Account a3 = new Account("user3@gmail.com", "password3");
a1.addTweet("Sup mah dudes.");
a1.addTweet("yoyo");
a2.addTweet("Allo Allo #tweeting");
a2.addTweet("#testing yoyo");
a1.getTweets().get(0).addLike(a3);
a1.addFollowing(a3);
em.persist(a1);
em.persist(a2);
em.persist(a3);
我遇到的问题是,LikeBy和提及没有正确持久化.正在生成链接器表并插入数据,但我在插入用户时不断出现重复的条目错误.我相信我正确地建立了关系(单向OneToMany),因为我不希望帐户跟踪它所提到的推文.
我尝试过的:
> @JoinColumn用于喜欢和提及(导致重复插入)
>对于喜欢和提及的@JoinTable(导致重复插入)
>只有@OneToMany用于喜欢和提及(这不会导致错误,但会为两个关系创建一个链接器表,其中任何一个都不能为null)
> @OneToMany for likes,然后@joinColumn提及nullable = true(这导致你不能在推文中提及你的情况,除非你喜欢它,这是奇怪的行为)
> @OneToMany(cascade = CascadeType.MERGE)(导致重复插入)
Netbeans输出的重复插入错误:
Warning: Local Exception Stack:
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.6.4.qualifier): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'user6@gmail.com' for key 'EMAIL'
Error Code: 1062
Call: INSERT INTO ACCOUNT (AVATARPATH, BIO, EMAIL, ENCRYPTEDPASSWORD, LOCATION, USERNAME, USERROLE, WEBSITE) VALUES (?, ?, ?, ?, ?, ?, ?, ?)
bind => [8 parameters bound]
Query: InsertObjectQuery(domain.Account@3c7f9d54)
我相信这个错误的发生是因为我的JPA imlementation的流程如下:
>帐户持续存在
>推文持续存在(因为它在账户内)
>帐户持续存在(因为它在Tweet内)< - 重复条目
我期待的是:
> 1个链接表,其中包含tweet_id(fk)和表示喜欢的account_id(fk)
> 1个链接表,其中包含tweet_id(fk)和表示提及的account_id(fk)
如果有人可以帮我解释注释或者解释我做错了什么,那将非常感激.
Ty提前获得任何帮助.