jpql附近的错误

时间:2017-12-22 12:39:34

标签: java postgresql hibernate jpql

您好我正在学习JPQL,我正在使用以下代码选择DTO

class User{
private int id;
private String name;

@oneToOne
private Service service;

}
Class Service{
private int id
private String serviceName;
}

class UserServiceDTO{

private String userName;
private String serviceName;

public UserServiceDTO(String userName,String serviceName){
this.userName=userName;
this.serviceName-serviceName;
}
}

public UserServiceDTO findByName(String userName){
TypedQuery<UserServiceDTO> query= em.createQuery("SELECT new UserServiceDTO(u.name, s.userName) FROM User u LEFT OUTER JOIN Service s where 
 u.name LIKE :userName");
 UserServiceDTO userService=query.setParameter("userName",userName).getSingleReslut();
}

我正在关注stacktrace:

Could not extract ResultSet
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "where"
  Position: 260
    at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2270)
    at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1998)
    at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:570)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:420)
    at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:305)
    at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:60)
    ... 43 more

我正在使用PostgreSQL 任何洞察都会有所帮助。请帮助我,我错了可能请指导我

2 个答案:

答案 0 :(得分:0)

该JPQL的正确语法是

SELECT new UserServiceDTO(u.name, s.serviceName) FROM User u LEFT OUTER JOIN u.service s WHERE u.name LIKE :userName 

连接是通过实体图完成的,因此您只需指定要访问的实体字段。

答案 1 :(得分:0)

无需显式连接。您还可以编写:SELECT new UserServiceDTO(u.name,u.service.serviceName)FROM User u其中u.name LIKE:userName;您可能需要指定连接列映射usimg @JoinColumn annotation