休眠。 ManyToOne生成n + 1选择

时间:2016-05-24 10:55:50

标签: hibernate many-to-one

@Entity
@Table(name="Articulo")
public class Articulo implements Serializable { 
        @Id
        @ManyToOne  
        @JoinColumn(name="cod_familia")
        Familia familia;    
        @Id
        String cod_articulo;    
        String lit_articulo;
        char estado;

    @Entity
    @Table(name="familia")
    public class Familia {

        @Id
        String cod_familia;
        String lit_familia;
        char estado;

当我列出所有“articulo”时,这个2课程:

public List<Articulo> list() {
    return session().createCriteria(Articulo.class).list();
}

hibernate生成1选择连接两个表,然后为每个系列添加1 ...

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

原因是这里有一个额外的@Id注释

@Id
@ManyToOne  
@JoinColumn(name="cod_familia")
Familia familia;

如果没有这个注释,Hibernate就不会使用额外的选择

@Entity
@Table(name = "Articulo")
public class Articulo {

    @Id
    private String codArticulo;

    @ManyToOne
    @JoinColumn(name = "cod_familia")
    private Familia familia;

}

    select
        this_.f_cod_articulo as f_cod_ar1_0_1_,
        this_.cod_familia as cod_fami2_0_1_,
        familia2_.f_cod_familia as f_cod_fa1_1_0_ 
    from
        Articulo this_ 
    left outer join
        familia familia2_ 
            on this_.cod_familia=familia2_.f_cod_familia

<强>更新

您可以添加其他代理主键和唯一约束。

@Entity
@Table(name = "Articulo",
        uniqueConstraints = @UniqueConstraint(
        columnNames = { "cod_articulo", "cod_familia" }))
public class Articulo implements Serializable {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "cod_articulo")
    private String codArticulo;

    @ManyToOne
    @JoinColumn(name = "cod_familia")
    private Familia familia;

}