【发布时间】:2011-05-13 19:03:17
【问题描述】:
我有一个大型数据集,我正在批量导入其中的行看起来像
(news_id, category_id_1, category_id_2, ..., category_id_9)
每个category_id_x 都是来自一组固定类别的整数。
我想将这多个类别映射到 m2m 关系中以便更快地搜索。
我有一个News 表和一个Category 表。
Category 表将类别 ID 映射到类别名称。
我已经在 JPA 中为各种 News 字段设置了所有映射,并且我想重用此代码。
我的问题是如何在 JPA 中导入这些 m2m 关系。
我正在按照以下思路进行思考,但我收到错误消息,提示您无法手动创建 Category 对象。
// News object
@Entity
@Table(name = "news", schema = "public", uniqueConstraints = {})
public class News implements java.io.Serializable {
// Fields
@Column(name = "asx_code")
private String asxCode;
@Id
@Column(name = "annnum", unique = true, nullable = false)
private String annnum;
@Column(name = "company_name")
private String companyName;
...
...
@ManyToMany()
@JoinTable(name="announcement_types",
joinColumns= @JoinColumn(name="annnum"),
inverseJoinColumns=@JoinColumn(name="report_type"))
private Collection<ReportType> reportType;
function m(String) {
// extract and return data from datasource
}
// Create a news object from 9 different report types
News o = new News();
java.util.Collection<ReportType> types = new HashSet();
types.add(new ReportType(toInt(m("RepType0"))));
types.add(new ReportType(toInt(m("RepType1"))));
types.add(new ReportType(toInt(m("RepType2"))));
types.add(new ReportType(toInt(m("RepType3"))));
types.add(new ReportType(toInt(m("RepType4"))));
types.add(new ReportType(toInt(m("RepType5"))));
types.add(new ReportType(toInt(m("RepType6"))));
types.add(new ReportType(toInt(m("RepType7"))));
types.add(new ReportType(toInt(m("RepType8"))));
types.add(new ReportType(toInt(m("RepType9"))));
o.setReportType(types);
// Query
try {
EntityTransaction entr = em.getTransaction();
entr.begin();
em.persist(row); # row is our News object
entr.commit();
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
// ERROR
SEVERE: Could not synchronize database state with session
org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: edu.unsw.eventstudy.shared.dto.ReportType
编辑:
似乎我正在处理分离实体的概念。这是在 Hibernate 中使用未保存值映射或 isSaved 属性解决的。现在在 JPA 中寻找解决方案。
【问题讨论】:
-
请复制完整的错误信息,以及触发它的代码。
-
添加了上面的代码。基本上对于每个新闻项目,我想在第二个表中为其所有报告类型创建条目,但是条目已经存在于第二个表中,并且我已经知道要关联的键。
标签: hibernate jpa many-to-many