Calendar calendar not saved as desired

I try to roll a calendar for a week and save it using Hibernate. Rolling work (verified using println), but the data that is stored 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> implements GenericDao<T, ID> class has the following method:

 @Override public void save(T instance) { getSessionFactory().getCurrentSession().save(instance); } 

public interface LoanDao extends GenericDao<Loan, Long> does not have a save method implementation.

What is wrong in my code?

0
source share
2 answers

You set the same calendar instance in dueDate and outDate! When you set outDate, the Calendar is, for example, 2012-07-02, and then you update the calendar value to 2012-07-09 and save it in dueDate.

The problem is that the same calendar instance is also used for outDate, so when Hibernate saves your object, it saves it all the way to the right, since both attributes have the same Calendar object.

Cloning the calendar before updating it, and your problem is resolved.

And: the date stored in the database is both the dueDate calendar and not the original calendar when you sent messages.

+1
source

roll does not change large fields ( see JavaDoc )

using

 outDate.add(Calendar.WEEK_OF_YEAR, 1); 

instead

0
source

All Articles