0
house_id 및 월/년을 기반으로 데이터베이스에서 개체를 검색하고 싶습니다. SQLite 데이터베이스에 전체 날짜를 저장하고 있습니다. 매월 한 가지 결과가 있어야합니다. 내 코드는 다음과 같습니다.기준을 사용하여 기간을 기준으로 데이터베이스에서 개체를 가져 옵니까?
기준을 특정 월 및 연도로 찾으려면 어떻게해야합니까?
나는 모든 가능한 비용 목록을 선택한 다음 날짜를 비교하는 각 개체를 거치지 않고 특정 월과 연도를 검색 할 수 있도록 내 Criteria
을 변경하는 방법을 실제로 찾고 있습니다.
UPDATE : 프랑수아 LEPORCQ의 답변에 따라 근무 코드 : 나는 수정 날짜 (LocalDate.now()
)를 통과 한 이미 이번 달 기존의 모든 레코드가있는 경우 확인 된 lookUpDate
매개 변수로
public static Costs getCosts(Date lookUpDate, House house) {
Costs costs = null;
Calendar myCalendar = Calendar.getInstance();
myCalendar.setTime(lookUpDate);
myCalendar.set(Calendar.DAY_OF_MONTH, 1);
Date monthStart = new java.sql.Date(myCalendar.getTimeInMillis());
myCalendar.add(Calendar.DAY_OF_MONTH,
(myCalendar.getMaximum(Calendar.DAY_OF_MONTH) - myCalendar.get(Calendar.DAY_OF_MONTH)));
Date monthEnd = new java.sql.Date(myCalendar.getTimeInMillis());
System.out.println("Start: " + monthStart);
System.out.println("End: " + monthEnd);
Session sess = mainApp.getSessionFactory().openSession();
Transaction tx = null;
try {
tx = sess.beginTransaction();
// create criteria builder
CriteriaBuilder builder = sess.getCriteriaBuilder();
// create criteria
CriteriaQuery<Costs> query = builder.createQuery(Costs.class);
// specify criteria root
Root<Costs> root = query.from(Costs.class);
query.select(root)
.where(builder.and(builder.equal(root.get("house"), house),
builder.greaterThanOrEqualTo(root.get("date"), monthStart),
builder.lessThanOrEqualTo(root.get("date"), monthEnd)));
List<Costs> costsList = sess.createQuery(query).getResultList();
if(!costsList.isEmpty()){
costs = costsList.get(0);
}
tx.commit();
} catch (Exception e) {
if (tx != null)
tx.rollback();
System.out.println(e);
throw e;
} finally {
sess.close();
}
return costs;
. 의사 코드
lookupStartDate = 01/month/year
lookUpEndDate = lookupStartDate + 1 month
where date >= lookupStartDate and date < lookUpEndDate
사용하는 java.util.Calendar에서
같은 것을 시도 시작일 1 개월 추가, 당신은 값을 원하는 여기서 날짜 필드는 그 해의 첫 번째 날보다 크고 다음 해의 첫날보다 작습니다. –
나는 그것을 이해한다. 그러나 나는 그것을 단지 표준에 어떻게 구현할 지 모른다. – Alyona