Reputation: 6236
I'm using Spring data jpa
and spring mvc
And i noticed that my object contact
is updated in database automatically.
Here's My Code :
@Transactional
@Controller
public class ContactController {
@RequestMapping(value="/update_contact ")
public @ResponseBody
String update_contact (...) {
...
Contact contact = contactrespository.findOne(idcontact);
contact.setName(...);
...
}
}
And without executing contactrespository.save(idcontact);
My contact
has been changed when i checked the database !
Can you explain me Why ?
Upvotes: 1
Views: 141
Reputation: 4158
There are many states of an Object :
In this context The changes are committed to contact because it is a persistent object that has been modified within a transaction because your controller is annotated with @Transactional
so it's associated with a Hibernate Session.
It is not a good practice to annotate a Controller
with Transactional
annotation, it is better used on the service Layer where we invoke the repository
not in the controller layer
@Controller
public class MyController{
@Autowired
private MyService service;
@RequestMapping ....
public Contact findContact(String name, ....){
Contact contact = service.get(...);
// other logic
}
}
@Service
public class MyService{
@Autowired
private MyRepository repository;
@Transactional(propagation=Propagation.SUPPORTS)
public Contact get(long id){
// better throw a notFuondException in here
return repository.findOne(id);
}
//same for other method like create and update with @Transactional REQUIRED NEW or REQUIRED propagation
}
Upvotes: 3