我基于Twitter的搜索聚类推文,并尝试使用Java中的Hibernate将结果存储在数据库中。当我尝试保存SearchResults对象时,出现如下错误:
org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session
我需要做什么才能让TweetCluster.java和SearchResults.java指向数据库中相同的推文表?我可以更改TweetCluster.java,使其指向一个单独的表,再次存储推文,但这似乎是浪费空间。
我已经拿出了如下所示的重要代码。
@Entity
@Table(name="search_results")
public class SearchResults {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long searchId;
@ManyToMany(targetEntity = Tweet.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER)
@OrderColumn(name="orderIndex")
private List<Tweet> tweets;
@OneToMany(targetEntity = TweetCluster.class, cascade=CascadeType.ALL, fetch=FetchType.EAGER, orphanRemoval=true)
@OrderColumn(name="orderIndex")
private List<TweetCluster> clusters;
public SearchResults() {
tweets = new ArrayList<Tweet>();
clusters = new ArrayList<TweetCluster>();
}
public List<Tweet> getTweets() {
return tweets;
}
public void addTweet(Tweet tweet){
tweets.add(tweet);
}
public void addCluster(TweetCluster cluster){
clusters.add(cluster);
}
public List<TweetCluster> getClusters() {
return clusters;
}
}
@Entity
@Table(name="tweet_cluster")
public class TweetCluster {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
private String name;
@ManyToMany(targetEntity = Tweet.class, fetch=FetchType.EAGER)
@OrderColumn(name="orderIndex")
private List<Tweet> tweets;
public TweetCluster(){
tweets = new ArrayList<Tweet>();
}
public TweetCluster(String name){
this();
this.name=name;
}
public long getId(){
return id;
}
public void setId(long id){
this.id = id;
}
public List<Tweet> getTweets() {
return tweets;
}
public void addTweet(Tweet tweet){
tweets.add(tweet);
}
}
@Entity
@Table(name="tweet")
public class Tweet {
@Id
@GenericGenerator(name="assigned", strategy = "assigned")
private long tweetId;
private String text;
public Tweet(){
}
public long getTweetId() {
return tweetId;
}
public void setTweetId(long id){
this.tweetId = id;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
}
修改
要保存结果,我运行如下代码:
SearchResults searchResult = new SearchResults();
searchResult .addCluster(new TweetCluster("cluster1"));
searchResult .addCluster(new TweetCluster("cluster2"));
searchResult.addTweet(new Tweet("Tweet 1"));
searchResult.addTweet(new Tweet("Tweet 2"));
searchResult.addTweet(new Tweet("Tweet 3"));
session.saveOrUpdate(searchResult);
在saveOrUpdate
中抛出异常答案 0 :(得分:0)
事实证明问题非常简单。 Tweet的生成器已分配。在我的单元测试中,我忘了分配一个id。因此,一些推文的id为零。