Hibernate 多对一的 实现

在一对多的问题中遇到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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值