如何检索具有一对多关系的实体与另一个具有一对多关系的实体?

时间:2019-06-20 22:14:14

标签: hibernate hibernate-mapping

在我的项目中,我有三个实体:A,B和C:

@Entity
@Table(name = "ta_testA",catalog = "mytesdb")
public class A{
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="fiIdA")
    private int fiIdA;
    @OneToMany(mappedBy ="a", cascade = CascadeType.ALL, fetch =    FetchType.EAGER, orphanRemoval = true)
    private List<B> b

....(getters and setters)
}

@Entity
@Table(name = "ta_testB",catalog = "mytesdb")
public class B{
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="fiIdB")
    private int fiIdB;
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="fiIdA")
    private A a;
    @OneToMany(mappedBy ="b", cascade = CascadeType.ALL, fetch =    FetchType.EAGER, orphanRemoval = true)
    private List<C> c

....(getters and setters)
}

@Entity
@Table(name = "ta_testC",catalog = "mytesdb")
public class C{
    @Id @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name="fiIdC")
    private int fiIdC;
    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name="fiIdb")
    private B b;

....(getters and setters)
}

public class ADAO extends CoreDAO {

    public A getAById(int id) {
        startOp();
        A a;
        try{
            sesion.flush();
            sesion.clear();
            Query query =  sesion.createQuery("Select a from"
                    + " A as a where "
                    + " (a.fiIdA = :id)");

            a = (A) query.setParameter("id",id).uniqueResult();

        }catch(HibernateException he){
            System.out.println(he.getMessage());
            throw he;
        }finally{
            sesion.close();
        }
        return a;
    }
}

public class BDAO extends CoreDAO {

    public B getBById(int id) {
        startOp();
        B b;
        try{
            sesion.flush();
            sesion.clear();
            Query query =  sesion.createQuery("Select b from"
                    + " B as b where "
                    + " (b.fiIdB = :id)");

            b = (B) query.setParameter("id",id).uniqueResult();

        }catch(HibernateException he){
            System.out.println(he.getMessage());
            throw he;
        }finally{
            sesion.close();
        }
        return b;
    }

}

如果我使用实体A DAO通过id检索对象,那么一切都很好,但是如果我只想获取B实体数据,则List属性会变得凌乱并返回很多重复数据。

如何从实体B仅获取数据,从而避免重复数据的问题?

0 个答案:

没有答案