2

I have the following problem:

I'm using Spring MVC 4.0.5 with Hibernate 4.3.5 and I'm trying to create a Restfull Web application. The problem is that I want to exclude some fields from getting serialized as JSON, depending on the method called in the controller using aspects.

My problem now is that Hiberate does not commit the transaction immideatly after it returns from a method but just before serializing.

Controller.java

public class LoginController {
    /*
     *  Autowire all the Services and stuff..
     */
    @RemoveAttribues({"fieldA","fieldB"})
    @RequestMapping{....}
    public ResponseEntity login(@RequestBody user) {
        User updatedUser = userService.loginTheUser(user);
        return new ResponseEntity<>(updatedUser,HttpStatus.OK);
    }

}

Service.java

public class UserService {
    @Transactional
    public User loginUser(User user) {
        user.setLoginToken("some generated token");
        return userDao.update(user); //userDao just calls entityManager.merge(..)
    }
}

The advice of the aspect does the following:

for every String find the corresponding setter and set the field to null

This is done, like I said, to avoid serialization of data (for which Jackson 2 is used)

The problem now is that only after the advice has finished the transaction is commited. Is there anything I can do to tell hibernate to commit immediatly or do I have to dig deeper and start handling the transactions myself (which I would like to avoid)?

EDIT: I also have autocommit turned on

<prop key="hibernate.connection.autocommit">true</prop>

I think the problem lies in the fact that I use lazy loading (because each user may have a huge laod of other enities attached to him), so the transaction is not commited until I try to serialze the object.

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
wastl
  • 2,643
  • 14
  • 27

1 Answers1

5

Don't set auto-commit to true. It's a terrible mistake.

I think you need a UserService interface and a UserServiceImpl for the interface implementation. Whatever you now have in the UserService class must be migrated to UserServiceImpl instead.

This can ensure that the @Transactions are applied even for JDK dynamic proxies and not just for CGLIB runtime proxies.

If you are using Open-Session-in-View anti-patterns, you need to let it go and use session-per-request instead. It's much more scalable and it forces you to handle optimum queries sin your data layer.

Using JDBC Transaction Management and the default session-close-on-request pattern you should be fine with this issue.

Vlad Mihalcea
  • 142,745
  • 71
  • 566
  • 911
  • Thanks for your answer. I did have PersistenceContext.EXTENDED turned on and it did solve my problem turning it off. – wastl Nov 18 '14 at 12:05