小编典典

如何使用Hibernate联接两个表的字段?

hibernate

我有两个表和相关的Java映射。

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 )
);

这是我的Java实体。国家POJO:

@Entity
@Table(name = "country")
public class Country {

    @Id
    @Column (name = "code")
    private String code;

    @Column (name = "name")
    private String name;

和用户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;

问题是,我怎么能加入Contry.codeUser.countryCode在Hibernate中使用注释?当我使用Hibernate创建User对象时,我需要自动绑定这两个字段(代码和countryCode)。


阅读 330

收藏
2020-06-20

共1个答案

小编典典

您需要@OneToMany从映射CountryUser实体,并@ManyToOne从映射UserCountry

@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;
}
2020-06-20