一、Hinbernate中持久化类的关联关系

在数据库中,表表之间是通过外键关联的,在程序中是要转化为持久化类也就是(JAVA Bean)来实例的。

但在Hibernater中持久化的之间的映射关系,不是通外键建立关联,而是通过属性.主要有以下几种

  • 一对一,
  • 一对多(多对一)
  • 多对多

关联方向:

  • 单向关联
  • 双向关联

二、一对多单向关联关系

2.1、建立数据库表

班级表,和学生表,学生生通过班级表中的,班级编号为外键

--班级表
create table grade
(
       gid       number           primary key,  --班级ID
       gname     varchar2(50),                  --班级名称
       gdesc     varchar2(50)                   --班级介绍
);
--学生表
create table student
(
       sid       number           primary key,  --主键ID学生ID
       sname     varchar2(20),            --学生姓名
       sex       varchar2(20),            --学生性别
       gid       number           references grade(gid) ---外键班级ID
);

2.2、建立持久化类和映射配置文件

班级和学生类

package entity;


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


/*
 * 班级类
 */
public class Grade implements java.io.Serializable {

    // Fields
    private static final long serialVersionUID = 1L;
    private int gid;
    private String gname;
    private String gdesc;
    private Set<Student> students = new HashSet<Student> ();

    // Constructors

    /** default constructor */
    public Grade() {
    }

    /** minimal constructor */
    public Grade(int gid) {
        this.gid = gid;
    }

    /** full constructor */
    public Grade(int gid, String gname, String gdesc, Set<Student> students) {
        this.gid = gid;
        this.gname = gname;
        this.gdesc = gdesc;
        this.students = students;
    }

    // Property accessors

    public int getGid() {
        return this.gid;
    }

    public void setGid(int gid) {
        this.gid = gid;
    }

    public String getGname() {
        return this.gname;
    }

    public void setGname(String gname) {
        this.gname = gname;
    }

    public String getGdesc() {
        return this.gdesc;
    }

    public void setGdesc(String gdesc) {
        this.gdesc = gdesc;
    }

    public Set<Student> getStudents() {
        return this.students;
    }

    public void setStudents(Set<Student> students) {
        this.students = students;
    }

}
View Code

相关文章:

  • 2017-12-14
  • 2021-11-07
  • 2021-06-17
  • 2022-12-23
  • 2021-06-17
  • 2021-06-17
  • 2022-12-23
  • 2021-08-01
猜你喜欢
  • 2021-12-20
  • 2021-04-01
  • 2021-10-23
  • 2021-05-24
  • 2021-07-10
  • 2022-12-23
  • 2021-08-09
相关资源
相似解决方案