title: JPA and Hibernate mapping with Mysql within Spring context: Can't save Java Set fields into database
body: <p>I am currently learning Hibernate and the Java Persistence API with SPRING.
  I have an @Entity Class "profil" with bidirectionnal association @oneToMany to other @Entity Class "Category".
  I want to get profilA.Set and save into profilB.set but it does not seem to commit to database.</p>
  
  <pre><code>@Entity
  @Table(name = "profil", catalog = "valife", uniqueConstraints = @UniqueConstraint(columnNames = {
          "email", "login" }))
  public class Profil implements java.io.Serializable {
  
      private Long id;
      private int version;
      private String login;
      private String password;
      private String lastname;
      private String firstname;
      private Timestamp creationdate;
      private Timestamp lastaccesdate;
      private boolean enabled;
      private String email;
      private FinancialAccountbook financialAccountbook;
      private NeedsAccountbook needsAccountbook;
      private StockAccountbook stockAccountbook;
  
      private Set&lt;Category&gt; categories = new HashSet&lt;Category&gt;(0);;
      private Set&lt;Payee&gt; payees = new HashSet&lt;Payee&gt;(0);
  
      public Profil() {
      }
  
      public Profil(String login, String password, Timestamp creationdate,
              Timestamp lastaccesdate, boolean enabled, String email) {
          this.login = login;
          this.password = password;
          this.creationdate = creationdate;
          this.lastaccesdate = lastaccesdate;
          this.enabled = enabled;
          this.email = email;
      }
  
      public Profil(String login, String password, String lastname,
              String firstname, Timestamp creationdate, Timestamp lastaccesdate,
              boolean enabled, String email) {
          this.login = login;
          this.password = password;
          this.lastname = lastname;
          this.firstname = firstname;
          this.creationdate = creationdate;
          this.lastaccesdate = lastaccesdate;
          this.enabled = enabled;
          this.email = email;
      }
  
      @Id
      @GeneratedValue(strategy = IDENTITY)
      @Column(name = "id", unique = true, nullable = false)
      public Long getId() {
          return this.id;
      }
  
      public void setId(Long id) {
          this.id = id;
      }
  
      @Version
      @Column(name = "version", nullable = false)
      public int getVersion() {
          return this.version;
      }
  
      public void setVersion(int version) {
          this.version = version;
      }
  
      @Column(name = "login", nullable = false, length = 50)
      @NotNull
      public String getLogin() {
          return this.login;
      }
  
      public void setLogin(String login) {
          this.login = login;
      }
  
      @Column(name = "password", nullable = false, length = 50)
      @NotNull
      public String getPassword() {
          return this.password;
      }
  
      public void setPassword(String password) {
          this.password = password;
      }
  
      @Column(name = "lastname", length = 50)
      public String getLastname() {
          return this.lastname;
      }
  
      public void setLastname(String lastname) {
          this.lastname = lastname;
      }
  
      @Column(name = "firstname", length = 50)
      public String getFirstname() {
          return this.firstname;
      }
  
      public void setFirstname(String firstname) {
          this.firstname = firstname;
      }
  
      @Temporal(TemporalType.TIMESTAMP)
      @Column(name = "creationdate", nullable = false, length = 19)
      public Date getCreationdate() {
          return this.creationdate;
      }
  
      public void setCreationdate(Timestamp creationdate) {
          this.creationdate = creationdate;
      }
  
      @Temporal(TemporalType.TIMESTAMP)
      @Column(name = "lastaccesdate", nullable = false, length = 19)
      public Date getLastaccesdate() {
          return this.lastaccesdate;
      }
  
      public void setLastaccesdate(Timestamp lastaccesdate) {
          this.lastaccesdate = lastaccesdate;
      }
  
      @Column(name = "enabled", nullable = false)
      public boolean isEnabled() {
          return this.enabled;
      }
  
      public void setEnabled(boolean enabled) {
          this.enabled = enabled;
      }
  
      @Column(name = "email", nullable = false, length = 50)
      @NotNull
      @Email
      public String getEmail() {
          return this.email;
      }
  
      public void setEmail(String email) {
          this.email = email;
      }
  
      @OneToOne(mappedBy = "profil")
      public FinancialAccountbook getFinancialAccountbook() {
          return financialAccountbook;
      }
  
      public void setFinancialAccountbook(
              FinancialAccountbook financialAccountbook) {
          this.financialAccountbook = financialAccountbook;
      }
  
      @OneToOne(mappedBy = "profil")
      public NeedsAccountbook getNeedsAccountbook() {
          return needsAccountbook;
      }
  
      public void setNeedsAccountbook(NeedsAccountbook needsAccountbook) {
          this.needsAccountbook = needsAccountbook;
      }
  
      @OneToOne(mappedBy = "profil")
      public StockAccountbook getStockAccountbook() {
          return stockAccountbook;
      }
  
      public void setStockAccountbook(StockAccountbook stockAccountbook) {
          this.stockAccountbook = stockAccountbook;
      }
  
      @OneToMany(mappedBy = "profil", fetch = FetchType.LAZY, cascade = { CascadeType.ALL })
      public Set&lt;Category&gt; getCategories() {
          return categories;
      }
  
      @Transactional
      public void setCategories(Set&lt;Category&gt; catSet) {
  
          this.categories = catSet;
  
      }
  
      @OneToMany(fetch = FetchType.LAZY, mappedBy = "profil")
      public Set&lt;Payee&gt; getPayees() {
          return payees;
      }
  
      public void setPayees(Set&lt;Payee&gt; payees) {
          this.payees = payees;
      }
  
      @Transient
      @SuppressWarnings("unchecked")
      protected &lt;T extends Appendix&gt; Set&lt;T&gt; getAppendixInternal(Class&lt;T&gt; type) {
          Set&lt;T&gt; appendix = null;
          if (type == Category.class) {
              if (this.getCategories() == null) {
                  this.categories = new HashSet&lt;Category&gt;();
              }
              appendix = (Set&lt;T&gt;) this.categories;
  
          }
          if (type == Payee.class) {
              if (this.getPayees() == null) {
                  this.payees = new HashSet&lt;Payee&gt;();
              }
              appendix = (Set&lt;T&gt;) this.payees;
  
          }
          return appendix;
      }
  
      @Transient
      protected &lt;T extends Appendix&gt; List&lt;T&gt; getSortedAppendix(Class&lt;T&gt; type) {
          List&lt;T&gt; sortedPets = new ArrayList&lt;T&gt;(getAppendixInternal(type));
          PropertyComparator.sort(sortedPets, new MutableSortDefinition("name",
                  true, true));
          return Collections.unmodifiableList(sortedPets);
      }
  
      @Transient
      @SuppressWarnings("unchecked")
      public List&lt;Payee&gt; getSortedPayees() {
          return (List&lt;Payee&gt;) this.getAppendixInternal(Payee.class);
      }
  
      @Transient
      @SuppressWarnings("unchecked")
      public List&lt;Category&gt; getSortedCategories() {
          return (List&lt;Category&gt;) this.getAppendixInternal(Category.class);
      }
  
      public void addPayee(Payee payee) {
          this.getPayees().add(payee);
          payee.setProfil(this);
      }
  
      @Transactional
      public void addCategory(Category cat) {
          cat.setProfil(this);
          this.getCategories().add(cat);
  
      }
  }
  </code></pre>
  
  <p>here the code for the test:</p>
  
  <pre><code>        java.util.Date date = new java.util.Date();
          Timestamp currentdate = new Timestamp(date.getTime());
          assertTrue(true);
          Profil profil = new Profil();
          profil.setLogin("default_EN");
          profil.setEnabled(false);
          profil.setPassword("default_EN");
          profil.setCreationdate(currentdate);
          profil.setLastaccesdate(currentdate);
          profil.setEmail("defaultEN@valife.org");
          Profil defaultFRprofil = (Profil) dao.find(new Long(1));
          assertEquals("default_FR", defaultFRprofil.getLogin());
          // dao.deleteObject(dao.find(new Long(8)));
          assertTrue(true);
          Set&lt;Category&gt; cat = new HashSet&lt;Category&gt;(
                  defaultFRprofil.getCategories());
  
          assertTrue(true);
          profil.setCategories(cat);
          assertTrue(true);
  
          dao.saveObject(profil);
  </code></pre>
  
  <p>What i want:
  get profilA.categories (set) and save a new set persistent into profilB.catagories so that in database i will have:</p>
  
  #
  
  <p>|//<strong>id</strong>//|bigint(20)
  |version|int(11)
  |<strong>name</strong>|varchar(50)
  |<strong>profilid</strong>|bigint(20)</p>
  
  <h3>|1|1|AUTOMOBILE|1  &lt;- profilA</h3>
  
  <p>|15|1|AUTOMOBILE|2  &lt;- profilB</p>
  
  <p>Here the code for @Entity Category</p>
  
  <pre><code>package org.egilbox.valife_springMVC.java.domain.model;
  
  import static javax.persistence.GenerationType.IDENTITY;
  
  import java.io.Serializable;
  
  import javax.persistence.CascadeType;
  import javax.persistence.Column;
  import javax.persistence.GeneratedValue;
  import javax.persistence.Id;
  import javax.persistence.JoinColumn;
  import javax.persistence.ManyToOne;
  import javax.persistence.MappedSuperclass;
  import javax.persistence.Version;
  import javax.validation.constraints.NotNull;
  
  import org.hibernate.validator.constraints.NotEmpty;
  
  @MappedSuperclass
  public abstract class Appendix implements Serializable {
  
  private Long id;
  private int version;
  private String name;
  
  private Profil profil;
  
  @Id
  @GeneratedValue(strategy = IDENTITY)
  @Column(name = "id", unique = true, nullable = false)
  public Long getId() {
      return this.id;
  }
  
  public void setId(Long id) {
      this.id = id;
  }
  
  @Version
  @Column(name = "version", nullable = false)
  public int getVersion() {
      return this.version;
  }
  
  public void setVersion(int version) {
      this.version = version;
  }
  
  @Column(name = "name", unique = false, nullable = false, length = 50)
  @NotNull
  @NotEmpty
  public String getName() {
      return this.name;
  }
  
  public void setName(String name) {
      this.name = name;
  }
  
  @ManyToOne(cascade = { CascadeType.ALL })
  @JoinColumn(name = "profilid", nullable = false)
  @NotNull
  public Profil getProfil() {
      return this.profil;
  }
  
  public void setProfil(Profil profil) {
      this.profil = profil;
  }
  
  }
  
  
  
    @Entity
    @Table(name = "category", catalog = "valife", uniqueConstraints =               @UniqueConstraint(columnNames = "name"))
    public class Category extends Appendix {}
  </code></pre>
  
  <p>Code for DAO:</p>
  
  <pre><code>  public abstract class GenericDAOWithHibernate&lt;T, ID extends Serializable&gt; {
  
  private Class&lt;T&gt; persistentClass;
  @PersistenceContext(unitName = "entityManager", properties = @PersistenceProperty(name = "org.hibernate.flushMode", value = "AUTO"))
  protected EntityManager entityManager;
  
  @SuppressWarnings("unchecked")
  public GenericDAOWithHibernate() {
      this.persistentClass = (Class&lt;T&gt;) ((ParameterizedType) getClass()
              .getGenericSuperclass()).getActualTypeArguments()[0];
  }
  
  public void setEntityManager(EntityManager entityManager) {
      this.entityManager = entityManager;
  }
  
  public Class&lt;T&gt; getPersistentClass() {
      return persistentClass;
  }
  
  public T find(ID id) {
      return entityManager.find(persistentClass, id);
  }
  
  @Transactional(propagation = Propagation.MANDATORY)
  public void saveObject(T entity) {
      entityManager.persist(entity);
  }
  
  @Transactional(propagation = Propagation.MANDATORY)
  public void deleteObject(T entity) {
      entityManager.remove(entity);
  }
  
  public List&lt;T&gt; findAll() {
      CriteriaQuery cq = this.entityManager.getCriteriaBuilder()
              .createQuery();
      cq.select(cq.from(persistentClass));
      return this.entityManager.createQuery(cq).getResultList();
  }
  // Inner classes
  
   } // end class GenericDAOWithHibernate
  </code></pre>
  
  <p>XML configuration:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:tx="http://www.springframework.org/schema/tx"
  xsi:schemaLocation="http://www.springframework.org/schema/beans  http://www.springframework.org/schema/beans/spring-beans.xsd
      http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
      http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"&gt;
  
  &lt;!--  RESOURCES DEFINITION --&gt;
  &lt;bean id ="datasource"
  class ="org.springframework.jdbc.datasource.DriverManagerDataSource"&gt;
   &lt;property name="driverClassName" value= "com.mysql.jdbc.Driver" /&gt;
   &lt;property name="password" value="XXX" /&gt;
   &lt;property name="url" value ="jdbc:mysql://localhost/valife" /&gt;
   &lt;property name="username" value="XXX" /&gt;
  &lt;/bean&gt;
  &lt;context:component-scan
          base-package="org.egilbox.valife_springMVC.java.domain"/&gt;
  &lt;bean id ="persistenceUnitManager"
  class ="org.springframework.orm.jpa.persistenceunit.DefaultPersistenceUnitManager" &gt;
  &lt;property name="defaultDataSource" ref="datasource" /&gt;
  
  &lt;property name="persistenceXmlLocations"&gt;
      &lt;list&gt;
      &lt;value&gt;classpath*:META-INF/persistance.xml&lt;/value&gt;
      &lt;/list&gt;
  &lt;/property&gt;
  &lt;/bean&gt;
  &lt;bean id="entityManagerFactory"
  class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" &gt;
  &lt;property name="persistenceUnitManager" ref="persistenceUnitManager" /&gt;
  &lt;property name="persistenceUnitName" value="entityManager" /&gt;
  &lt;/bean&gt;
  
  &lt;bean id ="transactionManager"
  class ="org.springframework.orm.jpa.JpaTransactionManager"&gt;
  &lt;property name="entityManagerFactory" ref="entityManagerFactory" /&gt;
  &lt;/bean&gt;
  &lt;tx:annotation-driven transaction-manager="transactionManager"/&gt;
  &lt;context:annotation-config&gt;&lt;/context:annotation-config&gt;
  &lt;/beans&gt;
  </code></pre>
  
  <p>Persitance.xml:</p>
  
  <pre><code>&lt;?xml version="1.0" encoding="UTF-8"?&gt;
  &lt;persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence"   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence   http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd "&gt;
  &lt;persistence-unit name="entityManager" transaction-type ="RESOURCE_LOCAL"&gt;
  &lt;provider&gt;org.hibernate.ejb.HibernatePersistence&lt;/provider&gt;
  &lt;properties&gt;
   &lt;property name="hibernate.dialect" value ="org.hibernate.dialect.MySQLDialect" /&gt;
   &lt;property name= "hibernate.show_sql" value ="true" /&gt;
  &lt;/properties&gt;
  &lt;/persistence-unit&gt;
  &lt;/persistence&gt;
  </code></pre>