从两个表Hibernate加入的标准

时间:2017-06-13 07:28:31

标签: java sql hibernate criteria

我有2个实体 黑名单

public class BlackList {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", unique = true, nullable = false)
    private Integer id;

    @ManyToOne
    @JoinColumn(name = "applicant_id", unique = true)
    private Applicant applicant;

public class Applicant {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id", unique = true, nullable = false)
    private Integer id;

    @Column(name = "number", nullable = false, unique = true)
    private String number;

请帮帮我。如何为此查询创建获取数据的条件:select applicant.number from black_list inner join applicant on black_list.applicant_id = applicant.id

  public  List<BlackList> getAll(){
        Session session =sessionFactory.getCurrentSession();
        ProjectionList projectionList = Projections.projectionList();
        Criteria criteria = session.createCriteria(BlackList.class);
        projectionList.add(Projections.property("applicant"));
        criteria.setProjection(projectionList);
        List res = criteria.list();
        return  res;
    }

这个方法返回了我/ id和number /但我只需要数字

2 个答案:

答案 0 :(得分:0)

  public  List<String> getAll(){
        Session session = sessionFactory.getCurrentSession();
        ProjectionList projectionList = Projections.projectionList();
        Criteria criteria = session.createCriteria(BlackList.class);
        criteria.createCriteria("applicant", "a");
        projectionList.add(Projections.property("a.number"));
        criteria.setProjection(projectionList);
        List<String> res = criteria.list();
        return  res;
    }

我需要这个......也许有人会帮忙

答案 1 :(得分:-1)

有两种方法可以解决这个问题,您可以使用hql从黑名单中选择申请人。或者您可以在申请人中添加反向联接,这样您就可以创建别名&#39;并添加一个非空的&#39;限制。