java - 从数据库中检索 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 对象列表
解决方案
更改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"
注意:
- 需要定义适当的构造函数。
- 需要使用完全限定名
推荐阅读
- laravel - 我在 Laravel 和 vuejs 中的应用程序,当我部署到 VPS 时,在 vue 组件中 API 调用会转到 localhost 而不是我的服务器 IP 地址
- java - 启动应用程序后出错:org.springframework.boot.autoconfigure.security.servlet.UserDetailsServiceAutoConfiguration 上的错误处理条件
- django - 反向关系的Django verbose_name
- javascript - ScrollMagic 循环 - 场景持续时间与作为场景一部分的视频持续时间相同
- java - 如何在 java.util.ResourceBundle 中获取特定键并设置其值?
- machine-learning - 掩码和图像在 UNET 中如何相互配合?
- node.js - 将 pm2 与 npm run 一起使用
- c++ - 在 C++ 中使用字符串函数时,使用 substr() 函数终止
- javascript - Angular-6 显示和隐藏下拉选择选项未显示正确的数据
- android - Android 库矢量转换为默认混淆的 png 和 Kotlin 文件