从数据库中检索Java对象列表而不是请求的对象列表

时间:2018-08-24 17:53:40

标签: java hibernate hql

我在尝试从数据库中提取数据以请求使用特定对象类型时遇到问题。我创建了查询,该查询正在获取Java Object类型的对象,而不是我需要的类型。这是我的DAO课:

import com.jackowiak.Domain.TurbinesData;
import com.jackowiak.Model.TurbineDataCSVReader;
import com.jackowiak.Utils.HibernateUtil;
import org.hibernate.Session;
import org.hibernate.query.Query;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import java.util.List;

public class TurbinesDaoBean {
    private static final Logger LOG = LoggerFactory.getLogger(TurbinesDaoBean.class);

    public List<TurbinesData> getTurbineDataFromDB(String turbineName) {

        LOG.info("Initializating DB connection to get turbine data");
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();

        Query query = session.createQuery("select windSpeed, turbinePower from TurbinesData where turbineName = :turbineName");
        query.setParameter("turbineName", turbineName);

        session.getTransaction().commit();
        List<TurbinesData> results = query.list();

        LOG.debug("Data for turbine " + turbineName + " collected successfully");
        return results;


    }
}

这是我的Entity类:

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

        @Id
        @GeneratedValue(strategy = GenerationType.IDENTITY)
        @Column(name = "ID", unique = true, nullable = false)
        protected long id;

        @Column(nullable = false, length = 50, name = "Nazwa_turbiny")
        protected String turbineName;

        @Column(nullable = false, length = 20, name = "V_wiatru")
        protected Double windSpeed;

        @Column(nullable = false, length = 20, name = "Moc_turbiny")
        protected Double turbinePower;

        public TurbinesData() {
        }

        public TurbinesData(Double windSpeed, Double turbinePower) {
            this.windSpeed = windSpeed;
            this.turbinePower = turbinePower;
        }

        public TurbinesData(String turbineName, Double windSpeed, Double turbinePower) {
            this.turbineName = turbineName;
            this.windSpeed = windSpeed;
            this.turbinePower = turbinePower;
        } 
// getters and setters
} 

我想在执行查询后接收TurbinesData对象的列表

2 个答案:

答案 0 :(得分:1)

jpql更改为:

"FROM TurbinesData td WHERE td.turbineName = :turbineName"

然后使用TypedQuery

编辑: 根据您的评论,您只想检索两个字段。您需要这样做:

"SELECT NEW package.to.TurbinesData(td.windSpeed, td.turbinePower) FROM TurbinesData td WHERE td.turbineName = :turbineName"

注意

  1. 需要定义适当的构造函数。
  2. 需要使用完全限定的名称

答案 1 :(得分:0)

您可以将List<Object>投射到List<custom class>

就像。

  

return (List<T>) query.list();

希望有帮助。