使用DetachedCriteria对多个子查询进行Hibernate

时间:2017-09-09 17:56:17

标签: mysql hibernate detachedcriteria

我想将此查询写入HQL:

select DISTINCT * from transportation transp 
    inner join price p on p.transportationId = transp.transportationId 
    where p.sectionId = ( select sec.sectionId from section sec where sec.lineId = ( select l.lineId from line l where l.lineId = 1000000000) )

但不知道写子查询。我知道我必须使用DetachedCriteria。

另一个问题: 如果我们可以在本机查询中编写此查询(使用createSQLQuery),如何将返回的objet转换为Transportation实体?

由于

我的实体:

@Entity
@Table(name = "transportation")
public class Transportation implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "transportationId")
    private Integer id;

    @OneToMany(mappedBy = "transportation", fetch = FetchType.EAGER)
    @JsonBackReference(value = "price-transportation")
    private Set<Price> prices = new HashSet<Price>();
    ...
}

@Entity
@Table(name = "price")
public class Price implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "priceId")
    private Integer id;

    @ManyToOne(optional = false)
    @JoinColumn(name = "transportationId")
    @JsonManagedReference(value = "price-transportation")
    private Transportation transportation;
    ...
}

@Entity
@Table(name = "section")
public class Section implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "sectionId")
    private Integer id;

    @ManyToOne(optional = false)
    @JoinColumn(name = "lineId")
    @JsonManagedReference
    private Line line;
    ...
}


@Entity
@Table(name = "line")
public class Line implements Serializable {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "lineId")
    private Integer id;

    @OneToMany(mappedBy = "line", cascade = CascadeType.ALL, fetch = FetchType.EAGER)
    @JsonBackReference
    private Set<Section> sections = new HashSet<Section>();
    ...
}

1 个答案:

答案 0 :(得分:0)

我使用 .addEntity(Transportation.class)解决了我的问题:

String query = "select DISTINCT * from moyen_transport transp"
                + " join prix_voyage p on p.ID_MoyenTransport = transp.ID_MoyenTransport"
                + " where p.ID_Troncon = ( select t.ID_Troncon from troncon t where t.ID_Troncon = ( select l.ID_Ligne from ligne l where l.ID_Ligne = 1000000000) )";
Query result = getSession().createSQLQuery(query).addEntity(Transportation.class)**;
List<Transportation> results = result.list();