Hayi
Hayi

Reputation: 6236

Object get updated in database automatically

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

Answers (1)

Rafik BELDI
Rafik BELDI

Reputation: 4158

There are many states of an Object :

  • Persistent: a persistent instance has a representation in the database and an identifier value and it is associated with a Hibernate Session.
  • Detached : a detached instance is an object that has been persistent, but its Session has been closed.
  • transient: an object is transient if it has just been instantiated using the new operator, and it is not associated with a Hibernate Session.

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

Related Questions