10

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?

El Guapo
  • 5,581
  • 7
  • 54
  • 82

2 Answers2

17

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):

jpkroehling
  • 13,881
  • 1
  • 37
  • 39
  • 1
    Thanks, this worked. I really, for some reason, thought Hibernate would make the assumption for me that I wanted it to be Tag to be updated with my files since I had the relationship Annotated on both sides. – El Guapo Dec 21 '10 at 15:53
  • The link does not exist more :( you can provide another source? – Filipe Feb 20 '14 at 21:30
  • I've changed the answer to point to the most current version. – jpkroehling Feb 21 '14 at 08:03
  • sorry, i have the same dubt.. I can't understand why hibernate does not put the id of the file in the saved tag. What other id can be, if not the id of the file that i'm saving in that moment, why not hibernate does not get that id e does not insert it in the FK of the Tag? Why Hibernate can't? – Andrea Scarafoni Apr 15 '21 at 16:06
3

Foreign key in the database reflects the state of Tag.file (since Tag is the owning side of the relationship as a "many" side in a bidirectional many-to-one relationship).

I can't see where you set it.

axtavt
  • 239,438
  • 41
  • 511
  • 482