java——Hibernate(2)

Hibernate

结合实例分析hibernate一对多以及多对一的对象映射

hibernate工具类:

hibernateUtil.java:

package hibernate;

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

public class hibernateUtil {
    private static SessionFactory sessionFactory;
    private static Session session;
    static {
        Configuration config = new Configuration().configure();
        sessionFactory = config.buildSessionFactory();
        
    }
    public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }
    public static Session getSession() {
        session = sessionFactory.openSession();
        return session;
    }
    public static void closeSession(Session session) {
        if (session != null) {
        session.close();
    }
    }
}

两个实体类:

Grade.java(班级):

package hibernate;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;

public class Grade implements Serializable {
    private int gid;
    private String gname;
    private String gdesc;
    private Set<Student> students = new HashSet<Student>();
    public int getGid() {
        return gid;
    }
    public void setGid(int gid) {
        this.gid = gid;
    }
    public String getGname() {
        return gname;
    }
    public void setGname(String gname) {
        this.gname = gname;
    }
    public String getGdesc() {
        return gdesc;
    }
    public void setGdesc(String gdesc) {
        this.gdesc = gdesc;
    }
    public Set<Student> getStudents() {
        return students;
    }
    public void setStudents(Set<Student> students) {
        this.students = students;
    }
    @Override
    public String toString() {
        return "Grade [gid=" + gid + ", gname=" + gname + ", gdesc=" + gdesc + ", students=" + students + "]";
    }
    public Grade(int gid, String gname, String gdesc, Set<Student> students) {
        super();
        this.gid = gid;
        this.gname = gname;
        this.gdesc = gdesc;
        this.students = students;
    }
    public Grade() {
        super();
    }
    public Grade(String gname, String gdesc) {
        super();
        this.gname = gname;
        this.gdesc = gdesc;
    }
    
}

Student.java(学生):

package hibernate;

import java.io.Serializable;

public class Student implements Serializable {
    private int sid;
    private String sname;
    private String sex;
    private Grade grade;
    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 Grade getGrade() {
        return grade;
    }
    public void setGrade(Grade grade) {
        this.grade = grade;
    }
    public String getSex() {
        return sex;
    }
    public void setSex(String sex) {
        this.sex = sex;
    }
    public Student(String sname, String sex) {
        super();
        this.sname = sname;
        this.sex = sex;
    }
    public Student() {
        super();
    }
    
}

主配置文件:

<?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">
<!-- Generated by MyEclipse Hibernate Tools.                   -->
<hibernate-configuration>

	<session-factory>
		<property name="myeclipse.connection.profile">lzjtest</property>
		<property name="connection.url">
			jdbc:mysql:///hibernate
		</property>
		<property name="connection.username">root</property>
		<property name="connection.password">123456</property>
		<property name="connection.driver_class">
			com.mysql.jdbc.Driver
		</property>
		<property name="dialect">
			org.hibernate.dialect.MySQL5Dialect
		</property>
		<mapping resource="hibernate/Grade.hbm.xml" />
		<mapping resource="hibernate/Student.hbm.xml" />


	</session-factory>

</hibernate-configuration>

 班级对象映射配置文件:

<?xml version="1.0"?>
<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Nov 9, 2006 6:27:53 PM by Hibernate Tools 3.2.0.beta7 -->
<hibernate-mapping>
      <class name="hibernate.Grade" table="grade">
           <id name="gid" column="gid" type="java.lang.Integer">
               <generator class="increment"></generator>
           </id>
           <property name="gname" type="java.lang.String">
               <column name="gname" length="20" not-null="true"></column>
           </property>
           <property name="gdesc">
               <column name="gdesc"></column>
           </property>
           <set name="students" table="student" inverse="true" cascade="save-update">
               <key column="gid"></key>
               <one-to-many class="hibernate.Student"/>
           </set>
       </class>
</hibernate-mapping>

学生对象映射配置文件:

<?xml version="1.0"?>
<!--
  ~ Hibernate, Relational Persistence for Idiomatic Java
  ~
  ~ License: GNU Lesser General Public License (LGPL), version 2.1 or later.
  ~ See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
  -->
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Nov 9, 2006 6:27:53 PM by Hibernate Tools 3.2.0.beta7 -->
<hibernate-mapping>
       <class name="hibernate.Student" table="student">
           <id name="sid" column="sid" type="java.lang.Integer">
               <generator class="increment"></generator>
           </id>
           <property name="sname" type="java.lang.String">
               <column name="sname" length="20" not-null="true"></column>
           </property>
           <property name="sex">
               <column name="sex"></column>
           </property>
           <many-to-one name="grade" class="hibernate.Grade" column="gid" ></many-to-one>
       </class>
</hibernate-mapping>

 测试类1:

package hibernate;

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

import org.hibernate.Session;
import org.hibernate.Transaction;

public class Test {
    public static void main(String[] args) {
        //findStudentsByGrade();
        //update();
        add();
        //delete();
    }
    public static void add() {
        Grade g = new Grade("java1班","试验测试班级1");
        Student s1 = new Student("张三","男");
        Student s2 = new Student("李四","女");
        Set<Student> ss = new HashSet<Student>();
        ss.add(s1);
        ss.add(s2);
        g.setStudents(ss);
        Session session = hibernateUtil.getSession();
        Transaction tx = session.beginTransaction();
        session.save(g);
        session.save(s1);
        session.save(s2);
        tx.commit();
        hibernateUtil.closeSession(session);
    }
    public static void findStudentsByGrade() {
        Session session = hibernateUtil.getSession();
        Grade grade = session.get(Grade.class, 1);
        System.out.println(grade.getGname()+"':'"+grade.getGdesc());
        Set<Student> students = grade.getStudents();
        for(Student stu:students) {
            System.out.println("姓名:"+stu.getSname()+"性别:"+stu.getSex());
        }
        hibernateUtil.closeSession(session);
    }
    public static void update() {
        Grade g = new Grade("java二班","java复习班");
        Session session = hibernateUtil.getSession();
        Student stu = (Student)session.get(Student.class, 1);
        g.getStudents().add(stu);
        session.save(g);
        Transaction tx = session.beginTransaction();
        tx.commit();
        hibernateUtil.closeSession(session);
    }
    public static void delete() {
        Session session = hibernateUtil.getSession();
        Transaction tx = session.beginTransaction();
        Student stu = (Student)session.get(Student.class, 1);
        session.delete(stu);
        tx.commit();
        hibernateUtil.closeSession(session);
    }
}

测试类2:

package hibernate;

import org.hibernate.Session;
import org.hibernate.Transaction;

public class test2 {
    public static void main(String[] args) {
        //save();
        findGradeByStudent();
    }
    public static void save() {
        Grade g = new Grade("python一班","python试验班");
        Student stu1 = new Student("愚得标","男");
        Student stu2 = new Student("小波","女");
        g.getStudents().add(stu2);
        g.getStudents().add(stu1);
        stu1.setGrade(g);
        stu2.setGrade(g);
        Session session = hibernateUtil.getSession();
        Transaction tx = session.beginTransaction();
        session.save(g);
        session.save(stu1);
        session.save(stu2);
        tx.commit();
        hibernateUtil.closeSession(session);
    }
    public static void findGradeByStudent() {
        Session session = hibernateUtil.getSession();
        Student s = (Student)session.get(Student.class, 3);
        System.out.println("该学生所处的班级是"+s.getGrade().getGname());
    }
}

 

一对多的映射:

 

文件Grade.hbm.xml中set元素的常用属性:

 

 

 

 

如果在“一方”映射文件进行一对多的配置,且在“多方”映射文件进行多对一的配置,这样会导致sql语句会进行两次维护,

如:

 

 其中红绿色标的语句其实已经重复实现了“多对一”以及“一对多”的重复定义了;

此时set元素中的inverse属性就可以指明只进行一方维护即可:

 

 

 如上图,其实在进行绿色箭头操作的时候,保存了班级这个表的保存,可以学生这个表是还需红色箭头来保存的,可是前面两个绿色箭头其实已经将学生的信息保存到班级的这个对象里去了,怎么才能让记录在班级对象里的学生对象信息自动地保存到学生表中呢?进行一个级联操作呢?这个时候就需要在set元素中进行cascade属性的设置

 

 

 

 总结:

 

 

 

通过myeclipes可直接加载hibernate框架插件,也可以通过数据库表直接生成对应的实体类和对应的映射配置文件(hbm.xml)。

 

posted @ 2020-03-11 17:35  xiao兆  阅读(149)  评论(0编辑  收藏  举报