我试图从表访问者Postgresql数据库中获取行。但我不需要所有列,但目前执行自定义查询,它不起作用。
EntityManager em = emf.createEntityManager();
Query query = em.createQuery("SELECT visitor_id, first_name, last_name, email, company, country_id FROM Visitor", Visitor.class);
List<Visitor> result = query.getResultList();
return result;
错误控制台显示我:
org.hibernate.exception.SQLGrammarException:无法执行查询 org.postgresql.util.PSQLException:找不到列名城市 在此ResultSet中。
SELECT visitor_id, city, company, email, email_confirmed, first_name,
identification_number, identification_other, image, is_active,
job_title, last_name, mobile_number, password, phone_number,
province, country_id, created_by, identification_type_id
FROM visitor;
所有栏目都在那里。所以我所做的是调用函数来获取所有行并将其设置在另一个名为bindRegisterToDashboard();的函数中。它的函数只从表中设置六列到对象visitorDashBoardViewModel,以便在视图上显示它。
//service file code
for (Visitor item: getVisitors()) {
visitorDashBoardViewModel.add(bindRegisterToDashboard(item);
}
return visitorDashBoardViewModel;
访客模特:
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long visitorId;
private String identificationOther;
private long identificationNumber;
private String firstName;
private String lastName;
private String email;
private boolean emailConfirmed;
private String phoneNumber;
private String mobileNumber;
private String password;
private String province;
private String city;
private String company;
private String jobTitle;
private Boolean isActive;
private byte[] image;
@ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinColumn(name="identification_type_id")
private IdentificationType identificationType;
@ManyToOne(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.LAZY)
@JoinColumn(name = "country_id", nullable = false)
private Country country= new Country();
答案 0 :(得分:0)
您的查询未返回访问者的实例。它返回对象数组。所以它不应该是TypedQuery<Visitor>
,而只是Query
。
Query query = em.createQuery("SELECT v.visitorId, v.firstName, v.lastName, v.email, v.company, v.country.id FROM Visitor v");
List<Object[]> rows = query.getResultList();
// now, in each Object[], visitor_id is at index 0, first_name at index 1, etc.
另外,请尊重Java命名约定:id,firstName,lastName等
如果您希望查询返回Visitor的实例,则应为
TypedQuery query = em.createQuery("SELECT v from Visitor v");
List<Visitor> visitors = query.getResultList();