Hibernate在@ManyToOne的查询中返回null hql

时间:2016-06-22 18:04:54

标签: java mysql hibernate hibernate-mapping

首先我道歉,如果我的问题看起来有点业余,但我对hibernate / jpa和mysql的了解有些限制。

好吧,我有以下实体:

用户实体

@Entity
@Table(name = "user")
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id_user")
    private Long idUser;

    @Column(nullable = false)
    private String name;

    @Column(nullable = false)
    private String email;

    @ManyToOne(optional = true, fetch = FetchType.EAGER)
    @JoinColumn(name = "level", referencedColumnName = "id_level", nullable = true)
    private Level level;

    @Transient
    private Long totalLikes;
}

从那里开始,我尝试执行以下mysql查询:

public User findUserByEmail(String email) {
        Session session = HibernateUtil.getSessionFactory().openSession();
        User user = null;

        String hql = "SELECT "
                   + "u.idUser as idUser, "
                   + "u.nome as nome, "
                   + "u.level as level, "
                   + "(SELECT count(*) FROM UserLikes likes WHERE likes.user = u.idUser) as totalLikes "
            + "FROM User u WHERE u.email = :email";
        try {
            Query query = session.createQuery(hql);
            query.setString("email", email);
            query.setResultTransformer(Transformers.aliasToBean(User.class));
            user = (Usuario) query.uniqueResult();

        } catch (RuntimeException ex) {
            throw ex;
        } finally {
            session.close();
        }

        return user;
    }

上面的代码正常返回User,但是当要在数据库中搜索的User没有在字段级别设置值时返回null。也就是说,如果我没有错,那么hibernate会执行内部联接用户/级别而不是左联接,从而返回null。

有没有人知道怎么解决这个问题?

1 个答案:

答案 0 :(得分:3)

我认为你需要使用它。

@ManyToOne //simple
@JoinColumn(nullable = true) simple

并在您的查询中也使用简单。

FROM User u WHERE u.email = :email

我在类似的项目中使用它并且工作。

好工作的人。