title: Hibernate transform instance to subclass
body: <p>I have mapped class in JPA. :</p>
  
  <pre><code>@Entity
  @Inheritance(strategy = InheritanceType.JOINED)
  public class User {
      private Long id;
      private Long name;
      //getters and setters go here
      ....
  }
  </code></pre>
  
  <p>I also have a subclass of this class, called Admin:</p>
  
  <pre><code>@Entity
  public class Admin extends User {
      private String cridentials;
      //getters and setters go here
      ....
  }
  </code></pre>
  
  <p>Now in my code I have managed instance of User attached to the session</p>
  
  <pre><code>...
  User user = entityManager.find(User.class, userId)
  </code></pre>
  
  <p>I need to transform this user to its subclass, Admin. This means I need 'User' table data remain untouched and new row to be inserted into 'Admin' table:</p>
  
  <pre><code>javax.persistence.EntityManager entityManager = ...;
  ...
  User user = entityManager.find(User.class, userId)
  Admin admin = new Admin();
  admin.setName(user.getName());
  
  entityManager.persist(admin);
  </code></pre>
  
  <p>But after I execute the last line, another row is inserted in both User and Admin tables.  How would I solve this? </p>
  
  <p>The only way I found so far is to save the fields of a User somewhere, then delete this instance from DB, and then create new Admin with all the data from User class. But I bet there is much better way of doing this.</p>
  
  <p>Thanks</p>