java - How to join fields of two tables using Hibernate? -
i have 2 tables , related java mapping.
create table country ( code varchar(3) primary key not null, name varchar(100) not null ); create table user ( id int primary key not null auto_increment, name varchar(100) not null, country_code varchar(3), foreign key ( country_code ) references country ( code ) ); here java entities. country pojo:
@entity @table(name = "country") public class country { @id @column (name = "code") private string code; @column (name = "name") private string name; and user pojo:
@entity @table(name = "user") public class user implements serializable { @id @generatedvalue(strategy = generationtype.auto) private integer id; @column(name = "name") private string name; @column(name = "country_code") private string countrycode; question how can join contry.code user.countrycode in hibernate using annotation? when create user object hibernate need bind these 2 fields (code , countrycode) automatically.
you need @onetomany mapping country user entity , corresponding @manytoone mapping user country:
@entity @table(name = "country") public class country { @id @column (name = "code") private string code; @column (name = "name") private string name; @onetomany(mappedby = "country") private set<user> users; } @entity @table(name = "user") public class user implements serializable { @id @generatedvalue(strategy = generationtype.auto) private integer id; @column(name = "name") private string name; @manytoone @joincolumn(name = "country_code") private country country; }
Comments
Post a Comment