JPA查询连接错误:org.hibernate.hql.internal.ast.QuerySyntaxException:连接所需的路径

时间:2017-03-28 14:17:31

标签: java hibernate jpa join

我正在尝试加入以下JPA查询,但收到以下错误:

  

org.hibernate.hql.internal.ast.QuerySyntaxException:期望的路径   加入! [来自com.crm.entity.User用户加入获取角色的角色   role.user_id = user.id其中user.deleted = false和user.enabled =   true和user.username =:username]

以下是实施:

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.transaction.Transactional;

import org.springframework.stereotype.Repository;

import com.crm.entity.User;

@Transactional
@Repository
public class UserJpaDaoImpl implements UserJpaDaoCustom {

    @PersistenceContext
    private EntityManager em;

    @Override
    public User getUser(String username) {
        Query query = em.createQuery("from User user "
                                    + "join fetch Role role on role.userId = user.id "
                                    + "where user.deleted = false "
                                    + "and user.enabled = true "
                                    + "and user.username = :username", User.class);
        query.setParameter("username", username);
        return (User)query.getSingleResult();
    }

}

User实体:

@Entity
@Table(name = "user")
public class User extends BaseEntity implements UserDetails, Visible {

    private static final long serialVersionUID = 1L;

    @Column(name = "username")
    private String username;

    @Column(name = "password")
    private String password;

    /* Spring Security fields*/
    @OneToMany
    @JoinColumn(name = "user_id")
    private List<Role> roles;
...

Role实体:

@Entity
@Table(name = "role")
public class Role implements GrantedAuthority, Identifiable {

    private static final long serialVersionUID = 1L;

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

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

    @Column(name = "user_id")
    private Integer userId;
...

我的查询中的联接有什么问题?

1 个答案:

答案 0 :(得分:2)

它是HQL而不是SQL:

   Query query = em.createQuery("from User user "
                                + "join fetch user.role "
                                + "where user.deleted = false "
                                + "and user.enabled = true "
                                + "and user.username = :username", User.class);

你必须处理不在表上的对象结构