java用hibernate SQLQuery获取几列

时间:2017-03-21 15:55:37

标签: java database hibernate select sql-query-store

我正在使用SQLQuery使用hibernate从数据库中选择一些数据。 当尝试选择*它工作,但只需要几个列时它返回:无效的列名称 搜索了有关此问题的其他主题,但没有帮助; 这是我的代码:

User.java在哪里声明变量:

public class User实现Serializable {

private static final long serialVersionUID = -1798070786993154676L;
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "id_Sequence")
@Column(name = "ID", unique = true, nullable = false)
@SequenceGenerator(name = "id_Sequence", sequenceName = "ID_SEQ")

private Integer id;

@Column(name = "FIRST_NAME", unique = false, nullable = false, length = 100)
private String firstname;
@Column(name = "LAST_NAME", unique = false, nullable = false, length = 100)
private String lastname;
@Column(name = "DATE_OB", unique = false, nullable = false, length = 100)
private String birthdate;
@Column(name = "DATE_OW", unique = false, nullable = false, length = 100)
private String startdate;
@Column(name = "DEPARTMENT", unique = false, nullable = false, length = 100)
private String department;
@Column(name = "POSITION", unique = false, nullable = false, length = 100)
private String position;

//使用getter和setter

尝试选择的部分:

public static List<User> getAllUser()
{
    List<User> result = null;
    Session session = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = null;
    try {
        tx = session.beginTransaction();

        String sql = "select first_name from employee";
        SQLQuery query = session.createSQLQuery   (sql).addEntity(User.class);
        result = query.list();



    } catch (HibernateException e) {
        if (tx != null)
            tx.rollback();
        e.printStackTrace();
    } finally {
        session.close();
    }
    return result;

}

因为我猜我不需要创建单独的hibernate-mapping文件,因为它已经在User类中完成了。 请帮助找出原因。

2 个答案:

答案 0 :(得分:2)

当您使用本机查询加载数据时(因为它在JPA世界中调用),您可以在查询所有列时加载完整实体,即SELECT * FROM foo,或者您可以加载一个或多个单独的列,这会导致获得Object[]或某种特定类型(例如String)。

这里你试图只将第一个名称加载为User实体,可能希望其他字段留空。然而,这不是它的工作原理。您可以加载完整实体,也可以加载指定列值的数组。

以下内容应该有效

SQLQuery query = session.createSQLQuery(sql);
List<String> names = query.list();

答案 1 :(得分:0)

Try this one : It is working for me!!

SQLQuery query = session.createSQLQuery(sql);
query.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);

List first_names = query.list();

for (Object object : first_names) 
         {
          System.out.println("User Details are==========  " + object);  
        // or
          Map map = (Map) object;
          System.out.println("first_names : " + map.get("first_name"));
         }