美文网首页
Hibernate注解配置一对一、一对多实例

Hibernate注解配置一对一、一对多实例

作者: li_jun | 来源:发表于2017-07-05 22:34 被阅读0次

使用Hibernate注解开发学生选课系统、其中共有4张表:
1、课程表Course:表明存在哪些课程。
2、学生表Student:记录学生信息。
3、选课表sc:此表为学生选课的记录,维护学生和课程的多对多关系。
4、教师表teacher:记录教师信息,一个老师只教一门课,但一门课程可以由多个老师教授,与课程表为一对多的关系。

开发流程:

  1. 导入Hibernate相关jar包
image.png

2.配置hibernate的核心文件hibernate.cfg.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    
    <hibernate-configuration>
        <session-factory>
            <!-- 配置数据库 -->
            <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
            <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/spring?characterEncoding=utf8</property>
            <property name="hibernate.connection.username">root</property>
            <property name="hibernate.connection.password">1234</property>
            
            <!-- 配置hibernate属性 -->
            <property name="hibernate.connection.pool_size">10</property>
            <property name="hibernate.show_sql">true</property>
            <property name="hibernate.format_sql">true</property>
            <property name="hibernate.hbm2ddl.auto">update</property>
                <!-- 设置数据库方言 注意在数据库是5.0之后org.hibernate.dialect.MySQLDialect会报type=MyISAM的错误
                    需要设置为org.hibernate.dialect.MySQL5InnoDBDialect
                 -->
            <property name="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</property>
            
            <!-- 配置mapping 注解使用的是class 配置文件的方式是使用resource -->
            <mapping class="com.lj.entity.Teacher"/>
            <mapping class="com.lj.entity.Course"/>
            <mapping class="com.lj.entity.Student"/>
        </session-factory>
    
    </hibernate-configuration>

3.编写实体类
Course:

package com.lj.entity;

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

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;

@Entity
public class Course {
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    
    private String name;
    
    @ManyToMany
    @JoinTable(name="sc",
            joinColumns=@JoinColumn(name="cid"),
            inverseJoinColumns=@JoinColumn(name="sid")) 
    private Set<Student> students = new HashSet<>();
    
    //mappedBy表示此表为从表,关系由对方维护相当于inverse="true"
    @OneToMany(cascade=CascadeType.ALL,mappedBy="course")
    private Set<Teacher> teachers = new HashSet<>();
    
    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;
    }
    public Set<Student> getStudents() {
        return students;
    }
    public void setStudents(Set<Student> students) {
        this.students = students;
    }
    public Set<Teacher> getTeachers() {
        return teachers;
    }
    public void setTeachers(Set<Teacher> teachers) {
        this.teachers = teachers;
    }
}

Teacher:

package com.lj.entity;

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


@Entity
public class Teacher {
    
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    
    private String name;
    
    @ManyToOne(cascade=CascadeType.ALL)
    @JoinColumn(name="course_id")
    private Course course;
    
    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;
    }
    public Course getCourse () {
        return course;
    }
    public void setCourse (Course course) {
        this.course = course;
    }
}

Student:

package com.lj.entity;


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

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;

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


@Entity
public class Student {
    
    @Id
    @GeneratedValue(strategy=GenerationType.IDENTITY)
    private int id;
    
    private String name;
    
    @ManyToMany
    //设置级联操作
    @Cascade(CascadeType.SAVE_UPDATE)
    //配置中间表sc,joinColumns为本表在sc的字段,inverseJoinColumns为对方表在sc的字段
    @JoinTable(name="sc",
        joinColumns=@JoinColumn(name="sid"),
        inverseJoinColumns=@JoinColumn(name="cid"))
    private Set<Course> courses = new HashSet<>();
    
    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;
    }
    public Set<Course> getCourses() {
        return courses;
    }
    public void setCourses(Set<Course> courses) {
        this.courses = courses;
    }
}

注意在使用注解的方法开发给entity类添加注解的时候一定注意注解要么全写在属性上要么全写在get方法上一定不要混着写否则会出现以下错误:
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.List, at table...

编写测试类:

public class ManyTableTest {
    private Configuration cfg;
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction tx;
    
    @Before
    public void common(){
        cfg = new Configuration().configure();
        sessionFactory = cfg.buildSessionFactory();
        session = sessionFactory.openSession();
        tx = session.beginTransaction();
    }
    
    @Test
    public void testManyToMany(){
        
        Teacher teacher1 =new Teacher();
        teacher1.setName("张老师");
        
        Teacher teacher2 = new Teacher();
        teacher2.setName("李老师");
        
        Course course1 = new Course();
        course1.setName("语文");
        teacher1.setCourse(course1);
        
        Course course2 = new Course();
        course2.setName("数学");
        
        Student student1 = new Student();
        student1.setName("小明");
        Student student2 = new Student();
        student2.setName("小刚");
        
        //小明选了语文和数学课
        student1.getCourses().add(course1);
        student1.getCourses().add(course2);
        //数学课添加了小刚
        course2.getStudents().add(student2);
        session.save(teacher1);
        session.save(teacher2);
        session.save(course1);
        session.save(course2);
        session.save(student1);
        session.save(student2);
    }
    
    @After
    public void after(){
        tx.commit();
        session.close();
        sessionFactory.close();
    }

}

相关文章

  • Hibernate注解配置一对一、一对多实例

    使用Hibernate注解开发学生选课系统、其中共有4张表:1、课程表Course:表明存在哪些课程。2、学生表S...

  • Hibernate 一对多操作

    一 表与表之间关系回顾 一对多 多对多 一对一 二 hibernate一对多操作1 一对多映射配置以客户联系人为列...

  • Hibernate 一对多配置(注解)

    商品与评论关系的一对多 表结构设计 t_goods: t_comment: 商品(一的一方) 商品的评论(多的一方)

  • hibernate笔记-关联关系

    hibernate 关联关系主要有一对一,一对多,多对多 一对一关联 一对一关联包括: 主键关联 唯一外键关联 主...

  • 拉钩笔记_模块一

    1.注解开发开发实现复杂映射: 一对一查询一对一 一对多查询一对多 代码实现如上,通过@Results、@Resu...

  • springboot mybaties 一对一 一对多

    一、注解版 1、 一对一 实体类 Mapper 2、一对多 实体类 mapper 3、 注解说明 results ...

  • Hibernate映射(一对多)

    Hibernate映射关系其实有很多种,包含一对一,一对多,多对一,多对多。其中,还有包含单向关联,多想关联。但是...

  • JPA 注解学习

    最近学习hibernate注解形式配置POJO类,将注解的解析记下来,以备以后使用。 例1. Hibernate ...

  • Hibernate4 JPA注解详解(上)

    前言 本期我们对Hibernate JPA注解的配置进行说明,这些注解如何使用,如何配置等。 @Table Tab...

  • Hibernate注解(三)关系映射级别注解

    一、关系映射级别注解 1、一对一单向外键关联 2、一对一双向外键关联 3、一对一单向外键联合主键 4、多对一单向外...

网友评论

      本文标题:Hibernate注解配置一对一、一对多实例

      本文链接:https://www.haomeiwen.com/subject/hllchxtx.html