简体   繁体   English

休眠条件,两个实体

[英]Hibernate criteria, two entities

Lets say I have a query : 可以说我有一个查询:

SELECT one FROM EntityOne one, EntityTwo two WHERE one.id = two.otherId AND two.someValue = 2

I'd like to transform it using Criteria tools but don't know to how fetch 我想使用Criteria工具对其进行转换,但不知道如何获取

thanks in advance 提前致谢

Here is the code on how you can get results using Criteria : 这是关于如何使用Criteria获得结果的代码:

EntityOne.java EntityOne.java

@Entity
public class EntityOne {
    @Id
    @GeneratedValue
    private int id;
    private String name;
    @OneToMany(mappedBy = "entity", cascade=CascadeType.ALL)
    private Set<EntityTwo> entities = new HashSet<EntityTwo>();
    public EntityOne(String name) {
        this.name = name;
    }
    public void addEntity(EntityTwo entity) {
        this.entities.add(entity);
    }
    // Default constructor, setters & getters
}

EntityTwo.java EntityTwo.java

@Entity
public class EntityTwo {
    @Id
    @GeneratedValue
    int id;
    String name;
    @ManyToOne
    @JoinColumn(name = "entity_one_id")
    private EntityOne entity;
    public EntityTwo(String name) {
        this.name = name;
    }
    // Default constructor, setters & getters
}

Code to save some entities to database: 将某些实体保存到数据库的代码:

    EntityOne eo1 = new EntityOne("Entity eo1");
    EntityTwo et1 = new EntityTwo("one");
    EntityTwo et2 = new EntityTwo("two");

    eo1.addEntity(et1);
    eo1.addEntity(et2);
    et1.setEntity(eo1);
    et2.setEntity(eo1);

    EntityOne eo2 = new EntityOne("Entity eo2");
    EntityTwo et3 = new EntityTwo("three");
    EntityTwo et4 = new EntityTwo("four");

    eo2.addEntity(et3);
    eo2.addEntity(et4);
    et3.setEntity(eo2);
    et3.setEntity(eo2);

    session.save(eo1);
    session.save(eo2);

Now the code for getting records using Criteria : 现在,使用Criteria获取记录的代码:

    Criteria criteria = session.createCriteria(EntityOne.class, "e1");
    criteria.createAlias("e1.entities", "e2");
    criteria.add(Restrictions.eq("e2.name", "two"));

    List<EntityOne> entityList = criteria.list();
    for (EntityOne entityOne : entityList) {
        System.out.println(entityOne.getName());
        for (EntityTwo entity : entityOne.getEntities()) {
            System.out.println("->" + entity.getName());
        }
    }

Output will be: 输出将是:

Entity eo1
->two
->one

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM