在一对多的问题中遇到Exception 如下:
Department 如下:
测试如下:
开始测试的时候,没有注意类型要一致,用了List类型,结果就出现了
在Department中 尽量不用List作为集合的类型,原因如下:
lists are indexed collections and therefor need a index column
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