1

I have got the following tables: Tag, Employee, Location. Employee and Location can have more tags. I think it's best to create new tables for these relations so: employee_tag and location_tag.

How do I do this using JPA? Right now I got this: Employee class:

@OneToMany()
@JoinTable(name="employee_tag", joinColumns={
    @JoinColumn(name="ID_employee", referencedColumnName="ID")
}, inverseJoinColumns={
    @JoinColumn(name="ID_tag", referencedColumnName="ID")
})
private Collection<Tag> tags;

Tag class:

@ManyToOne()
private Employee employee;

It creates a new table named employee_tag but tag still has a column employee_ID. How do I link the tag to this table?

Klaasvaak
  • 5,634
  • 15
  • 45
  • 68
  • 1
    See http://stackoverflow.com/questions/5165743/spring-roo-hibernate-one-to-many-relation-creates-additional-table – axtavt Apr 22 '12 at 14:11
  • Oke nice, so what I want is almost default. But there is still an employee_ID in the tag table. – Klaasvaak Apr 22 '12 at 19:19

1 Answers1

2

If you need a unidirectional one-to-many association, you have not to put the employee association in the tag class, you have to declare the association in the Employee class.

@Entity
public class Employee {
   @OneToMany()
   @JoinTable(name="employee_tag", joinColumns={
   @JoinColumn(name="ID_employee", referencedColumnName="ID")
   }, inverseJoinColumns={
   @JoinColumn(name="ID_tag", referencedColumnName="ID")
   })
   public Collection<Tag> tags;
   ...
}

@Entity
public class Tag {      
   ...
}

Otherwise you can do bidirectional association as below:

@Entity
public class Employee {
   @OneToMany(mappedBy="troop")
   public Collection<Tag> tags;
   ...
}

@Entity
public class Tag {
   @ManyToOne
   @JoinColumn(name="employee_fk")
   public Employee employee;
   ...
}

Take a look at hibernate annotations doc

landal79
  • 1,520
  • 1
  • 11
  • 26