如何在Spring中使用Hibernate从SubQuery中的一对一关系中获取数据

时间:2013-03-07 14:20:00

标签: mysql spring hibernate

我有两个表hesk_usersuser,如下。

@Entity @table(名称= “hesk_users”) 公共类UserHesk {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column
private int id;

@OneToOne
@JoinColumn(name="user_id")
private User user;

    set.... get..

}

@Entity @table(名称= “用户”) public class User实现Serializable {

@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;

@NotEmpty
@Column
private String firstname;

     @OneToOne(mappedBy="user")
private UserHesk userHesk; 

    set ... get ... 

}

我有hibernate查询,但它不起作用..

            DetachedCriteria detachedCriteria=DetachedCriteria.forClass(UserHesk.class)
    .setProjection(Projections.property("user_id"));

    Criteria criteria=sessionFactory.getCurrentSession().createCriteria(User.class);
    criteria.add(Property.forName("id").notIn(detachedCriteria));
    User user=(User)criteria.list().get(0);
    System.out.println(user.getFirstname());
    System.out.println("Subquery Size "+criteria.list().size());

user_id提交的错误。由于关系而无法获得。

1 个答案:

答案 0 :(得分:0)

HQL和条件查询始终使用实体类和属性。永远不会是基础表和列的名称。 UserHesk类没有任何user_id属性。它有user属性。

所以代码应该是

DetachedCriteria detachedCriteria = 
    DetachedCriteria.forClass(UserHesk.class)
                    .setProjection(Projections.property("user.id"));

甚至

DetachedCriteria detachedCriteria = 
    DetachedCriteria.forClass(UserHesk.class)
                    .createAlias("user", "u")
                    .setProjection(Projections.property("u.id"));