休眠-获取日期集中存在一年的记录

时间:2018-10-23 11:45:05

标签: spring hibernate date collections set

模型

@Entity
@Table(name = "calendar", schema = "master")
public class Calendar implements Serializable {

    private static final long serialVersionUID = -8537804959644622294L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "calender_id")
    private long calendarId;
    @ManyToOne(targetEntity = SittingLocation.class, cascade = CascadeType.MERGE)
    @JoinColumn(name = "sitting_location_id", referencedColumnName = "sitting_location_id")
    private SittingLocation sittingLocation;
    @ElementCollection(fetch = FetchType.EAGER)
    @CollectionTable(name = "calender_date", schema = "master", joinColumns = @JoinColumn(name = "calender_id"))
    @Temporal(TemporalType.DATE)
    @DateTimeFormat(pattern = "dd-MM-yyyy")
    @Column(name = "calender_date")
    private Set<Date> dates = new LinkedHashSet<>();

    public Calendar() {
        this.calendarId = 0;
        this.sittingLocation = null;
        this.dates = null;
    }
\\getter and setter
}

DAO

    @SuppressWarnings("unchecked")
        @Override
        public List<Calendar> listCalendarByYear(SittingLocation sittingLocation,int year) {
            try {
                Query query = sessionFactory.getCurrentSession()
                        .createQuery("FROM Calendar c WHERE c.sittingLocation=:sittingLocation AND :year in elements(YEAR(c.dates))");
                query.setParameter("sittingLocation", sittingLocation);
                query.setParameter("year", year);
                return query.getResultList();
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        }

我被这段代码困了一个星期。 我在日期集中提供了可以通过检查给定年份来获取记录的解决方案。 查询“ FROM日历c WHERE c.sittingLocation =:sittingLocation AND:元素中的年份(YEAR(c.dates))”的任何替代方法。

请帮助。

提前谢谢。

0 个答案:

没有答案