您的位置:首页 > 其它

Hibernate中one-to-many的基本操作

2011-12-25 10:13 295 查看
数据库

drop database if exists stuInfo;

create database if not exists stuInfo;

use stuInfo;

drop table if exists login;

create table if not exists login

(

loginId int auto_increment primary key,

loginName varchar(20) not null,

passwd varchar(20)

);

insert into login(loginName,passwd) values('admin','1234');

insert into login(loginName,passwd) values('user','1234');

drop table if exists classes;

create table if not exists classes

(

classId int auto_increment primary key,

className varchar(20) not null

);

insert into classes(className) values('ETP1');

insert into classes(className) values('ETP2');

insert into classes(className) values('ETP3');

insert into classes(className) values('ETP4');

insert into classes(className) values('ETP5');

drop table if exists student;

create table if not exists student

(

stuId int auto_increment primary key,

stuName varchar(20) not null,

stuSex smallint default 0,

stuAge smallint default 20,

stuBirth date,

stuHobby varchar(30),

stuStatus smallint,

fclassId int,

foreign key(fclassId) references classes(classId)

);

insert into student(stuName,stuSex,stuAge,stuBirth,stuHobby,stuStatus,fclassId) values('stu1',1,20,'1989-09-09 08:08:22','music;sport',1,1);

insert into student(stuName,stuSex,stuAge,stuBirth,stuHobby,stuStatus,fclassId) values('stu2',0,21,'1989-01-01 08:08:23','music;sport',1,1);

insert into student(stuName,stuSex,stuAge,stuBirth,stuHobby,stuStatus,fclassId) values('stu3',1,22,'1989-02-02 08:08:24','music;sport',1,2);

insert into student(stuName,stuSex,stuAge,stuBirth,stuHobby,stuStatus,fclassId) values('stu4',0,23,'1989-03-03 08:08:25','music;sport',1,2);

insert into student(stuName,stuSex,stuAge,stuBirth,stuHobby,stuStatus,fclassId) values('stu5',1,24,'1989-04-04 08:08:26','music;sport',1,3);

insert into student(stuName,stuSex,stuAge,stuBirth,stuHobby,stuStatus,fclassId) values('stu6',1,25,'1989-05-05 08:08:27','music;sport',1,5);

select stuId,stuSex,stuName,stuAge,stuBirth,stuHobby,stuStatus,fclassId FROM student;

select classId,className from classes;

select loginName,passwd from login;



Pojo

package com.xy.pojo;

import java.util.HashSet;

import java.util.Set;

public class Classes implements java.io.Serializable

{

// Fields

private Integer classId;

private String className;

private Set students = new HashSet(0);

// Constructors

/** default constructor */

public Classes()

{

}

/** minimal constructor */

public Classes(String className)

{

this.className = className;

}

/** full constructor */

public Classes(String className, Set students)

{

this.className = className;

this.students = students;

}

// Property accessors

public Integer getClassId()

{

return this.classId;

}

public void setClassId(Integer classId)

{

this.classId = classId;

}

public String getClassName()

{

return this.className;

}

public void setClassName(String className)

{

this.className = className;

}

public Set getStudents()

{

return this.students;

}

public void setStudents(Set students)

{

this.students = students;

}

}



<?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="com.xy.pojo.Classes" table="classes" catalog="stuinfo">

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

<column name="classId" />

<generator class="native" />

</id>

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

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

</property>

<set name="students" inverse="true" cascade="all">

<key>

<column name="fclassId" />

</key>

<one-to-many class="com.xy.pojo.Student" />

</set>

</class>

</hibernate-mapping>



package com.xy.pojo;

import java.util.Date;

public class Student implements java.io.Serializable

{

// Fields

private Integer stuId;

private Classes classes;

private String stuName;

private Short stuSex;

private Short stuAge;

private Date stuBirth;

private String stuHobby;

private Short stuStatus;

// Constructors

/** default constructor */

public Student()

{

}

/** minimal constructor */

public Student(String stuName)

{

this.stuName = stuName;

}

/** full constructor */

public Student(Classes classes, String stuName, Short stuSex, Short stuAge, Date stuBirth, String stuHobby, Short stuStatus)

{

this.classes = classes;

this.stuName = stuName;

this.stuSex = stuSex;

this.stuAge = stuAge;

this.stuBirth = stuBirth;

this.stuHobby = stuHobby;

this.stuStatus = stuStatus;

}

// Property accessors

public Integer getStuId()

{

return this.stuId;

}

public void setStuId(Integer stuId)

{

this.stuId = stuId;

}

public Classes getClasses()

{

return this.classes;

}

public void setClasses(Classes classes)

{

this.classes = classes;

}

public String getStuName()

{

return this.stuName;

}

public void setStuName(String stuName)

{

this.stuName = stuName;

}

public Short getStuSex()

{

return this.stuSex;

}

public void setStuSex(Short stuSex)

{

this.stuSex = stuSex;

}

public Short getStuAge()

{

return this.stuAge;

}

public void setStuAge(Short stuAge)

{

this.stuAge = stuAge;

}

public Date getStuBirth()

{

return this.stuBirth;

}

public void setStuBirth(Date stuBirth)

{

this.stuBirth = stuBirth;

}

public String getStuHobby()

{

return this.stuHobby;

}

public void setStuHobby(String stuHobby)

{

this.stuHobby = stuHobby;

}

public Short getStuStatus()

{

return this.stuStatus;

}

public void setStuStatus(Short stuStatus)

{

this.stuStatus = stuStatus;

}

}



<?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="com.xy.pojo.Student" table="student" catalog="stuinfo">

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

<column name="stuId" />

<generator class="native" />

</id>

<many-to-one name="classes" class="com.xy.pojo.Classes"

fetch="select">

<column name="fclassId" />

</many-to-one>

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

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

</property>

<property name="stuSex" type="java.lang.Short">

<column name="stuSex" />

</property>

<property name="stuAge" type="java.lang.Short">

<column name="stuAge" />

</property>

<property name="stuBirth" type="java.util.Date">

<column name="stuBirth" length="10" />

</property>

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

<column name="stuHobby" length="30" />

</property>

<property name="stuStatus" type="java.lang.Short">

<column name="stuStatus" />

</property>

</class>

</hibernate-mapping>

HibernateSessionFactory

package com.xy.pojo;

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.cfg.Configuration;

public class HibernateSessionFactory

{

private static String CONFIG_FILE_LOCATION = "/hibernate.cfg.xml";

private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();

private static Configuration configuration = new Configuration();

private static org.hibernate.SessionFactory sessionFactory;

private static String configFile = CONFIG_FILE_LOCATION;

static

{

try

{

configuration.configure(configFile);

sessionFactory = configuration.buildSessionFactory();

}

catch (Exception e)

{

System.err.println("%%%% Error Creating SessionFactory %%%%");

e.printStackTrace();

}

}

private HibernateSessionFactory()

{

}

/**

* Returns the ThreadLocal Session instance. Lazy initialize the

* <code>SessionFactory</code> if needed.

*

* @return Session

* @throws HibernateException

*/

public static Session getSession() throws HibernateException

{

Session session = (Session) threadLocal.get();

if (session == null || !session.isOpen())

{

if (sessionFactory == null)

{

rebuildSessionFactory();

}

session = (sessionFactory != null) ? sessionFactory.openSession() : null;

threadLocal.set(session);

}

return session;

}

/**

* Rebuild hibernate session factory

*

*/

public static void rebuildSessionFactory()

{

try

{

configuration.configure(configFile);

sessionFactory = configuration.buildSessionFactory();

}

catch (Exception e)

{

System.err.println("%%%% Error Creating SessionFactory %%%%");

e.printStackTrace();

}

}

/**

* Close the single hibernate session instance.

*

* @throws HibernateException

*/

public static void closeSession() throws HibernateException

{

Session session = (Session) threadLocal.get();

threadLocal.set(null);

if (session != null)

{

session.close();

}

}

/**

* return session factory

*

*/

public static org.hibernate.SessionFactory getSessionFactory()

{

return sessionFactory;

}

/**

* return session factory

*

* session factory will be rebuilded in the next call

*/

public static void setConfigFile(String configFile)

{

HibernateSessionFactory.configFile = configFile;

sessionFactory = null;

}

/**

* return hibernate configuration

*

*/

public static Configuration getConfiguration()

{

return configuration;

}

}



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 Hibernate Tools. -->

<hibernate-configuration>

<session-factory>

<property name="dialect">

org.hibernate.dialect.MySQLDialect

</property>

<property name="connection.url">

jdbc:mysql://localhost:3306/stuinfo

</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="myeclipse.connection.profile">

xy_mysql

</property>

<mapping resource="com/xy/pojo/Student.hbm.xml" />

<mapping resource="com/xy/pojo/Classes.hbm.xml" />

</session-factory>

</hibernate-configuration>



package com.xy.test;

import org.hibernate.Session;

import org.hibernate.Transaction;

import com.xy.pojo.Classes;

import com.xy.pojo.HibernateSessionFactory;

import com.xy.pojo.Student;

public class Test

{

public void test01()

{

Session session = null;

Transaction tran = null;

try

{

session = HibernateSessionFactory.getSession();

tran = session.beginTransaction();

// 将学号为30的学生的班级设为3班

Classes c = (Classes) session.createQuery("from Classes c where c.classId=3").uniqueResult();

Student s = (Student) session.createQuery("from Student s where s.stuId=30").uniqueResult();

s.setClasses(c);

tran.commit();

}

catch (Exception e)

{

e.printStackTrace();

tran.rollback();

}

finally

{

HibernateSessionFactory.closeSession();

}

}

public void test02()

{

Session session = null;

Transaction tran = null;

try

{

session = HibernateSessionFactory.getSession();

tran = session.beginTransaction();

// 此处在Classes.hbm.xml的one-to-many中设置了cascade=all

// 表明对Classes的所有CRUD操作,将会级联到Student上

// 比如删除班级号为3的班级,那么学生表中班级为3的同学的记录也会被删除

Classes c = (Classes) session.createQuery("from Classes c where c.classId=3").uniqueResult();

session.delete(c);

tran.commit();

}

catch (Exception e)

{

e.printStackTrace();

tran.rollback();

}

finally

{

HibernateSessionFactory.closeSession();

}

}

public void test03()

{

Session session = null;

Transaction tran = null;

try

{

session = HibernateSessionFactory.getSession();

tran = session.beginTransaction();

// 根据班级号删除学生

Classes c = (Classes) session.createQuery("from Classes c where c.classId=2").uniqueResult();

int count = session.createQuery

("delete from Student s where s.classes=" + c.getClassId()).executeUpdate();

System.out.println(count);

tran.commit();

}

catch (Exception e)

{

e.printStackTrace();

tran.rollback();

}

finally

{

HibernateSessionFactory.closeSession();

}

}

public static void main(String[] args)

{

Test t = new Test();

t.test03();

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: