What I am trying to do is make my Play! project use an already existing database on MySQL. The connection to the database is fine. My problem lies with linking the foreign keys constraints in the MySQL database to my Play! project’s class’s @ManyToOne relationships.
So basically what I currently have is in my database is:
...
create table clubadmin (
clubadmin_id int not null auto_increment,
club_id int not null,
user_id int not null,
primary key (clubadmin_id),
constraint fk_clubadmin_club_id foreign key (club_id) references club(club_id),
constraint fk_clubadmin_user_id foreign key (user_id) references user(user_id)
);
create table special(
spec_id int not null auto_increment,
spec_datetime datetime not null,
spec_content varchar(500) not null,
clubadmin_id int not null,
primary key (spec_id),
constraint fk_special_clubadmin_id foreign key (clubadmin_id) references clubadmin(clubadmin_id)
);
...
With emphasis on the relationship between special and clubadmin.
In my Play! project I have a ClubAdmin and a Special class that have the following:
package models;
...
@Entity
@Table(name="special")
public class Special extends GenericModel
{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Required
public Long spec_id;
...
@ManyToOne
@Required
public Clubadmin clubadmin;
public Special(Clubadmin admin,...)
{
...
this.clubadmin = admin;
...
}
}
and
package models;
...
@Entity
@Table(name="clubadmin")
public class ClubAdmin extends GenericModel
{
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Required
public Long clubadmin_id;
...
@OneToMany(mappedBy="clubadmin",cascade=CascadeType.ALL)
public List<Special> specials;
public ClubAdmin(...)
{
...
this.specials=new ArrayList<Special>();
...
}
}
From what I can see, it looks like the creation of the @ManyToOne relationship in the Special class is creating a new field inside the Special table with the name of clubadmin_clubadmin_id that represents the foreign key , regardless of the existence the fk_special_clubadmin_id constraint. This should not be happening.
How do I make Play! realise and use the existing constraints in the database so that it does not create its own?
I am using Play! 1.2.4 and MySQL 5.3
Thanks!
Add a JoinColumn annotation to your ManyToOne field to specify a column name different than the one inferred by jpa
Something like