快速解决遇到hibernate的小问题
Nov 7
1.id 设置native自增报错?native需要数据库设置自增
id使用native自增,跑测试用例,抛异常
- org.hibernate.HibernateException: The database returned no natively generated identity value
2.单向一对多,抛出异常
User 表对应多个Address,配置User单项一对多,测试用例报错,详情如下:
xml 代码
- <class name="User" table="user">
-
- <id name="userId" type="integer" column="user_id">
- <generator class="native" />
- id>
-
- <bag name="userAddress" lazy="true" >
- <key column="user_id" >key>
- <one-to-many class="UserAddress">one-to-many>
- bag>
-
- class>
报错:UserAddress未保存
java 代码
- org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [com.hibernate.bean.user.UserAddress#123]
原因:没有设置级联更新,添加cascase='true',修改如下:
xml 代码
- <bag name="userAddress" lazy="true" cascade="all">
- <key column="user_id" >key>
- <one-to-many class="UserAddress">one-to-many>
- bag>
3.update一对多对象,报错:no session or session is close
UserAddress设置lazy=true
xml 代码
- <bag name="userAddress" lazy="true" cascade="all">
- <key column="user_id" >key>
- <one-to-many class="UserAddress">one-to-many>
- bag>
将UserAddress的list 赋值给 user, 保存user后,再次查询保存后User , 报错 no session or session is close
java 代码
- public boolean addUserAddress(int userid, UserAddress userAddress) {
-
- User user = (User) dao.findById(User.class, 123);
-
- List list = new ArrayList();
- list.add(userAddress);
-
- user.setUserAddress(list);
-
- dao.update(user);
- User user2 = (User) dao.findById(User.class, 123);
- }
java 代码
- org.hibernate.LazyInitializationException: failed to lazily initialize a collection of role: com.hibernate.bean.user.User.userAddress, no session or session was closed
看到 no session or session was close ,立即应该想到方法没有事务处理,延时加载UserAddress,必须在事务里面,不然怎么加载呢? 添加事务,以spring为例:
java 代码
- @Transactional
- public boolean addUserAddress(int userid, UserAddress userAddress) {
- }