4.Hibernate关联映射注解之多对一单向外键关联

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

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



4.Hibernate关联映射注解之多对一单向外键关联

//多方持有一方的引用,比如:多个学生对应一个班级(多对一的关系)

@ManyToOne(cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
@JoinColumn(name="cid", referencedColumnName="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="mto_fk.Students"/>
        <mapping class="mto_fk.Classroom"/>

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

2.实体类

Students.java:

package mto_fk;

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", referencedColumnName="CID")
    public Classroom getRoom() {
        return room;
    }

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


}

Classroom.java:

package mto_fk;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;

import org.hibernate.annotations.GenericGenerator;


@Entity
public class Classroom {

    @Id
    @GeneratedValue(generator="cid")
    @GenericGenerator(name="cid", strategy="assigned")
    @Column(length=4)
    private String cid; //班级编号
    private String cname; //班级名称

    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;
    }


}

3.测试类

package mto_fk;

import java.util.Date;

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;

import mto_fk.Students;
import mto_fk.Classroom;


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(), room1);
        Students stu2 = new Students("李四", "男", new Date(), room1);
        Students stu3 = new Students("王五", "女", new Date(), room2);
        Students stu4 = new Students("老六", "女", new Date(), room2);

        //先保存班级对象
        session.save(room1);
        session.save(stu1);
        session.save(room1);
        session.save(stu2);
        session.save(room2);
        session.save(stu3);
        session.save(room2);
        session.save(stu4);

        transaction.commit();

    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值