我是Hibernate的新手。我成功检索单列和完整表但是当我尝试表中的特定列时它给了我错误。 这是错误
[Ljava.lang.Object;@2c7d121c, [Ljava.lang.Object;@65aa6596, [Ljava.lang.Object;@67389cb8, [Ljava.lang.Object;@419a20a6
这是实体:MovieRatings.java
package com.hibernate.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity
@Table(name = "movie_ratings")
public class MovieRatings {
@Id
@GeneratedValue(strategy=GenerationType.IDENTITY)
@Column(name = "id")
private int id;
@Column(name = "movie_id")
private int user_id;
@Column(name = "user_id")
private int movie_id;
@Column(name = "rating")
private int rating;
public MovieRatings()
{
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUser_id() {
return user_id;
}
public void setUser_id(int user_id) {
this.user_id = user_id;
}
public int getMovie_id() {
return movie_id;
}
public void setMovie_id(int movie_id) {
this.movie_id = movie_id;
}
public int getRating() {
return rating;
}
public void setRating(int rating) {
this.rating = rating;
}
@Override
public String toString() {
return "MovieRatings [id=" + id + ", user_id=" + user_id + ", movie_id=" + movie_id + ", rating=" + rating
+ "]";
}
}
这是主要功能
package com.hibernate.getdata;
import java.util.List;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import com.hibernate.entity.MovieRatings;;
public class GetMovieInfo {
public static void main(String[] args) {
// TODO Auto-generated method stub
SessionFactory factory = new Configuration().configure().addAnnotatedClass(MovieRatings.class).buildSessionFactory();
Session session = factory.getCurrentSession();
try {
session.beginTransaction();
String hql="select E.user_id, E.rating from MovieRatings as E";
System.out.println(hql);
@SuppressWarnings({ "deprecation", "unchecked" })
List<MovieRatings> theRatings = session.createQuery(hql).list();
System.out.println(theRatings);
/*for(MovieRatings tempRatings:theRatings)
{
System.out.println(tempRatings.getUser_id());
System.out.println(tempRatings.getRating());
}*/
session.getTransaction().commit();
} catch (Exception e) {
// TODO: handle exception
}
}
}
答案 0 :(得分:2)
我成功检索单列和完整表但是什么时候 我正在尝试在表格中的特定列它给我错误。
使用Hibernate(对于JPA也是如此),当您在查询特定列中选择而不是实体本身时,list()
Query
方法将返回具有此结构的对象:{ {1}}。
List的每个元素对应一行,每个元素都是一个数组,其中包含List<Object[]>
使用的顺序中的选定值。
因此,您必须迭代列表以检索值:
select
答案 1 :(得分:0)
尝试使用此:
try {
session.beginTransaction();
String hql="select E.user_id, E.rating from MovieRatings as E";
System.out.println(hql);
@SuppressWarnings({ "deprecation", "unchecked" })
Query query = session.createSQLQuery(hql);
query.setResultTransformer(Transformers.aliasToBean(GetMovieInfo.class));
List<MovieRatings> theRatings = query.list();
System.out.println(theRatings);
session.getTransaction().commit();
} catch (Exception e) {
// TODO: handle exception
}