`
ttitfly
  • 浏览: 623896 次
  • 性别: Icon_minigender_1
  • 来自: 杭州
社区版块
存档分类
最新评论

hibernate----one-to-many

阅读更多
hibernate里的一对多one-to-many(以学生和班级为例子)
1.双向关联情况下

Classes.java:

package com.domain;

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

public class Classes implements java.io.Serializable {


	private Integer id;

	private String name;

	private Set students = new HashSet(0);

	public Classes() {
	}

	public Classes(String name) {
		this.name = name;
	}

	public Classes(String name, Set students) {
		this.name = name;
		this.students = students;
	}

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Set getStudents() {
		return this.students;
	}

	public void setStudents(Set students) {
		this.students = students;
	}

}


Student.java

package com.domain;

public class Student implements java.io.Serializable {

	private Integer id;

	private Classes classes;

	private String name;

	public Student() {
	}

	public Student(String name) {
		this.name = name;
	}

	public Student(Classes classes, String name) {
		this.classes = classes;
		this.name = name;
	}

	public Integer getId() {
		return this.id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Classes getClasses() {
		return this.classes;
	}

	public void setClasses(Classes classes) {
		this.classes = classes;
	}

	public String getName() {
		return this.name;
	}

	public void setName(String name) {
		this.name = name;
	}

}


Classes.hbm.xml


<?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.domain.Classes" table="classes" catalog="hibernatetest">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="native" />
        </id>
        <property name="name" type="java.lang.String">
            <column name="name" not-null="true" />
        </property>
        <!-- inverse="true" 主动权反转给了Classes,cascade="all"级联students表里的数据会级联被删除或更新等,这里设置的是all,lazy="true" students表里的数据会lazy加载 -->
        <set name="students" inverse="true" cascade="all" lazy="true">
            <key>
                <column name="classId" />
            </key>
            <one-to-many class="com.domain.Student" />
        </set>
    </class>
</hibernate-mapping>


Student.hbm.xml


<?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.domain.Student" table="student" catalog="hibernatetest">
        <id name="id" type="java.lang.Integer">
            <column name="id" />
            <generator class="native" />
        </id>
        <!-- cascade="all" classes表里的数据会被级联操作   fetch="select" classes表里的数据会以左外连接的形式取出来(根据学生查找班级的具体信息时),如果值是join 则进行内连接-->
        <many-to-one name="classes" class="com.domain.Classes" fetch="select" cascade="all">
            <column name="classId" />
        </many-to-one>
        <property name="name" type="java.lang.String">
            <column name="name" not-null="true" />
        </property>
    </class>
</hibernate-mapping>


测试类
package com.dao;


import java.util.Iterator;
import java.util.Set;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.domain.Classes;
import com.domain.Student;

public class Test {
	public static void main(String[] args){
		Session session = HibernateSessionFactory.getSession();
		Transaction tx = session.beginTransaction();
		//添加数据
		/*
		
		//定义学生一
		Student student1 = new Student();
		student1.setName("zhansan");
		//定义学生二
		Student student2 = new Student();
		student2.setName("lisi");
		
		//定义班级0201班
		Classes classes = new Classes();
		classes.setName("0201");
		//双向关联给主表设置关联
		classes.getStudents().add(student1);
		classes.getStudents().add(student2);
		
		//双向关联给从表设置关联
		student1.setClasses(classes);
		student2.setClasses(classes);
		
		session.save(classes);
		
		tx.commit();
		session.close();
		*/
		
		//修改多方
		//修改学生,必须给要修改的这个学生每个属性都赋值
		/*Student student = new Student();
		student.setName("wangwu111");
		student.setId(1);
		
		Classes classes = new Classes();
		classes.setId(1);
		classes.setName("0201");
		//如果下面这句代码不要的话,则修改执行的sql为update hibernatetest.student set classId=?, name=? where id=?,修改后classId为null(即使classId原来有值,也会被改为null),所以,必须给要修改的这个学生每个属性都赋值
		student.setClasses(classes);
		
		//修改
		session.update(student);
		
		tx.commit();
		session.close();*/
		//修改执行的sql:
		/*
		Hibernate: update hibernatetest.student set classId=?, name=? where id=?
		Hibernate: update hibernatetest.classes set name=? where id=?
		级联修改
		*/
		
		
		
		//修改一方,不需要给Set集合属性赋值
		/*
		Classes classes = new Classes();
		classes.setId(1);
		classes.setName("0210");
		//修改
		session.update(classes);
		
		tx.commit();
		session.close();*/
		//执行的sql:Hibernate: update hibernatetest.classes set name=? where id=?
		
		//查询操作
		String hql = "from Classes c where c.id=1";
		Query query = session.createQuery(hql);
		Classes classes = (Classes)query.uniqueResult();
		System.out.println(classes.getId() + " : " + classes.getName() + " : ");
		//如果再这里进行session.close();那么需要写下面的判断,强制性去拿student表里的数据
//		if(!Hibernate.isInitialized(classes.getStudents())){
//			Hibernate.initialize(classes.getStudents());
//		}
		
		//因为Student设置的lazy,执行下面的语句时,才去student表查询
		Set set = classes.getStudents();
		Iterator iterator = set.iterator();
		while(iterator.hasNext()){
			Student cla = (Student)iterator.next();
			System.out.println(cla.getId() + " : " + cla.getName());
		}
		session.close();
		//执行的sql
		/*
		Hibernate: select classes0_.id as id1_, classes0_.name as name1_ from hibernatetest.classes classes0_ where classes0_.id=1
		1 : 0210 : 
		Hibernate: select students0_.classId as classId1_, students0_.id as id1_, students0_.id as id0_0_, students0_.classId as classId0_0_, students0_.name as name0_0_ from hibernatetest.student students0_ where students0_.classId=?
		2 : zhansan
		1 : wangwu111
		*/
	}

}



根据学生查找班级:

package com.dao;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;

import com.domain.Student;

public class TestSelect {

	public static void main(String[] args) {
		Session session = HibernateSessionFactory.getSession();
		String hql = "from Student s where s.classes.id=1";
		Query query = session.createQuery(hql);
		List<Student> list = query.list();
		
		for(int i=0;i<list.size();i++){
			Student student = (Student)list.get(i);
			System.out.println(student.getId() + " : " + student.getName() + " : " + student.getClasses().getId() + " : " + student.getClasses().getName());
			
			//执行的sql:Hibernate: select student0_.id as id0_, student0_.classId as classId0_, student0_.name as name0_ from hibernatetest.student student0_ where student0_.classId=1
			//System.out.println(student.getId() + " : " + student.getName());
		}
		
		session.close();
		/**
		 执行的sql为:
		 Hibernate: select student0_.id as id0_, student0_.classId as classId0_, student0_.name as name0_ from hibernatetest.student student0_ where student0_.classId=1
		 Hibernate: select classes0_.id as id1_0_, classes0_.name as name1_0_ from hibernatetest.classes classes0_ where classes0_.id=?

		 

		 */

	}

}




2.单向关联情况下

把一方的Set集合去掉,对应的.hbm.xml里的部分也给去掉。
即去掉:
 <set name="students" inverse="true" cascade="all" lazy="true">
            <key>
                <column name="classId" />
            </key>
            <one-to-many class="com.domain.Student" />
        </set>


测试类:
package com.dao;

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

import com.domain.Classes;
import com.domain.Student;

public class TestInsert {

	public static void main(String[] args) {
		Session session = HibernateSessionFactory.getSession();
		Transaction tx = session.beginTransaction();
		//定义班级0201班
		Classes classes = new Classes();
		classes.setName("0201test");
		
		//定义学生一
		Student student1 = new Student();
		student1.setName("zhansantest");
		student1.setClasses(classes);
		//定义学生二
		Student student2 = new Student();
		student2.setName("lisitest");
		student2.setClasses(classes);
		
		//classes一定要最先被save
		session.save(classes);
		session.save(student1);
		session.save(student2);
		
		tx.commit();
		session.close();
		/**
		 执行的sql:
		 Hibernate: insert into hibernatetest.classes (name) values (?)
		 Hibernate: insert into hibernatetest.student (classId, name) values (?, ?)
		 Hibernate: insert into hibernatetest.student (classId, name) values (?, ?)
		 */
		
		
		

	}

}


分享到:
评论
2 楼 jiangshaolin 2008-04-18  
不知道是什么意思...
1 楼 jiangshaolin 2008-04-18  
谢谢你,有一个问题还想请教你.

java.lang.NullPointerException
at org.hibernate.tuple.AbstractEntityTuplizer.createProxy(AbstractEntityTuplizer.java:372)
at org.hibernate.persister.entity.AbstractEntityPersister.createProxy(AbstractEntityPersister.java:3121)
at org.hibernate.event.def.DefaultLoadEventListener.createProxyIfNecessary(DefaultLoadEventListener.java:232)
at org.hibernate.event.def.DefaultLoadEventListener.proxyOrLoad(DefaultLoadEventListener.java:173)
at org.hibernate.event.def.DefaultLoadEventListener.onLoad(DefaultLoadEventListener.java:87)
at org.hibernate.impl.SessionImpl.fireLoad(SessionImpl.java:862)
at org.hibernate.impl.SessionImpl.internalLoad(SessionImpl.java:830)
at org.hibernate.type.EntityType.resolveIdentifier(EntityType.java:266)
at org.hibernate.type.EntityType.resolve(EntityType.java:303)
at org.hibernate.engine.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:116)
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:842)
at org.hibernate.loader.Loader.doQuery(Loader.java:717)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:224)
at org.hibernate.loader.Loader.doList(Loader.java:2145)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2029)
at org.hibernate.loader.Loader.list(Loader.java:2024)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:375)
at org.hibernate.hql.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:308)
at org.hibernate.engine.query.HQLQueryPlan.performList(HQLQueryPlan.java:153)
at org.hibernate.impl.SessionImpl.list(SessionImpl.java:1106)
at org.hibernate.impl.QueryImpl.list(QueryImpl.java:79)
at org.jsl.mybbs.dao.impl.IQuestionDAOImpl.queryByCommemflag(IQuestionDAOImpl.java:25)
at org.jsl.mybbs.struts.action.IndexAction.list(IndexAction.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:589)
at org.apache.struts.actions.DispatchAction.dispatchMethod(DispatchAction.java:270)
at org.apache.struts.actions.DispatchAction.execute(DispatchAction.java:187)
at org.apache.struts.action.RequestProcessor.processActionPerform(RequestProcessor.java:431)
at org.apache.struts.action.RequestProcessor.process(RequestProcessor.java:236)
at org.apache.struts.action.ActionServlet.process(ActionServlet.java:1196)
at org.apache.struts.action.ActionServlet.doGet(ActionServlet.java:414)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:689)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:237)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
at org.jsl.mybbs.filter.EncodingFilter.doFilter(EncodingFilter.java:22)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:186)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:157)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:214)
at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
at org.apache.catalina.core.StandardContextValve.invokeInternal(StandardContextValve.java:198)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:152)
at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:137)
at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:118)
at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:102)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.core.StandardValveContext.invokeNext(StandardValveContext.java:104)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:520)
at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:929)
at org.apache.coyote.tomcat5.CoyoteAdapter.service(CoyoteAdapter.java:160)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:799)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:705)
at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:577)
at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:683)
at java.lang.Thread.run(Thread.java:626)
Hibernate: select subitems0_.itemid as itemid1_, subitems0_.subid as subid1_, subitems0_.subid as subid4_0_, subitems0_.itemid as itemid4_0_, subitems0_.subname as subname4_0_, subitems0_.subcode as subcode4_0_ from mybbs.subitem subitems0_ where subitems0_.itemid=?
Hibernate: select questions0_.subid as subid1_, questions0_.qid as qid1_, questions0_.qid as qid5_0_, questions0_.subid as subid5_0_, questions0_.id as id5_0_, questions0_.title as title5_0_, questions0_.content as content5_0_, questions0_.offerscore as offerscore5_0_, questions0_.status as status5_0_, questions0_.clickcount as clickcount5_0_, questions0_.accpetflag as accpetflag5_0_, questions0_.commenflag as commenflag5_0_, questions0_.questiontime as questio11_5_0_ from mybbs.question questions0_ where questions0_.subid=?

相关推荐

    Hibernate one-to-many / many-to-one关系映射

    "Hibernate one-to-many / many-to-one关系映射"是两个基本的关系类型,用于表示实体间的关联。在这个主题中,我们将深入探讨这两种关系映射的原理、配置和实际应用。 一、一对一(one-to-one)与一对多(one-to-...

    (4)Hibernate中的many-to-one和one-to-many关系

    本话题主要探讨两种基本的关系映射类型:many-to-one(多对一)和one-to-many(一对多)。这两种关系映射是数据库中常见的关联类型,理解和掌握它们对于开发高质量的Java应用至关重要。 1. many-to-one关系 many-to...

    hibernate many-to-one(多对一)及 cascade(级联).doc

    ### Hibernate Many-to-One (多对一) 及 Cascade (级联) #### 一、Many-to-One(多对一) 在数据库设计中,实体之间的关系主要包括一对一、一对多、多对多等几种类型。而在ORM(对象关系映射)框架Hibernate中,...

    Hibernate-one-to-many

    同时,`Account.hbm.xml`中的`many-to-one`元素将`column`属性设置为`FID`,表示通过`FID`字段关联到`User`实体。 #### 测试场景解释 在测试场景中,我们创建了一个`User`对象和一个`Account`对象,并在`User`对象...

    hibernate学习5之one-to-many双向关联.docx

    在配置双向一对多关联时,我们通常在"多"一端(这里是`Student`)的集合属性上使用`&lt;many-to-one&gt;`标签,将`Classes`对象映射到数据库中的外键。同时,在"一"端(`Classes`)使用`&lt;set&gt;`标签,表示班级可以包含多个...

    hibernate one-to-one 一对一唯一外键关联映射_单向 and 双向

    在Hibernate中,一对一唯一外键关联映射可以通过 `&lt;many-to-one&gt;` 标签来配置。例如,以下是Person实体与IdCard实体的一对一唯一外键关联映射配置: ```xml &lt;many-to-one name="idCard" column="card_id...

    Hibernate one-to-many-annotation

    在Hibernate中,`one-to-many`关系是常见的实体间关系之一,表示一个实体可以与多个其他实体相关联。本文将深入探讨`Hibernate one-to-many`注解的使用和实现细节。 ### 一、`@OneToMany`注解概述 `@OneToMany`...

    Hibernate Mapping Many-to-One 实例 内附源代码及附件下载

    本实例将详细讲解如何在Hibernate中实现Many-to-One关系映射,这是一种常见的数据库关联,表示一个实体可以与多个其他实体相关联。 在Many-to-One关系中,通常一个实体(如部门)可以有多个相关实体(如员工),而...

    Hibernate Tutorial 04 (Many-to-one and One-to-one Association

    为了使用 `publisher` 属性,我们需要在 `Book` 类的 Hibernate 映射文件中添加 `&lt;many-to-one&gt;` 映射。这将在 `BOOK` 表中添加一个名为 `PUBLISHER_ID` 的列,并存储关联出版商的 ID。 ```xml &lt;!-- 其他属性的...

    hibernate-shards.jar

    non-free programs enables many more people to use the whole GNU operating system, as well as its variant, the GNU/Linux operating system. Although the Lesser General Public License is Less ...

    Hibernate应用例子many-to-many

    本示例将详细讲解如何在Hibernate中实现多对多(many-to-many)的关系映射。 在数据库设计中,多对多关系是指两个实体之间存在多个关联,比如学生和课程的关系,一个学生可以选修多门课程,一门课程也可以被多个...

    Hibernate中many-to-one关系的编写_远航的水手

    Hibernate中many-to-one关系的编写_远航的水手

    hibernate-release-5.0.7.Final.zip官方

    &lt;one-to-many class="Order"/&gt; ``` ```java @Entity public class User { @Id private Long id; private String name; @Fetch(FetchMode.JOIN) @OneToMany(mappedBy = "user") private List&lt;Order&gt;...

    Hibernate one to many(many to one) 配置

    标题"Hibernate one to many(many to one) 配置"涉及到的是关系型数据库在Java中的持久化框架Hibernate中的两种关联映射关系:一对一(One-to-One)和多对一(Many-to-One)。在数据库设计中,这种关系很常见,例如...

    Hibernate中many-to-one关系的编写_远航的水手.htm

    Hibernate中many-to-one关系的编写_远航的水手.htm

    hibernate-mapping

    例如,`&lt;one-to-one&gt;`、`&lt;many-to-one&gt;`、`&lt;one-to-many&gt;`和`&lt;many-to-many&gt;`元素分别对应这四种关系。关联映射通常涉及外键的处理和级联操作。 5. 注解方式的Mapping 除了XML映射,Hibernate还支持注解方式的映射...

    hibernate-dtd

    映射文件`*.hbm.xml`则是Hibernate对象与数据库表之间的映射定义,DTD在这里定义了如`&lt;class&gt;`、`&lt;table&gt;`、`&lt;id&gt;`、`&lt;property&gt;`、`&lt;many-to-one&gt;`等元素的结构。通过这些元素,开发者可以详细指定Java类与数据库表...

    Hibernate-api Hibernate文档

    - Many-to-One:多对一关联。 - Many-to-Many:多对多关联。 十、Inheritance Mapping Hibernate支持三种继承映射策略:Single Table、Table Per Class Hierarchies 和 Table Per Subclass。 十一、Hibernate事件...

    many-to-one 配置详解

    many-to-one 配置详解 讲的很清楚 适合新手 值得下载

    hibernate one-to-many 单/双向关联映射配置心得

    本文主要关注Hibernate中的一个核心概念——一对一(One-to-One)、一对多(One-to-Many)和多对一(Many-to-One)关联映射,特别是关于“一到多”单向和双向关联映射的配置心得。 首先,让我们了解“一到多”关联...

Global site tag (gtag.js) - Google Analytics