Hibernate创建重复的对象

时间:2013-03-19 18:58:55

标签: hibernate annotations one-to-many

由于我的内部联接,Hiberate正在创建重复的对象。查询将父表与子表连接(父表与子表有一对多的关系)。

数据:

Category (Parent)
ID|Name
1|A
2|B

Testcase (Child)
ID|CategoryID|Name|Run
1|1|A|500
2|1|B|500
3|1|C|500
4|2|D|600

来自join的结果,其中run = 500

CategoryID|TestcaseID|TestCase Name
1|1|A
1|2|B
1|3|C

由此,我希望Hibernate创建一个Category对象,其中包含一个包含3个testcase对象的列表。相反,它创建了3个Category对象,每个对象都有3个测试用例的正确列表

类别[ID = 1,名称= FOO,testCases = [TestCase [ID = 1,name = A,runId = 500],TestCase [ID = 2,name = B,runId = 500],TestCase [ID = 3,name = C,runId = 500]]]

类别[ID = 1,名称= FOO,testCases = [TestCase [ID = 1,name = A,runId = 500],TestCase [ID = 2,name = B,runId = 500],TestCase [ID = 3,name = C,runId = 500]]]

类别[ID = 1,名称= FOO,testCases = [TestCase [ID = 1,name = A,runId = 500],TestCase [ID = 2,name = B,runId = 500],TestCase [ID = 3,name = C,runId = 500]]]

型号:

@Entity
@Table(name = "CATEGORY")
public class Category implements Serializable
{
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "CATEGORYID")
    private int ID;

    @Column(name = "CATEGORYNAME")
    private String name;

    @OneToMany(fetch = FetchType.EAGER)
    @JoinColumn(name = "CATEGORYID")
    @Filter(name = "TEST_RUN_ID_FILTER")
    private Collection<TestCase> testCases;
}

@Entity
@Table(name = "TESTCASE_NEW")
@FilterDef(name = "TEST_RUN_ID_FILTER", defaultCondition = "TESTRUNID in (:IDS)", parameters = { @ParamDef(name = "IDS", type = "int") })
public class TestCase implements Serializable
{
    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "TESTCASEID")
    private int ID;

    @Column(name = "TESTCASENAME")
    private String name;

    @Column(name = "STATUS")
    private String status;

    @Column(name = "TESTRUNID")
    private int testRunId;
}

DAO:

 public List<Category> getAllCategoriesForTestRuns(List<Integer> testRunIDs)
    {
        Session session = getSession();
        session.enableFilter("TEST_RUN_ID_FILTER")
                .setParameterList("IDS", testRunIDs);
        Query query = session.createQuery("select c from Category c inner join c.testCases tc");
        List<Category> result = query.list();
        return result;
    }

如果我查找HQL查询以选择distinct,我能够得到正确的结果,但我想知道是否有更正确的方法。从我的谷歌搜索,我尝试将@Fetch(FetchMode.SELECT)添加到Category中的testCase列表,但没有效果。

谢谢!

1 个答案:

答案 0 :(得分:2)

使用ResultTransformer:

Query query = session.createQuery("hql")
                  .setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

问题是你的内部联接将为testCases集合中的每个实体返回一个对象(因为数据库查询结果集将用于内部联接)。