3

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 Answer 1

2

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;
}
Sign up to request clarification or add additional context in comments.

3 Comments

But I need just a countryCode not Country object.
@user3279337 This is how you create mapping between entities in hibernate. You can get countryCode from the country reference.
@user3279337 BTW, this is just a very basic mapping. There are many more options you can give. You might want to go through hibernate documentation for more information on this.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.