简体   繁体   中英

Hibernate: rename autogenerated Id in a @ManyToOne relationship

I have a MySQL database with two tables, contacts and addresses . The table addresses contains a column contactid of type big integer to connect with the contact table.

I have the following entities in Hibernate with a bidirectional OneToMany - ManyToOne relationship. The problem is that the @ManyToOne relationship creates another contact_id column of type integer in my datatabase. I would like to use the already existing contactid column and not have contact_id so I was thinking I should rename the autogenerated contact_id column to contactid but I don't know if this is possible...

Is there any way to solve this without modifying the database?

Thanks in advance.

@Entity
@Table(name="contacts")
public class Contact implements Serializable {

    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private Integer id;

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

    @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.EAGER, mappedBy="contact")
    private List<Address> addresses= new ArrayList<Address>();

    // getters and setters
}


@Entity
@Table(name="addresses")
public class Address implements Serializable {

    @Id
    @Column(name="id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private long id;

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

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

    @ManyToOne
    private Contact contact;

    // getters and setters
}

You need to have @JoinColumn(name = "id") along with your @ManyToOne in Address .

By adding the mappedBy to addresses you are letting the child to own the relation ship. When you mention the JoinColumn you are telling that what is the columns that hold the actual relationship in DB.

Also, you were talking about contact_id but I couldn't see that in your mapping.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM