Hi
I m using Hibernate to work with a local SQLServer.
These are my classes:
Person:
Code:
@Id
public String getId()
@OneToOne(fetch=FetchType.EAGER,cascade=CascadeType.ALL)
public Metadata getMetadata()
@OneToMany(mappedBy = "person", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
public List<Nickname> getNicknames()
Nickname:
Code:
@Id
public String getId()
@ManyToOne
public Person getPerson()
public String getNickname()
Metadata:
Code:
@Id
public String getId()
@OneToOne(mappedBy="metadata")
public Person getPerson()
@CollectionOfElements(fetch = FetchType.EAGER)
@MapKey(columns = @Column(name = "fieldKey", nullable = false))
public Map<String, String> getMetadata()
I use this code to create the objects:
Code:
Person p = new Person();
p.setId("p1");
p.setNicknames(new ArrayList<Nickname>());
Nickname n= new Nickname();
n.setId("n1");
n.setPerson(p);
n.setNickname("n1");
p.getNicknames().add(n);
Metadata metadata = new Metadata();
metadata.setId("md1");
metadata.setPerson(p);
metadata.setMetadata(new HashMap<String, String>());
metadata.getMetadata().put("n1", "v1");
metadata.getMetadata().put("n2", "v2");
p.setMetadata(metadata);
personDao.create(p);
This creates all the raws in the DB as it should.
However, running this line:
Code:
System.out.println(pd.read("p1").getNicknames().size());
Prints "2", although there is only one Nickname raw in DB and in my creation code.
This is because Hibernate uses a select with Join with the Metadata_metadata table, which has two raws (n1=v1,n2=v2).
How does Hibernate know it should create only one Person object, and even only one Nickname object (although it gets two lines for the select), but puts the Nickname twice in the Nicknames list in that Person?
BTW - changing the Nicknames property to be a Set instead of a List works fine (but a Set is not good for me...).
Thanks
Yair