1
User user = userRepository.findOne(1);
user.setName("Alex");//I want to save it
user.detache()
user.setAge(44);//I dont want to save it 

How detach and Attach user with JPA JpaRepository<User, Long>

That's a fundamental principle of JPA. You work with attached (managed) entities, and every modification made on these managed entities is automatically made persistent but in same case I want to turn off it. How to do it in clean way?

Kamil Nękanowicz
  • 6,254
  • 7
  • 34
  • 51
  • What do you actually want to do? Save only the name and not the age? – Turbut Alin Dec 06 '16 at 08:02
  • I want save only name not age and I dont want to write custom query I want to avoid boilerplate code – Kamil Nękanowicz Dec 06 '16 at 08:13
  • I am not sure I understand. You don't have the possibility *not* to set the fields you don't want updated? – Turbut Alin Dec 06 '16 at 08:17
  • Yes, every modification is immediately saved to the database. In my case I want to use it but sometimes I want to disable it. but if is not possible then I am gonna completely diable it for whole project – Kamil Nękanowicz Dec 06 '16 at 08:31
  • The modifications should only be saved when you call `JpaRepository#save` – Turbut Alin Dec 06 '16 at 08:34
  • no, data are saved immediately, after setName I see In logs SQL with update, also I checked it in database: http://stackoverflow.com/questions/13588565/spring-data-jpa-why-are-changes-to-a-returned-entity-automatically-persisted – Kamil Nękanowicz Dec 06 '16 at 08:39
  • That's a fundamental principle of JPA. You work with attached (managed) entities, and every modification made on these managed entities is automatically made persistent. – Kamil Nękanowicz Dec 06 '16 at 08:41
  • You might want to use a `@Transient` field for that. – Predrag Maric Dec 06 '16 at 08:47
  • I use @Transient, but I want to have controlon code level not annotation lvl – Kamil Nękanowicz Dec 06 '16 at 08:53
  • 1
    [Here](http://stackoverflow.com/questions/26795436/spring-jparepository-detach-and-attach-entity/26812963#26812963) is how you can add `detach()` method to your repository. – Predrag Maric Dec 06 '16 at 09:03
  • thanks, but that code is ugly I do not intend to implement this for all repositories – Kamil Nękanowicz Dec 06 '16 at 09:10
  • 1
    You can extend `JpaRepository` (say, `ExtendedJpaRepository`) and add `detach` and `merge` (equivalent to `attach`) methods to the interface. Then provide your own implementation which will be available to all repositories that extend your custom interface. See [my sample application](https://github.com/manish-in-java/spring-jpa-hibernate) for an example of creating your own custom repository implementation. – manish Dec 06 '16 at 13:14

0 Answers0