I have two tables and 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 is my 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 is how can I join Contry.code
to User.countryCode
in Hibernate using annotation? When I create User object with Hibernate I need to bind these two fields (code and countryCode) automatically.
You need @OneToMany
mapping from Country
to User
entity and corresponding @ManyToOne
mapping from User
to 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;
}
来源:https://stackoverflow.com/questions/22334630/how-to-join-fields-of-two-tables-using-hibernate