Search code examples
javainsertpersistencepersist

java persistence works with reading from database, silently fails to insert / update


I have created a simple java web (Vaadin) application project using JPA and it works for reading entities from database. When I try to use either persist() or merge(), nothing happens in database. When looking at the logs, there are SELECT queries, but no INSERT / UPDATE.

I am using Glassfish 3.1 with JDBC resource defined, persistence.xml to use that resource (JTA). I am using default configuration files, generated automatically by Eclipse.

There is also another similar project done by someone else, uses the same JTA and this problem does not appear. Looked over its configuration and didn't find anything important.

Both projects do not use transactions.

persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<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">
<persistence-unit name="MapperPersistence">
    <jta-data-source>mapper</jta-data-source>
         <class>pl.bdk.mapper.domain.jpaImpl.MappingImpl</class>
...
         <class>pl.bdk.mapper.domain.jpaImpl.UserImpl</class>
             <properties>
                 <property name="eclipselink.logging.level" value="FINE" />
             </properties>
    </persistence-unit>
</persistence>

Java code

public class MappingService {
    public static int createMapping(String clientProductId, User user) {
        MappingImpl mapping = new MappingImpl();
        mapping.setUser(user);
        mappingDao.save(mapping);
        return mapping.getMappingId();
    }
}

...
public class MappingDao {
    public void save(MappingImpl mapping) {
        entityManager.persist(mapping);
    }
}

...
@Entity
@Table("t_mapping")
public class MappingImpl() {
    @Id
    @SequenceGenerator(name="T_MAPPING_MAPPINGID_GENERATOR", sequenceName="S_MAPPING_ID", allocationSize=1)
    @GeneratedValue(strategy=GenerationType.SEQUENCE, generator="T_MAPPING_MAPPINGID_GENERATOR")
    private Integer id;

    @ManyToOne
    @JoinColumn(name="user_id")
    private User user;

... getters and setters...
}

Solution

  • OK, the matter seemed simple, but it isn't.

    This post helped me a lot: Hibernate doesn't save and doesn't throw exceptions?

    First of all - JPA needs some kind of transaction mechanism. Normally it is managed underneath and needs no setup. This means the easiest way is to create an EJB (Enterprise Java Bean) project, where EntityManager would be injected with @PersistenceContext. If one prefers to create the EntityManager locally (no EJB), a transaction mechanism still has to be provided. More info in the above post.