我有两个实体:
@Entity 公共类文件 ..... .. @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @OneToMany(fetch = FetchType.LAZY,mappedBy =file,cascade = CascadeType.ALL) private List< Tag>标签; ....... 其他属性 ....... @实体公共类标记。 ...... @Id @GeneratedValue(strategy = GenerationType.AUTO) private int id; @ManyToOne @JoinColumn(name =file_id)私有文件文件; @Column 私人字符串标签; ....... 其他物业 .......我试图通过执行以下操作来插入到File(和随后的Tag)中:
文件文件=新文件(); 标签标签=新标签(); tag.setTag(tag1); Tag2 tag2 = new Tag(); tag2.setTag(tag2); 列表< Tag> tags = new ArrayList< Tag>(); tags.add(tag); tags.add(tag2); file.setTags(tags); ---在这里添加其他文件属性---然后插入文件在我的DAO中使用:
sessionFactory.getCurrentSession()。saveOrUpdate(file);在我的日志中,我看到一个插入到我的文件表中,并且2插入到我的标记表中,但是,我的标记表中指向我的文件表(file_id)的外键是NULL。
我可能做错了什么?
解决方案不设置标签的文件,只是标签的文件。请记住,在OOP中,与关系模型相反,您必须设置关系的两端。您不能仅仅因为您将一组标签添加到文件而从标签导航到文件。就你而言,你可以从文件导航到标签(即:列出文件的所有标签)。通过仅查看标签,您无法确定标签属于哪个文件。
通常做的是在其中一个模型中使用helper方法,如下所示:
public void addTag(Tag tag){ this.tags.add(tag); tag.setFile(this); }请参阅这个例子(来自Hibernate的测试套房):
I have two entities:
@Entity public class File ....... @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; @OneToMany(fetch=FetchType.LAZY, mappedBy="file", cascade=CascadeType.ALL) private List<Tag> tags; ....... OTHER PROPERTIES ....... @Entity public class Tag ....... @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; @ManyToOne @JoinColumn(name="file_id") private File file; @Column private String tag; ....... OTHER PROPERTIES .......I am trying to insert into File (and subsequently Tag) by doing the following:
File file = new File(); Tag tag = new Tag(); tag.setTag("tag1"); Tag2 tag2 = new Tag(); tag2.setTag("tag2"); List<Tag> tags = new ArrayList<Tag>(); tags.add(tag); tags.add(tag2); file.setTags(tags); ---Add other file attributes here---I am then inserting the file in my DAO using:
sessionFactory.getCurrentSession().saveOrUpdate(file);In my logs I see an insert into my "file" table and 2 inserts into my tag table, however, the foreign key in my tag table that points to my file table (file_id) is NULL.
What could I possibly be doing wrong?
解决方案You are not setting the File for a Tag, just the Tag's to a File. Remember that in OOP, as opposed to the Relational Model, you have to set both ends of a relationship. You can't navigate from Tag to File just because you added a set of Tags to a File. In your case, you can just navigate from File to Tag (ie: list all Tags for a File). You can't tell which File a Tag belongs to, by looking only at the Tag.
What is usually done is a helper method in one of the models, like this:
public void addTag(Tag tag) { this.tags.add(tag); tag.setFile(this); }See this for an example (from Hibernate's test suite):
更多推荐
Hibernate插入级联不插入外键
发布评论