多对一单向和一对多单向,在数据库的表现都是在多的一方加上一的外键

在类里的表现,一对多单向,是在一的一方加上多的引用,多对一单向,是在一的一方加上多的set集合。

User和Group,一个Group有多个User

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;
    
    @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>();
    
    //一对多
    @OneToMany
    // 指定外键名字,若不指定,hibernate会把一对多当成多对多的一种情况,生成一张临时中间表分别指向user和group     
    @JoinColumn(name="groupId")
    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 User (
id integer not null auto_increment,
name varchar(255),
groupId integer,
primary key (id)
)

 

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

alter table User
add index FK285FEB744AEC3A (groupId),
add constraint FK285FEB744AEC3A
foreign key (groupId)
references t_group (id)

 

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