Hibernate:获得太多行 [英] Hibernate: getting too many rows

查看:154
本文介绍了Hibernate:获得太多行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在使用Hibernate从数据库中获取行时遇到问题。当我想只获得一行时,我收到的是20.当我想从表中获得大约1.5k行的所有行时,我收到了15.2k行。
此表的实体类具有复合主键。

I have problem with getting rows from my database using Hibernate. When I would like to get only one row, I am receiving 20. When I would like to get all of rows from table with about 1.5k rows, I am receiving exactly 15.2k rows. Entity class of this table has composite primary key.

这是获取所有行的代码:

This is my code for getting all rows:

Criteria criteria = getSession().createCriteria(type);
criteria.setCacheable(true).setCacheRegion(BaseEntity.PACKAGE);
criteria.list();

这是我的实体类:

@javax.persistence.Entity
@Table(name = "my_table")
public class My extends MyEntity<MyPK> {

    @EmbeddedId
    private MyPK id;

    @Column(name = "text", nullable = false)
    protected String text;

    @ManyToOne
    @JoinColumn(name = "property", nullable = false, insertable = false, updatable = false)
    protected Option option;

    @Override
    public MyPK getId() {
        return id;
    }

    @Override
    public void setId(MyPK id) {
        this.id = id;
    }

    //getters and setter
}

这是 MyPK 类:

@Embeddable
public class MyPK implements Serializable {

   @Column(name = "qwerty")
   protected String qwerty;

   @Column(name = "property")
   protected String property;

   //constructors, getters and setters
}

MyEntity 类是带有 @MappedSuperclass 注释的抽象类。这是这个类标题:

MyEntity class is abstract class with @MappedSuperclass annotation. This is this class header:

@MappedSuperclass
public abstract class MyEntity<T extends Serializable>

我做错了什么?这个问题是 EmbeddedId

What am I doing wrong? Is this problem with EmbeddedId?

编辑#1
我是已经意识到这是问题所在:

EDIT #1 As I have realized this is problem with this:

@ManyToOne
@JoinColumn(name = "property", nullable = false, insertable = false, updatable = false)
protected Option option;

此对象包含另一个表的外键。而这另一张表引用了另一张表。最后一个表有10行用于上一个表。在结果中我得到行数量* 10.问题可能在于我的实体中的Hibernate注释。

This object contains foreign key to another table. And this another table has reference to another. And this last table has 10 rows for previous table. In the result I am getting rows amount * 10. The problem is probably with Hibernate annotation in my entities.

推荐答案

它看起来像你可能正急切地想要在某个地方加入多对一的关系。默认行为是您为数据库返回的每一行获取一个实体。如果您不想更改热切的提取,但想要删除结果中的重复项,则需要使用此 ResultTransformer

It looks like you're probably eagerly joining a many-to-one relationship somewhere. The default behavior is that you get one entity for each row returned by the database. If you don't want to change the eager fetching, but do want to remove duplicates in your result, you need to use this ResultTransformer:

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

这篇关于Hibernate:获得太多行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆