Hibernate(七)一对一映射

一、创建数据库表

--班级表
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
);

--学生证表
create table paper
(
       pid   number primary key,
       pdesc varchar2(100)  ,
       sid   number references student(sid) not null
       
);

二、创建配置文件和持久化类

学生类

技术分享
package entity;

/*
 * 学生类
 */
public class Student implements java.io.Serializable {

    // Fields

    private static final long serialVersionUID = 1L;
    private int sid;
    private String sname;
    private String sex;
    //增加班级属性
    private Grade grade;
    //学生证类
    private Paper paper;

    // Constructors

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

    /** minimal constructor */
    public Student(int sid) {
        this.sid = sid;
    }

    /** full constructor */
    public Student(int sid, String sname, String sex ) {
    
        this.sid = sid;

        this.sname = sname;
        this.sex = sex;
    }

    // Property accessors

    public int getSid() {
        return this.sid;
    }

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

    

    public String getSname() {
        return this.sname;
    }

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

    public String getSex() {
        return this.sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Grade getGrade() {
        return grade;
    }

    public void setGrade(Grade grade) {
        this.grade = grade;
    }

    public Paper getPaper() {
        return paper;
    }

    public void setPaper(Paper paper) {
        this.paper = paper;
    }
    

}
View Code

学生证类

技术分享
package entity;

/*
 * 学生证类
 */

public class Paper implements java.io.Serializable {

    // Fields

    private static final long serialVersionUID = 1L;
    private int pid;
    private Student student;
    private String pdesc;

    // Constructors

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

    /** minimal constructor */
    public Paper(int pid) {
        this.pid = pid;
    }

    /** full constructor */
    public Paper(int pid, Student student, String pdesc) {
        this.pid = pid;
        this.student = student;
        this.pdesc = pdesc;
    }

    // Property accessors

    public int getPid() {
        return this.pid;
    }

    public void setPid(int pid) {
        this.pid = pid;
    }

    public Student getStudent() {
        return this.student;
    }

    public void setStudent(Student student) {
        this.student = student;
    }

    public String getPdesc() {
        return this.pdesc;
    }

    public void setPdesc(String pdesc) {
        this.pdesc = pdesc;
    }

}
View Code

 

hibernate.cfg.xml配置文件

<?xml version=‘1.0‘ encoding=‘UTF-8‘?>
<!DOCTYPE hibernate-configuration PUBLIC
          "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
          "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <session-factory>
        <property name="dialect">
            org.hibernate.dialect.Oracle9Dialect
        </property>
        <property name="connection.url">
            jdbc:oracle:thin:@localhost:1521:orcl
        </property>
        <property name="connection.username">root</property>
        <property name="connection.password">root</property>
        <property name="connection.driver_class">
            oracle.jdbc.OracleDriver
        </property>
        <property name="show_sql">true</property>
        <property name="format_sql">true</property>

        <mapping resource="entity/Grade.hbm.xml" />
        <mapping resource="entity/Student.hbm.xml" />
        <mapping resource="entity/Paper.hbm.xml" />

    </session-factory>

</hibernate-configuration>

 

学生类配置文件

技术分享
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="entity.Student" table="STUDENT" schema="ROOT">
        <id name="sid" type="java.lang.Integer">
            <column name="SID" precision="22" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="sname" type="java.lang.String">
            <column name="SNAME" length="20" />
        </property>
        <property name="sex" type="java.lang.String">
            <column name="SEX" length="20" />
        </property>
        <!--配置grade属性  -->
        <many-to-one name="grade" class="entity.Grade" cascade="save-update">
        <!--指定学生表中的外键  -->
        <column name="GID" />
        </many-to-one>
        <!-- 添加学生证的配置 -->
        <one-to-one name="paper" class="entity.Paper" cascade="all" lazy="false"/>
    </class>
</hibernate-mapping>
View Code

学生证类配置文件 

技术分享
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse Persistence Tools
-->
<hibernate-mapping>
    <class name="entity.Paper" table="PAPER" schema="ROOT">
        <id name="pid" type="java.lang.Integer">
            <column name="PID" precision="22" scale="0" />
            <generator class="assigned" />
        </id>
        
        <property name="pdesc" type="java.lang.String">
            <column name="PDESC" length="100" />
        </property>
        <!-- 学生信息 unique唯一的-->
        <many-to-one name="student" class="entity.Student" unique="true" lazy="false">
            <column name="SID" precision="22" scale="0" />
        </many-to-one>
    </class>
</hibernate-mapping>
View Code

测试类

技术分享
package Test;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import entity.Paper;
import entity.Student;

public class Demo6 {

    public static void main(String[] args) {
        save();
        find();
    }

    public static void save() {
        
        Student stu1 = new Student();
        stu1.setSid(20151109);
        stu1.setSname("钱七");
        stu1.setSex("女");
    
        Paper paper=new Paper();
        paper.setPid(9001);
        paper.setPdesc("钱七的学生证");
        paper.setStudent(stu1);
        
        
        stu1.setPaper(paper);
        
        // 建立session
                Session session = new Configuration().configure().buildSessionFactory()
                        .openSession();
                // 开始事务
                Transaction transaction = session.beginTransaction();
            
            
                // 保存学生证
                session.save(stu1);
                // 提交事务
                transaction.commit();
                // 关闭session
                session.close();

    }

    public static void find() {
        // 建立session
        Session session = new Configuration().configure().buildSessionFactory()
                .openSession();
        Paper paper=(Paper) session.get(Paper.class, 9001);
        System.out.println(paper.getPid()+paper.getPdesc());
        Student stu1=paper.getStudent();
        System.out.println(stu1.getSid()+"\t"+stu1.getSname());
    }

}
View Code

 发现可以 通过学生证,找到学生

但反过来,如果通过学生,找到学生证呢,显示是不能的,因为学生类中配置文件没有实现关联

修改学生类的配置文件  property-ref="student"用来指定Paper类中的属性

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="entity.Student" table="STUDENT" schema="ROOT">
        <id name="sid" type="java.lang.Integer">
            <column name="SID" precision="22" scale="0" />
            <generator class="assigned" />
        </id>
        <property name="sname" type="java.lang.String">
            <column name="SNAME" length="20" />
        </property>
        <property name="sex" type="java.lang.String">
            <column name="SEX" length="20" />
        </property>
        <!--配置grade属性  -->
        <many-to-one name="grade" class="entity.Grade" cascade="save-update">
        <!--指定学生表中的外键  -->
        <column name="GID" />
        </many-to-one>
        <!-- 添加学生证的配置 -->
        <one-to-one name="paper" class="entity.Paper" cascade="all" lazy="false" property-ref="student"/>
    </class>
</hibernate-mapping>

测试类

技术分享
package Test;

import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;

import entity.Paper;
import entity.Student;

public class Demo6 {

    public static void main(String[] args) {
        findByStu();
    }

    public static void save() {
        
        Student stu1 = new Student();
        stu1.setSid(20151109);
        stu1.setSname("钱七");
        stu1.setSex("女");
    
        Paper paper=new Paper();
        paper.setPid(9001);
        paper.setPdesc("钱七的学生证");
        paper.setStudent(stu1);
        
        
        stu1.setPaper(paper);
        
        // 建立session
                Session session = new Configuration().configure().buildSessionFactory()
                        .openSession();
                // 开始事务
                Transaction transaction = session.beginTransaction();
            
            
                // 保存学生证
                session.save(stu1);
                // 提交事务
                transaction.commit();
                // 关闭session
                session.close();

    }

    public static void find() {
        // 建立session
        Session session = new Configuration().configure().buildSessionFactory()
                .openSession();
        Paper paper=(Paper) session.get(Paper.class, 9001);
        System.out.println(paper.getPid()+paper.getPdesc());
        Student stu1=paper.getStudent();
        System.out.println(stu1.getSid()+"\t"+stu1.getSname());
    }
    public static void findByStu() {
        // 建立session
        Session session = new Configuration().configure().buildSessionFactory()
                .openSession();
        Student stu=(Student) session.get(Student.class, 20151109);
        System.out.println(stu.getSname());
        Paper paper=stu.getPaper();
        System.out.println(paper.getPid()+"\t"+paper.getPdesc());
    }

}
View Code

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。