注意事项:一对多,多对一双向关联,在一的一方的多的getSet集合上的oneToMany上加上mappedBy。告诉hibernate由多的方一来维护关系。这也符合逻辑

,本来外键就是在加在多的一方。

User类:

package com.oracle.hibernate;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

@Entity
public class User {

    private int id;
    private String name;
    private Group  group;
    
    @ManyToOne
    public Group getGroup() {
        return group;
    }
    public void setGroup(Group group) {
        this.group = group;
    }
    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
}

Group类:

package com.oracle.hibernate;

import java.util.HashSet;
import java.util.Set;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;

@Entity
@Table(name="t_group")//group是mysql的关键字,换个名
public class Group {

    private int id;
    private String name;
    //用set集合,不重复。因为表里的记录也不会重复
    private Set<User>  users = new HashSet<User>();
    
    //铁律:双向关系,必设mappedBy,
    //在oneTomany一方设mappedBy,告诉hibernate,在多的一方来维护关系,在Group类里就不用管我了,
    @OneToMany(mappedBy="group")
    public Set<User> getUsers() {
        return users;
    }
    public void setUsers(Set<User> users) {
        this.users = users;
    }
    @Id
    @GeneratedValue
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    
}

生成的表:

hibernate建表语句:

create table t_group (
id integer not null auto_increment,
name varchar(255),
primary key (id)
)

create table User (
id integer not null auto_increment,
name varchar(255),
group_id integer,
primary key (id)
)

alter table User
add index FK285FEB80FC033B (group_id),
add constraint FK285FEB80FC033B
foreign key (group_id)
references t_group (id)

 

 欢迎关注个人公众号一起交流学习: