6.Hibernate关联映射注解之一对多双向外键关联

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

实体之间的映射关系:
        一对一:一个公民对应一个身份证号码。
        一对多(多对一):一个公民有多个银行账号。
        多对多:一个学生有多个老师,一个老师有多个学生。



6.Hibernate关联映射注解之一对多双向外键关联

//多方:多方持有一方的引用
@ManyToOne(cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
@JoinColumn(name="cid")
//一方:一方持有多方的集合
@OneToMany(cascade={CascadeType.ALL}, fetch=FetchType.LAZY)
@JoinColumn(name="cid")

1.配置文件

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="connection.username">root</property> <!-- 用户名 -->
        <property name="connection.password">123456</property>  <!-- 密码 -->
        <property name="connection.driver_class">com.mysql.jdbc.Driver</property> <!-- 驱动类名 -->
        <property name="connection.url">jdbc:mysql:///hibernate?userUnicode=true&amp;charaterEncoding=UTF-8</property><!-- 数据库url -->
        <property name="dialect">org.hibernate.dialect.MySQLDialect</property> <!-- 方言 -->

        <property name="show_sql">true</property> <!-- 在控制台显示SQL语句 -->
        <property name="format_sql">true</property> <!-- 格式化SQL语句 -->
        <property name="hibernate.default_schema">hibernate</property>  <!-- 默认的数据库 -->
        <property name="hbm2ddl.auto">update</property> <!-- 删除原表创建新表 -->

        <property name="current_session_context_class">thread</property> <!-- 本地事务 -->

        <!-- 注册Students,Classroom类 -->
        <mapping class="otm_bfk.Students"/>
        <mapping class="otm_bfk.Classroom"/>

    </session-factory>
</hibernate-configuration>

2.实体类

Students.java:

package otm_bfk;

import java.util.Date;

import javax.persistence.CascadeType;
import javax.persistence.Entity; //JPA注解
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;

//学生类
@Entity
public class Students{

    private int sid; // 学号
    private String sname; // 姓名
    private String gender; // 性别
    private Date birthday; // 出生日期
    private Classroom room; //多方持有一方的引用

    public Students() {

    };

    public Students(String sname, String gender, Date birthday, Classroom room) {
        this.sname = sname;
        this.gender = gender;
        this.birthday = birthday;
        this.room = room;
    }

    @Id
    @GeneratedValue
    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }


    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    public String getGender() {
        return gender;
    }

    public void setGender(String gender) {
        this.gender = gender;
    }

    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }

    @ManyToOne(cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
    @JoinColumn(name="cid")
    public Classroom getRoom() {
        return room;
    }

    public void setRoom(Classroom room) {
        this.room = room;
    }


}

Classroom.java:

package otm_bfk;

import java.util.Set;

import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;

import org.hibernate.annotations.GenericGenerator;


//班级类

@Entity
public class Classroom {

    @Id
    @GeneratedValue(generator="cid")
    @GenericGenerator(name="cid", strategy="assigned") //手动配置主键
    @Column(length=10) //在数据库中字段长度为10
    private String cid; //班级编号
    private String cname; //班级名称

    @OneToMany(cascade={CascadeType.ALL}, fetch=FetchType.LAZY)
    @JoinColumn(name="cid")
    private Set<Students> stu; //一方持有多方的集合

    public Classroom() {

    }

    public Classroom(String cid, String cname) {
        this.cid = cid;
        this.cname = cname;
    }

    public String getCid() {
        return cid;
    }
    public void setCid(String cid) {
        this.cid = cid;
    }
    public String getCname() {
        return cname;
    }
    public void setCname(String cname) {
        this.cname = cname;
    }

    public Set<Students> getStu() {
        return stu;
    }

    public void setStu(Set<Students> stu) {
        this.stu = stu;
    }


}

3.测试类

package otm_fk;

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

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.hibernate.tool.hbm2ddl.SchemaExport;
import org.junit.Test;


public class ObjectTest {
    private SessionFactory sessionFactory;
    private Session session;
    private Transaction transaction;

    @Test
    public void testSaveStudentWithImage() throws Exception{
        //创建配置对象
        Configuration config = new Configuration().configure(); //hibernate.cfg.xml
        //创建服务注册对象
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //创建会话工产对象
        sessionFactory = config.buildSessionFactory(serviceRegistry);
        //会话对象
        //session = sessionFactory.openSession();
        //开启事务
        //transaction = session.beginTransaction();

        SchemaExport  export = new SchemaExport(config);
        export.create(true, true);

    }

    @Test
    public void testSaveStudent() throws Exception{
        //创建配置对象
        Configuration config = new Configuration().configure(); //hibernate.cfg.xml
        //创建服务注册对象
        ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
        //创建会话工产对象
        sessionFactory = config.buildSessionFactory(serviceRegistry);
        //会话对象
        session = sessionFactory.getCurrentSession();
        //开启事务
        transaction = session.beginTransaction();

        //创建两个班级对象
        Classroom room1 = new Classroom("C001", "软件工程");
        Classroom room2 = new Classroom("C002", "电子工程");
        //创建四个学生对象
        Students stu1 = new Students("张三", "男", new Date());
        Students stu2 = new Students("王五", "男", new Date());
        Students stu3 = new Students("王颖", "女", new Date());
        Students stu4 = new Students("够呛", "女", new Date());

        //创建两个集合对象
        Set<Students> set1 = new HashSet<Students>();
        set1.add(stu1);
        set1.add(stu2);

        Set<Students> set2 = new HashSet<Students>();
        set2.add(stu3);
        set2.add(stu4);

        room1.setStu(set1);
        room2.setStu(set2);
        //由于是双向外键关联不分先后保存
        session.save(stu1);
        session.save(stu2);
        session.save(stu3);
        session.save(stu4);
        //由于是双向外键关联不分先后保存
        session.save(room1);
        session.save(room2);
        //提交事务
        transaction.commit();

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值