Hibernate标准,两个实体

时间:2014-08-26 16:08:34

标签: java hibernate criteria

假设我有疑问:

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

我想使用Criteria工具对其进行转换,但不知道如何获取

提前致谢

1 个答案:

答案 0 :(得分:0)

以下是有关如何使用Criteria获取结果的代码:

<强> 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

@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
}

将一些实体保存到数据库的代码:

    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);

现在使用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());
        }
    }

输出将是:

Entity eo1
->two
->one