I'm just looking into the use of Hibernate Annotations vs mapping files and porting a simple demo over to hibernate annotations. At the moment the demo works, however instead of using my existing table structure to store a collection, Hibernate is generating a new table but storing the exact same data in it.
In my database I have a users table [id (PK), username, etc...] and an authorities table [userid (PK), authority (PK)]. The authorities table has a foreign key constraint from userid to id in the users table such that one user can have many authorities. The two fields of the authorities table also make up a composite primary key.
I have an annotated User class and an annotated Authority class like so:
Code:
@Entity
@Table(name="users")
public class User
{
private int id;
private String username;
//etc...
private Set authorities = new HashSet();
public void setId(int idIn) { id = idIn; }
public void setUsername(String userIn) { username = userIn; }
public void setAuthorities(Set authIn) { authorities = authIn; }
@Id @GeneratedValue(strategy=GenerationType.AUTO)
public int getId() { return id; }
@Column(unique=true)
public String getUsername() { return username; }
@OneToMany(targetEntity=Authority.class, fetch=FetchType.EAGER)
public Set<Authority> getAuthorities() { return authorities; }
}
Code:
@Entity
@Table(name="authorities")
public class Authority
{
private int id;
private String authority;
public void setId(int idIn) { id = idIn; }
public void setAuthority(String authIn) { authority = authIn; }
@Id
@Column(name="userid")
public int getId() { return id; }
@Id
public String getAuthority() { return authority; }
}
If I use the above code and create a user with some authorities then save the user using Hibernate then a new table gets generated called users_authorities with a users_id field and a authorities_authority field. The value placed in the users_id field is what should go into the authorities.userid field in my own database structure, and likewise the users_authority field should go into the authorities.authority in my own database.
Any ideas as to where I've gone wrong? I annotated the Authority class with the table name authorities so I don't understand why Hibernate is ignoring this and using users_authorities instead. Other than this the demo is working fine.
Thanks.