码迷,mamicode.com
首页 > Web开发 > 详细

Hibernate对象映射关系:多对一

时间:2015-08-20 16:58:39      阅读:219      评论:0      收藏:0      [点我收藏+]

标签:hibernate

一:项目截图

技术分享


二:业务代码

package com.cloud.domain;
import java.util.Set;
public class Department implements java.io.Serializable{
/**
* 实现java.io.Serializable 接口的类是可序列化的。
* 没有实现此接口的类将不能使它们的任一状态被序列化或逆序列化。
*/
private static final long seriaVersionUID = 1L;
private Integer id;
private String name;
//设置一个集合,对应多个学生:one-to-many
private Set<Student> stu;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<Student> getStu() {
return stu;
}
public void setStu(Set<Student> stu) {
this.stu = stu;
}
public static long getSeriaversionuid() {
return seriaVersionUID;
}

}


package com.cloud.domain;
public class Student implements java.io.Serializable{
/**
* 实现java.io.Serializable 接口的类是可序列化的。
* 没有实现此接口的类将不能使它们的任一状态被序列化或逆序列化。
*/
private static final long seriaVersionUID = 1L;
private Integer id;
private String name;
private Department dept;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Department getDept() {
return dept;
}
public void setDept(Department dept) {
this.dept = dept;
}
public static long getSeriaversionuid() {
return seriaVersionUID;
}
}


三:项目配置代码

Department.hbm.xml

<?xml version="1.0"encoding="utf-8"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/HibernateMapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.cloud.domain">

<class name="Department">

<!--配置主键属性 -->

<id name="id"type="java.lang.Integer">

<!-- 配置生成策略 -->

<generator class="increment"/>

</id>

<property name="name"type="java.lang.String">

   <column name="name" length="64"not-null="true"/>

</property>

<!-- 配置one-to-many关系 -->

<set name="stu"cascade="save-update">

<!-- 指定Student类对应的外键 -->

<key column="dept_id"/>

<one-to-many class="Student"/>

</set>

</class>

</hibernate-mapping>

 

Student.hbm.xml

 

<?xml version="1.0"encoding="utf-8"?>

<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/HibernateMapping DTD 3.0//EN"

"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping package="com.cloud.domain">

<class name="Student">

<id name="id"type="java.lang.Integer">

   <generator class="increment"/>

</id>

<!-- property是指业务逻辑代码里面的属性 -->

<property name="name" type="java.lang.String">

<!-- column是指在数据库表中生成的列名 -->

   <column name="name" length="64"/>

</property>

<!-- private Department dept;对于Student中该属性不能使用property配置 -->

<!-- 因为多个学生对应一个部门,所以这里使用 many-to-one配置 -->

<many-to-one name="dept"column="dept_id"/>

</class>

</hibernate-mapping>

 

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">

 

<!-- Generated by MyEclipse HibernateTools.                   -->

<hibernate-configuration>

 

<session-factory>

   <property name="dialect">

      org.hibernate.dialect.MySQLDialect

   </property>

   <property name="connection.url">

      jdbc:mysql://localhost:3306/zjgm01

   </property>

   <property name="connection.username">root</property>

   <property name="connection.password">root</property>

   <property name="connection.driver_class">

      com.mysql.jdbc.Driver

   </property>

   <property name="show_sql">true</property>

   <!-- 配置hibernate自动创建关系模型表 -->

   <property name="hbm2ddl.auto">update</property>

   <mapping resource="com/cloud/domain/Department.hbm.xml"/>

   <mapping resource="com/cloud/domain/Student.hbm.xml" />

 

</session-factory>

 

</hibernate-configuration>

四:测试代码

package com.cloud.view;
import java.util.HashSet;
import java.util.Set;
import org.hibernate.Hibernate;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.cloud.domain.Department;
import com.cloud.domain.Student;
import com.cloud.util.HibernateUtil;
public class TestMain {


/**
* @param args
*/
public static void main(String[] args) {
Session s=null;
Transaction tx=null;
try {
s=HibernateUtil.getCurrentSession();
tx=s.beginTransaction();
//取出1号部门的所有学生,方法一
//String hql="from Student where dept.id=1";
//方法二one-to-many关系
/*
Department department1=(Department) s.get(Department.class, 1);
//取出该部门的学生
Set<Student> stus=department1.getStu();
for(Student ss:stus){
System.out.println(ss.getName());
}
*/
//添加学生
Department department=new Department();
department.setName("业务部门");
Student stu1=new Student();
stu1.setName("大明");
Student stu2=new Student();
stu2.setName("小明");
Set sets=new HashSet<Student>();
sets.add(stu1);
sets.add(stu2);
department.setStu(sets);
s.save(department);
tx.commit();
} catch (Exception e) {
if(tx!=null){
tx.rollback();
}
}finally{
if(s!=null && s.isOpen()){
s.close();
}
}

}


public static Student getStudent() {
Session s=null;
Transaction tx=null;
Student student1=null;
try {
s=HibernateUtil.getCurrentSession();
tx=s.beginTransaction();
student1=(Student) s.get(Student.class, 3);
//System.out.println(student1.getName()+"所在部门:"+student1.getDept().getName());
//显示初始化代理对象
Hibernate.initialize(student1.getDept());
tx.commit();
} catch (Exception e) {
if(tx!=null){
tx.rollback();
}
}finally{
if(s!=null && s.isOpen()){
s.close();
}
}
return student1;
}


public static void add() {
//HibernateUtil.getCurrentSession();
Session s=null;
Transaction tx=null;
try {
s=HibernateUtil.getCurrentSession();
tx=s.beginTransaction();
//添加一个学生和部门,并且把学生关联到部门当中
Student stu=new Student();
stu.setName("张三");
Student stu2=new Student();
stu2.setName("李四");
Department d=new Department();
d.setName("财务部");
Department d2=new Department();
d2.setName("人事部");
//把学生分配到部门当中去
stu.setDept(d);
//这里必须注意保存时必须先保存部门再保存学生
s.save(d);
s.save(stu);
stu2.setDept(d2);
s.save(d2);
s.save(stu2);
tx.commit();
} catch (Exception e) {
if(tx!=null){
tx.rollback();
}
}finally{
if(s!=null && s.isOpen()){
s.close();
}
}
}
}


五:测试结果

Hibernate: select max(id) from Department
Hibernate: select max(id) from Student
Hibernate: insert into Department (name, id) values (?, ?)
Hibernate: insert into Student (name, dept_id, id) values (?, ?, ?)
Hibernate: insert into Student (name, dept_id, id) values (?, ?, ?)
Hibernate: update Student set dept_id=? where id=?
Hibernate: update Student set dept_id=? where id=?

版权声明:博主原创文章,转载请说明出处。http://blog.csdn.net/dzy21

Hibernate对象映射关系:多对一

标签:hibernate

原文地址:http://blog.csdn.net/dzy21/article/details/47808439

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!