How to join fields of two tables using Hibernate?

廉价感情. 提交于 2020-01-01 16:31:11

问题


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.


回答1:


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!