问题描述
我试图每周滚动一个日历,并使用Hibernate持久化。滚动工作(使用 println 进行测试),但保存在数据库中的数据似乎是原始日历。
I am trying to roll a calendar by a week and persist it using Hibernate. The rolling work (tested using println) but the data being saved in the database seems to be the original calendar.
Calendar outDate = Calendar.getInstance();
System.out.println(outDate.getTime());
Loan loan = new Loan();
loan.setCatalogueEntry(catalogueEntry);
loan.setOutDate(outDate);
loan.setNoOfRenewals(0);
outDate.add(Calendar.WEEK_OF_YEAR, 1); //Rolling the calendar to a week further
System.out.println(outDate.getTime());
loan.setDueDate(outDate);
loan.setUser(user);
loanDao.save(loan);
catalogueEntryDao.update(catalogueEntry);
GenericHibernateDao< T,ID extends Serializable>实现GenericDao< T,ID>
类有以下方法:
@Override
public void save(T instance) {
getSessionFactory().getCurrentSession().save(instance);
}
public interface LoanDao extends GenericDao< Loan,Long&
public interface LoanDao extends GenericDao<Loan, Long>
doesn't have any implementation of save method.
我的代码有什么问题?
推荐答案
您在dueDate和outDate中设置相同的日历实例!当您设置outDate时,日历是例如。 2012-07-02,然后将日历值更新为2012-07-09,并将其存储在dueDate中。
You are setting the same Calendar instance in dueDate and outDate! When you set the outDate, the Calendar is e.g. the 2012-07-02, and then you update the calendar value to 2012-07-09, and store it in dueDate.
问题是,同样的日历实例也用于outDate,所以当Hibernate持久化对象时,它会完全正确地存储它,因为这两个属性共享相同的Calendar对象。
The problem is, the same calendar instance is also used for outDate, so when Hibernate persists your object, it stores it completely right, since both attributes share the same Calendar object.
在更新日历之前克隆日历,您的问题已解决。
Clone the calendar before updating it, and your problem is solved.
AND:数据库都是dueDate日历,而不是您发布的原始日历!
AND: The date stored in the database is both times the dueDate calendar, not the original calendar as you posted!
这篇关于滚动日历不按需保留的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!