我有一个包含DeviceData
列的表Username, Watts, and CreatedOn
,其中CreatedOn
的类型为Datetime (yyyy-MM-dd HH:mm:ss)
。所有三列都形成一个复合键,并且是Hibernate中的@Embeddable
类。
@Embeddable
public class TimeSeriesPowerPK implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private String username;
private Integer watts;
private String dateTime;
public TimeSeriesPowerPK(String username, Integer watts, String dateTime) {
this.username = username;
this.watts = watts;
this.dateTime = dateTime;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Integer getWatts() {
return watts;
}
public void setWatts(Integer watts) {
this.watts = watts;
}
public String getDateTime() {
return dateTime;
}
public void setDateTime(String dateTime) {
this.dateTime = dateTime;
}
}
如何在下面显示的DAO中编写查询以检索其creatednn在当前时间与用户输入的小时数或分钟数之间的行的所有Watts值?
public List<Integer> getPowerUsageForUser(String minutes) {
List<Integer> powerUsedList = sessionFactory.getCurrentSession().createQuery("***query***").list();
return powerUsedList;
}
非常感谢任何帮助!提前谢谢!
编辑:更新了问题,以检索所有选定行的特定列值。
答案 0 :(得分:3)
使用以下代码
public List<TimeSeriesPowerPK> getPowerUsageForUser(String minutes) {
Query query = sessionFactory.getCurrentSession().createQuery("From TimeSeriesPowerPK where dateTime <=:param1 AND dateTime >= :parma2 ");
query.setParameter("param1",currentDateObject);
query.setParameter("param2",userEnteredDateObject);
List<TimeSeriesPowerPK> powerUsedList=query.list();
return powerUsedList;
}
请注意,必须将类的dateTime映射到数据库表的createdOn列。 希望它有所帮助。
答案 1 :(得分:1)
您可以使用标准
public List<TimeSeriesPowerPK> getPowerUsageForUser() {
Criteria powerCriteria= session.createCriteria(TimeSeriesPowerPK.class);
powerCriteria.setResultTransformer(CriteriaSpecification.DISTINCT_ROOT_ENTITY);
powerCriteria.add(Restrictions.le("dateTime",currentDateObject));
powerCriteria.add(Restrictions.ge("dateTime",userEnteredDateObject));
return powerCriteria.list();
}
答案 2 :(得分:1)
试试这个
Query qrFetch=ursession.createQuery("from TimeSeriesPowerPK where dateTime between :start_date and :end_date");
qrFetch.setParameter("start_date",currentDateObject);
qrFetch.setParameter("end_date",userEnteredDateObject);
List<TimeSeriesPowerPK> timeSeriesPowerPKList=qrFetch.list();