0

I have a Spring MVC web-app, where this back-end has all RESTful web-services, so we have an entity.jar, a dao.jar, and services.jar, and web-services.war.

In the DAO layer, I've had this discussion with my boss before that when we save or update, we want to have an object returned that is managed and can have lazy-loading done on it.

We do have a Postgres SQL database and the primary key is a long, and is set by a sequence in Postgres.

So, I have the following two methods:

@Override
public MyEntity create(MyEntity myObject)
{
    this.sessionFactory.getCurrentSession().save(myObject);
    this.sessionFactory.getCurrentSession().flush();
    this.sessionFactory.getCurrentSession().refresh(myObject);
    return myObject;
}

@Override
public MyEntity update(MyEntity myObject)
{
    this.sessionFactory.getCurrentSession().update(myObject);
    this.sessionFactory.getCurrentSession().flush();
    this.sessionFactory.getCurrentSession().refresh(myObject);
    return myObject;
}

My boss is very technical, and has looked up these methods himself to see what they all do. He thinks we don't need the flush and refresh. But all my unit tests show these two methods have always worked well.

So, I ask you is there anything wrong with the way I am using these two methods? These would be called from any business services (services.jar). The business services are obviously where the transaction and session begin.

Thanks!

tjholmes66
  • 1,850
  • 4
  • 37
  • 73

1 Answers1

2

Sometimes the Session will execute the SQL statements needed to synchronize the JDBC connection's state with the state of objects held in memory. This process, called flush, occurs by default at the following points:

1.before some query executions

2.from org.hibernate.Transaction.commit()

3.from Session.flush()

This means flush() will be called at the end of your transaction. Also, if your first-level cache has not been used not too much, then there not need to call flush().

refresh() method is useful when database triggers are used to initialize some of the properties of the object, i.e. to re-load an object and all its collections. So if you're using refresh() before commit() all your manual changes will be gone.

This and this also would be helpful.

Hibernate reference

Community
  • 1
  • 1
Pallav Jha
  • 3,409
  • 3
  • 29
  • 52