JPA 查询联接错误:org.hibernate.hql.internal.ast.QuerySyntaxExcepti



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

org.hibernate.hql.internal.ast.QuerySyntaxException: 预期的路径 加入![来自com.crm.entity.User user join fetch Role role on role.user_id = user.id 其中 user.delete = 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;
...

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

它是

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

你必须处理对象结构而不是表。

最新更新