`
myharmony
  • 浏览: 106257 次
  • 性别: Icon_minigender_1
  • 来自: 中山市
社区版块
存档分类
最新评论

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
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics