I have a similar problem:
I want to map these two tables:
WOOD (Table)
---------------
ID_WOOD (Primary Key)
NAME
TREE (Table)
-------------
ID_WOOD (Primary Key AND Foreign Key)
ID_TREE (only Primary Key)
NAME
The Relationship: OneToMany (one Wood can consist of at least one Tree or more Trees)
My Table WOOD:
Code:
@Entity
@Table(name = "WOOD)
public class Wood implements Serializable {
private Integer idWood;
@Id
@Column(name = "ID_WOOD")
// getter/setter
private String name;
@Column(name = "NAME")
// getter/setter
//hashCode/equals
..
// relationship to TREES
private Set<Tree> trees = new HashSet<Tree>();
@OneToMany(mappedBy = "wood", targetEntity = Tree.class)
@JoinColumn(name = "ID_WOOD", referencedColumnName = "ID_WOOD", nullable = false, insertable = false, updatable = false)
// getter/setter
}
My Table TREE :
Code:
@Entity
@Table(name = "TREE )
public class Tree implements Serializable {
// Tree consists of a composite key (ID_TREE, ID_WOOD)
public static class TreeID implements Serializable
{
@Basic(optional = false)
@Column(name = "ID_TREE", nullable = false, columnDefinition = "integer")
private Integer idApplication;
@Basic(optional = false)
@Column(name = "ID_WOOD", nullable = false, columnDefinition = "integer")
private Integer idDocument;
//hashCode/equals
..
}
@EmbeddedId
private TreeID treeID = new TreeID();
// getter/setter
// relationship to Wood (this does not work!!)
private Wood wood;
@ManyToOne(optional = true, targetEntity = Wood.class)
@JoinColumn(name = "ID_WOOD", referencedColumnName = "ID_WOOD", nullable = false, insertable = false, updatable = false)
// getter/setter
}
My Relationship does NOT work properly.
(I have tried it also with PrimaryKeyJoinColumn, without success..I guess this is only for OneToOne-Relationships)
This HQL
"from Wood w"
returns a correct SQL:
Code:
select
wood0_.ID_WOOD as IDWOOD _829_,
wood0_.NAME as name_829_,
from
MYSCEME.WOOD wood0_
But this HQL
"from Tree t"
returns a corrupted SQL:
Code:
select
tree0_.ID_WOOD as IDWOOD _829_,
tree0_.ID_TREE as IDTREE _829_,
tree0_.wood as wood3_829_,
tree0_.NAME as name829_,
from
MYSCEME.TREE tree0_
This:
tree0_.wood as wood3_829_, should be a relationship (!) and has not to be in this sql-statement. So I guess, my Mapping is false! But Hibernate does not complain anything when validating the schema.
I do not know, what is wrong?
Is it possible to mapp a bidirectional mapping?
How can I improve this mapping?