使用HQL在Hibernate中查询

时间:2016-06-06 22:47:14

标签: java hibernate jpa hql jpql

我已经尝试了很长时间用HQL进行简单的查询,但它总是返回我

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: 
unexpected token: on near line 1, column 72 
[select p, g.Description from entity.TB_Person p inner join TB_Gender g 
 on p.IdGender = g.Id where p.Username= :Username]

以下是查询的代码:

String jpql = "select p, g.Description "
            + "from TB_Person p inner join TB_Gender g "
            + "on p.IdGender = g.Id where p.Username= :Username";
Query query = manager.createQuery(jpql);
query.setParameter("Username", credentials.getUsername());
List l = (List)query.getResultList();

以下是我的实体:

package entity;

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

import org.hibernate.annotations.ForeignKey;

@Entity
@Table(name="TB_Person")
public class TB_Person {

@Id
private String CPF;

private String Name;

private Date Birthday; 

private String PhotoPath;

@ForeignKey(name = "fk_TB_Person_TB_User1")
private String Username;

@ForeignKey(name = "fk_person_gender")
private int IdGender;
public String getUsername() {
    return Username;
}

public void setUsername(String username) {
    Username = username;
}

public String getCPF() {
    return CPF;
}

public void setCPF(String cPF) {
    CPF = cPF;
}

public String getName() {
    return Name;
}

public void setName(String name) {
    Name = name;
}

public Date getBirthday() {
    return Birthday;
}

public void setBirthday(Date birthday) {
    Birthday = birthday;
}

public String getPhotoPath() {
    return PhotoPath;
}

public void setPhotoPath(String photoPath) {
    PhotoPath = photoPath;
}
}

package entity;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="TB_Gender")
public class TB_Gender {

    @Id
    private int Id;

    private String Description;

    private String Abbreviation;

    public String getDescription() {
        return Description;
    }

    public void setDescription(String description) {
        Description = description;
    }

    public String getAbbreviation() {
        return Abbreviation;
    }

    public void setAbbreviation(String abbreviation) {
        Abbreviation = abbreviation;
    }

    public int getId() {
        return Id;
    }

}

我做错了什么?

1 个答案:

答案 0 :(得分:1)

我认为你没有正确建立实体之间的关系。

@ForeignKey代表constraint,但不代表java实体之间的关系。

在Hibernate 5.1版本之前,如果您之前没有使用@OneToOne, @OneToMany, @ManyToOne之类的注释建立它们之间的关系,则不能在JPQL中使用实体之间的连接,...更多info关于此主题和如何加入不相关的实体。

要执行查询,您必须在实体中定义类似的内容

 @Entity
 @Table(name="TB_Person")
 public class TB_Person {

     @Id
     private String CPF;

     @OneToOne
     @JoinColumn(name = "user_id") // <- table column constrained by fk_TB_Person_TB_User1
     private TB_User user;

     ...
 }