hibernate中的常见错误及Hibernate学习笔记

本文解析了ORM框架中常见的两个错误:一是保存含有未持久化关联对象时的异常;二是懒加载集合时因会话关闭导致的问题,并给出了相应的解决办法。

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

>>1.object references an unsaved transient instance - save the transient instanc

出现这个错误的原因是在保存该对象前,发现该对象包含有其他空的对象。

我的报错地方是在执行一对多级联的时候报错:

/*********************************************/
			Set<Channel> channelSet = new HashSet<Channel>();
			Channel channel = null;
			for(int i=1;i<4;i++) {
				channel = new Channel();
				channel.setChannelId(i);
				channel.setChannel("channel" + i);
				channel.setChannelName("channelName" + i);
				channelSet.add(channel);
			}
			
			user.setChannels(channelSet);

			/*********************************************/
			
			userService.save(user);

之间报这样的错是因为数据库中并没有保存相应的对象,等保存后错误就消失了,执行这个操作后会把数据库中对应的一个字段填上值。

 

>>2.failed to lazily initialize a collection of role: com.gmako.entity.UserInfo.extendsUserInfos, no session or session was closed

这个是懒加载异常,就是在查询时没有加载关联表的对象,你读取这个关联对象的时候,hibernate的session已经关闭,所以无法获取对象。你可以在配置文件里关闭懒加载 lazily=false

<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
                                   "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- 
    Mapping file autogenerated by MyEclipse - Hibernate Tools
-->
<hibernate-mapping>
 <class lazy="false" name="com.autonavi.monitor.model.User" table="user">
  <id name="userId" type="integer" unsaved-value="0">
   <column name="userId"/>
   <generator class="native"/>
  </id>
  <property  name="name" type="string">
   <column name="name" />
  </property>
  <property  name="userName" type="string">
   <column name="userName" not-null="true"/>
  </property>
  <property name="password" type="string">
   <column name="password" not-null="true"/>
  </property>
  <property name="actor" type="int">
   <column name="actor"/>
  </property>
  <property name="authority" type="string">
   <column name="authority"/>
  </property>
  <property  name="email" type="string">
   <column name="email"/>
  </property>
  <property name="phone" type="string">
   <column name="phone"/>
  </property>
 <property name="phone1" type="string">
   <column name="phone1"/>
  </property>
  <property name="phone2" type="string">
   <column name="phone2"/>
  </property>
  
  <set name="channels" cascade="all" lazy="false">
      <key column="userId" />
      <one-to-many class="com.autonavi.monitor.model.Channel"/>
  </set>
  
 </class>
</hibernate-mapping>


>>3. HQL语句,from后面是对象名而不是表名,where后面是对象的属性名而不是表的字段名

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值