在一对多的问题中遇到Exception 如下:
org.hibernate.exception.SQLGrammarException: could not initialize a collection
Department 如下:
package com.domain;
import java.util.Set;
public class Department {
private int id;
private String deptname ;
private Set<Employee> emps;
public Set<Employee> getEmps() {
return emps;
}
public void setEmps(Set<Employee> emps) {
this.emps = emps;
}
public Department() {
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getDeptname() {
return deptname;
}
public void setDeptname(String deptname) {
this.deptname = deptname;
}
}
测试如下:
public class ManyToOneTest {
public static void main(String[] args) {
Set<Employee> emps = queryEmpByDeptID(1);
for (Employee emp : emps) {
System.out.println(emp.getId() + " " + emp.getName());
}
System.out.println("----end----");
}
static Set<Employee> queryEmpByDeptID(int deptid) {
Session session = null;
Transaction tx = null;
Department dept = new Department();
[b]Set[/b]<Employee> emps;
try {
session = HibernateUtil.getSession();
dept = (Department) session.get(Department.class, deptid);
Hibernate.initialize(dept.getEmps());
System.out.println(dept.getEmps().size());
emps = [b](Set)[/b] dept.getEmps();
return emps;
} catch (HibernateException e) {
throw e;
} finally {
if (session != null) {
session.close();
}
}
}
}
开始测试的时候,没有注意类型要一致,用了List类型,结果就出现了
org.hibernate.exception.SQLGrammarException: could not initialize a collection
在Department中 尽量不用List作为集合的类型,原因如下:
lists are indexed collections and therefor need a index column
分享到:
相关推荐
Hibernate一对一,一对多,多对多实例
这里包含了hibernate多对一单向关联关系实现源码,希望对你有用。
hibernate外键实现一对一双向关联关系源码
hibernate主键实现一对一单向关联关系源码
hibernate外键实现一对一单向关联关系源码
用Hibernate实现数据库表的一对一,一对多,多对多设置,以及向数据库添加数据
NULL 博文链接:https://fangguanhong.iteye.com/blog/1735885
是用hibernate实现一对多的关联对初学javaee有一定的帮助希望大家努力学习呀
该中有一对多,多对一,多对多,单向的双向都具有
hibernate中一对多和多对一的配置区别
hibernate一对一主键关联代码实现
论坛系统项目(Struts 2+Hibernate+Spring实现)论坛系统项目(Struts 2+Hibernate+Spring实现)论坛系统项目(Struts 2+Hibernate+Spring实现)论坛系统项目(Struts 2+Hibernate+Spring实现)论坛系统项目(Struts...
使用Struts2+Hibernate实现对部门表、员工表两张表的增删改查。
hibernate基于主外键的一对多/多对一关联
用户Hibernate实现的一个分页 希望对大家有用哦!!!
本实例采用struts+hibernate实现注册功能,也就给数据库加入一条记录,其中包括时间字段的添加.
使用hibernate技术实现对MySQL数据库的一对多和多对一的映射。下载后对应着改一下自己的IP地址就好了。
Spring+Hibernate实现用户登录程序,可执行,里面配置文件是正确的,在mysql中见一个wangwei数据库,再建个user表就可执行
解压导入到你的Myeclipse或者eclipse,更改路径,加入架包