title: JPA EntityManager : save objects only when explicitly requested
body: <p>I'm fairly new to Hibernate and JPA, and am currently working on an application that uses it through JPA's EntityManager.</p>
  
  <p>When looking at some basic hibernate tutorials using Hibernate session, I see that I can do : </p>
  
  <pre><code>val session = HibernateUtil.getSessionFactory().getCurrentSession()
  session.beginTransaction()
  val coordinates = session.find(Coordinates::class.java, "12345")
  coordinates.longitude = 0.0
  session.save(coordinates)
  session.getTransaction().commit()
  </code></pre>
  
  <p>When using Entitymanager, it's done this way : </p>
  
  <pre><code>val em = emFactory.createEntityManager()
  em.transaction.begin()
  val coordinates = em.find(Coordinates::class.java, "12345")
  coordinates.longitude = 0.0
  em.transaction.commit()
  </code></pre>
  
  <p>The main difference here is that using EntityManager, I don't have to explicitly make a call to a <code>save</code> function to actually update the object, which will be flushed eventually during commit. Of course, I coul do something like </p>
  
  <pre><code>if(obj.id == null) {
      return em.merge()
  } else {
      val saved = em.persist(obj)
      return saved
  }
  </code></pre>
  
  <p>But what's the point for already existing objects if they get saved anyway, no matter if I call this or not ?</p>
  
  <p>Surprisingly, the <a href="https://thorben-janssen.com/implementing-the-repository-pattern-with-jpa-and-hibernate/" rel="nofollow noreferrer">examples</a> found around here seem to rely on a save method as well.</p>
  
  <p>My question is : is there a way to configure EntityManager to update the objects only when requested specifically (i.e. mimick session behavior) ? Or do I have to use Session to achieve this ?</p>