hibernate一对多与多对多示例

本文介绍了使用Hibernate框架实现学生、老师和班级的ORM映射及持久化操作的过程,包括实体类的设计、映射文件的编写、配置文件的配置以及测试类的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

文件清单:

文件名

描述

Student.java

学生信息类

Teacher.java

老师信息类

Clazz.java

班级信息类

Student.hbm.xml

学生信息对应映射文件

Teacher.hbm.xml

老师信息对应映射文件

Clazz.hbm.xml

班级信息对应映射文件

Hibernate.cfg.xml

Hibernate配置文件

HibernateUtil.java

Hibernate工具类

Test.java

测试类

 

 

Student.java

import java.util.Set;

 

publicclass Student {

privateintid;

private String name;

privateintage;

private Clazz clazz = null;

private Set<Teacher> teacs;

 

public Set<Teacher> getTeacs() {

returnteacs;

}

publicvoid setTeacs(Set<Teacher> teacs) {

this.teacs = teacs;

}

publicint getId() {

returnid;

}

publicvoid setId(int id) {

this.id = id;

}

public String getName() {

returnname;

}

publicvoid setName(String name) {

this.name = name;

}

publicint getAge() {

returnage;

}

publicvoid setAge(int age) {

this.age = age;

}

public Clazz getClazz() {

returnclazz;

}

publicvoid setClazz(Clazz clazz) {

this.clazz = clazz;

}

}

 

Teacher.java

import java.util.Set;

 

publicclass Teacher {

privateintid;

private String name;

private Set<Student> stus;

 

publicint getId() {

returnid;

}

publicvoid setId(int id) {

this.id = id;

}

public String getName() {

returnname;

}

publicvoid setName(String name) {

this.name = name;

}

public Set<Student> getStus() {

returnstus;

}

publicvoid setStus(Set<Student> stus) {

this.stus = stus;

}

}

 

Clazz.java

import java.util.Set;

 

publicclass Clazz {

privateintid;

private String name;

private Set<Student> stus;

 

publicint getId() {

returnid;

}

publicvoid setId(int id) {

this.id = id;

}

public String getName() {

returnname;

}

publicvoid setName(String name) {

this.name = name;

}

public Set<Student> getStus() {

returnstus;

}

publicvoid setStus(Set<Student> stus) {

this.stus = stus;

}

}

 

Student.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

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

<hibernate-mapping

package="com.xfimti.hiberante.beans">

<class name="Student">

<id name="id" >

<generator class="native"></generator>

</id>

<property name="name"></property>

<property name="age"></property>

 

<many-to-one name="clazz" column="clazz_id"></many-to-one>

<set table="stu_tea" name="teacs">

<key column="student_id"></key>

<many-to-many class="Teacher" column="teacher_id"></many-to-many>

</set>

</class>

 

</hibernate-mapping>

 

Teacher.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

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

<hibernate-mapping

package="com.xfimti.hiberante.beans">

<class name="Teacher">

<id name="id" >

<generator class="native"></generator>

</id>

<property name="name"></property>

 

<set table="stu_tea" name="stus">

<key column="teacher_id"></key>

<many-to-many class="Student" column="student_id"></many-to-many>

</set>

</class>

 

</hibernate-mapping>

 

 

Clazz.hbm.xml

<?xml version="1.0"?>

<!DOCTYPE hibernate-mapping PUBLIC

"-//Hibernate/Hibernate Mapping DTD 3.0//EN"

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

<hibernate-mapping

package="com.xfimti.hiberante.beans">

<class name="Clazz">

<id name="id" >

<generator class="native"></generator>

</id>

<property name="name"></property>

<set name="stus" inverse="true">

<key column="clazz_id"></key>

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

</set>

</class>

 

</hibernate-mapping>

 

 

Hibernate.cg.xml

<!DOCTYPE hibernate-configuration PUBLIC

"-//Hibernate/Hibernate Configuration DTD 3.0//EN"

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

 

<hibernate-configuration>

<session-factory name="foo">

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

<property name="hibernate.format_sql">false</property>

 

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

 

<property name="hibernate.connection.driver_class">

com.mysql.jdbc.Driver

</property>

<property name="hibernate.connection.url">

jdbc:mysql:///test

</property>

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

<property name="hibernate.connection.password">123</property>

<property name="hibernate.dialect">

org.hibernate.dialect.MySQLDialect

</property>

<mapping resource="com/xfimti/hiberante/beans/Student.hbm.xml" />

<mapping resource="com/xfimti/hiberante/beans/Clazz.hbm.xml" />

<mapping resource="com/xfimti/hiberante/beans/Teacher.hbm.xml" />

</session-factory>

</hibernate-configuration>

 

HibernateUtil.java

import org.hibernate.HibernateException;

import org.hibernate.Session;

import org.hibernate.SessionFactory;

import org.hibernate.cfg.Configuration;

 

publicclass HibernateUtil {

privatestatic SessionFactory sessionFactory = null;

 

static {

try {

sessionFactory = new Configuration().configure().buildSessionFactory();

} catch (HibernateException e) {

System.err.println("Initial SessionFactory creation failed." + e);

e.printStackTrace();

}

}

 

publicstatic Session getSession() {

returnsessionFactory.openSession();

}

}

 

Test.java

import java.util.ArrayList;

import java.util.HashSet;

import java.util.List;

import java.util.Set;

 

import org.hibernate.HibernateException;

import org.hibernate.Query;

import org.hibernate.Session;

import org.hibernate.Transaction;

 

import com.xfimti.hiberante.beans.Clazz;

import com.xfimti.hiberante.beans.Student;

import com.xfimti.hiberante.beans.Teacher;

import com.xfimti.hibernate.util.HibernateUtil;

 

publicclass Test {

 

publicstaticvoid main(String[] args) {

/*一对多示例。*/

/*List<Student> ss = getAllStudent(3);

System.out.println(ss.size());

Iterator<Student> its = ss.iterator();

while(its.hasNext()) {

Student s = its.next();

System.out.println(s.getName()+","+s.getAge());

}*/

 

/*多对多示例。*/

/*添加一个老师的信息。*/

/*Teacher t = new Teacher();

t.setName("teacher1");

addTeacher(t);*/

 

/*添加一个班级信息。*/

/*Clazz clazz = new Clazz();

clazz.setName("xxxxxx");

addClazz(clazz);*/

 

/*添加一个学生信息。他的老师是teacher1,所在班级为xxxxxx*/

Student s = new Student();

s.setName("yyyyyy");

String clazzName = "xxxxxx";

String teacherName = "teacher1";

addStudent(s, clazzName, teacherName);

}

 

/**根据班级名称查询出班级信息。*/

publicstatic Clazz getClazz(String name) {

Clazz clazz = null;

Session s = HibernateUtil.getSession();

Query q = s.createQuery("from Clazz as c where c.name=?");

q.setString(0, name);

clazz = (Clazz) q.uniqueResult();

if(s != null) {

s.close();

}

return clazz;

}

 

/**添加学生信息。*/

publicstaticvoid addStudent(Student stu,String clazzName) {

Session session = null;

Transaction tx = null;

 

try {

session = HibernateUtil.getSession();

tx = session.beginTransaction();

session.saveOrUpdate(stu);

Clazz clazz = getClazz(clazzName);

stu.setClazz(clazz);

tx.commit();

} catch (HibernateException e) {

if(tx != null) {

tx.rollback();

}

e.printStackTrace();

}

finally{

if(session != null) {

session.close();

}

}

}

 

/**添加班级信息。*/

publicstaticvoid addClazz(Clazz clazz) {

Session session = null;

Transaction tx = null;

 

try {

session = HibernateUtil.getSession();

tx = session.beginTransaction();

session.save(clazz);

tx.commit();

} catch (HibernateException e) {

if(tx != null) {

tx.rollback();

}

e.printStackTrace();

}

finally{

if(session != null) {

session.close();

}

}

}

 

/**通过班级编号,查询出该班级所有的学生信息。*/

publicstatic List<Student> getAllStudent(int clazz_id) {

List<Student> ss = new ArrayList<Student>();

Session s = HibernateUtil.getSession();

Clazz clazz = (Clazz) s.get(Clazz.class, 3);

for (int i = 0; i < clazz.getStus().size(); i++) {

ss.add((Student)clazz.getStus().toArray()[i]);

}

return ss;

}

 

/**添加老师信息*/

publicstaticvoid addTeacher(Teacher t) {

Session session = null;

Transaction tx = null;

 

try {

session = HibernateUtil.getSession();

tx = session.beginTransaction();

session.save(t);

tx.commit();

} catch (HibernateException e) {

if(tx != null) {

tx.rollback();

}

e.printStackTrace();

}

finally{

if(session != null) {

session.close();

}

}

}

 

/**添加学生信息。多对多*/

publicstaticvoid addStudent(Student s,String clazzName,String teacherName) {

Session ss = null;

Transaction tx = null;

try {

ss = HibernateUtil.getSession();

tx = ss.beginTransaction();

ss.save(s);

/*根据班级名称查出班级信息。*/

Query q = (Query) ss.createQuery("from Clazz where name=?");

q.setString(0, clazzName);

Clazz clazz = (Clazz) q.uniqueResult();

q = null;

/*根据老师姓名查出老师信息。*/

q = ss.createQuery("from Teacher where name=?");

q.setString(0, teacherName);

Teacher t = (Teacher) q.uniqueResult();

s.setClazz(clazz);

/*clazzt设置到s,在处理持久化状态自动检测更改并修改。*/

Set<Teacher> st = new HashSet<Teacher>();

st.add(t);

s.setTeacs(st);

tx.commit();

} catch (HibernateException e) {

if(tx != null) {

tx.rollback();

}

e.printStackTrace();

}finally {

if(ss != null) {

ss.close();

}

}

}

 

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值