首页 > 解决方案 > 从数据库中检索 java 对象列表而不是请求的对象列表

问题描述

我在尝试从我的数据库中提取数据请求为特定对象类型时遇到问题。我创建了查询,它正在获取 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
    @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 对象列表

标签: javahibernatehql

解决方案


更改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. 需要使用完全限定名

推荐阅读