Murilo
Murilo

Reputation: 4553

Mapping @ManyToMany relationship with hibernate annotation

UPDATE: I saw the database relationships and I realized that the Module table has two references to the Unit Table (nid, unnr), but Unit Table doesnt have a reference to Module Table, it has only to subrack table using the nid.

Upvotes: 1

Views: 129

Answers (1)

Yoeri Smets
Yoeri Smets

Reputation: 141

first of all, all your code that is currently showing is mixing up some things...

You define a @JoinTable annotation, which means that you have 3 tables, 1 with units, 1 with modules and one with the id's of both entities in it...

2nd remark I have is that you talk about a One-To-Manny relationship between a module and units, but in your example code you put a Many-To-Many...

If I follow your description I would build it like this in code:

@Entity
@Table(name = "unit")
public class Unit {
@Column(name = "nid")
private int nid;
@Id
@GeneratedValue
@Column(name = "unnr")
private int unnr;
@Column(name = "unhwtype")
private int unhwtype;
@Column(name = "unslot")
private int unslot;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "nid")
private Module module;

@Entity
@Table(name = "module")
public class Module {
@Column(name = "nid")
private int nid;
@Id
@Column(name = "mpos")
private int mpos;
@Column(name = "mhwtype")
private int mhwtype;
@OneToMany(mappedBy = "module", cascade = {CascadeType.ALL})
private Set units;

The problem her is that I'm not sure if this is going to work, since the nid is not an ID column in the module Entity, I think you will need to change your design so that nid is an Id column... You can give it a try with this code and hope it works, otherwise change the nid in the module Entity to an ID..

Upvotes: 1

Related Questions