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

>>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后面是对象的属性名而不是表的字段名

 

 

你可能感兴趣的:(hibernate中的常见错误及Hibernate学习笔记)