hibernate关联映射(注解) —— 一对多关联关系(@OneToMany)

hibernate基于注解的一对多关联使用@OneToMany注解。
注意:需要引入的为: javax.persistence.OneToMany

@OneToMany(fetch = FetchType.EAGER)
@Cascade(CascadeType.SAVE_UPDATE)//设置级联操作
@JoinColumn(name = "groupId") //指定多端的外键
@OrderBy(value = "userId ASC") //加载时按 userId的升序排序  

假设有两个类:User(用户)与Group(组),一个组有多个用户。

首先,对于hibernate配置文件 hibernate.cfg.xml 要做如下改动:


<mapping resource="demo/entity/User.hbm.xml"/>
<mapping resource="demo/entity/Group.hbm.xml"/>

改为:


<mapping class="demo.entity.User" />
<mapping class="demo.entity.Group" />

Group 类如下:

package demo.entity;

import java.util.Set;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.OrderBy;
import javax.persistence.Table;

import org.hibernate.annotations.Cascade;
import org.hibernate.annotations.CascadeType;

@Entity //设置为Entity 实体
@Table(name = "u_group") //设置数据库表名
public class Group {
    private int groupId;
    private String groupName;
    private Set users;

    @Id //设置主键
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    @Column(name = "groupId", nullable = false)
    public int getGroupId() {
        return groupId;
    }
    public void setGroupId(int groupId) {
        this.groupId = groupId;
    }

    @Basic
    @Column(name = "groupName", nullable = false)
    public String getGroupName() {
        return groupName;
    }
    public void setGroupName(String groupName) {
        this.groupName = groupName;
    }

    //一对多关联映射
    @OneToMany(fetch = FetchType.EAGER)
    @Cascade(CascadeType.SAVE_UPDATE)//设置级联操作
    @JoinColumn(name = "groupId") //指定多端的外键
    @OrderBy(value = "userId ASC") //加载时按 userId的升序排序  
    public Set getUsers() {
        return users;
    }
    public void setUsers(Set users) {
        this.users = users;
    }

}

User类如下:

package demo.entity;

import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity 
@Table(name = "user")
public class User {
    private int userId;
    private String username;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "userId", nullable = false)
    public int getUserId() {
        return userId;
    }

    public void setUserId(int userId) {
        this.userId = userId;
    }

    @Basic
    @Column(name = "username", nullable = false)
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

}

hibernate自动建表操作结果 :
hibernate关联映射(注解) —— 一对多关联关系(@OneToMany)_第1张图片

你可能感兴趣的:(hibernate)