Question

I have problem with using EntityManager.persist(Object) method. Now when i get rid of other problems, by app work without Exception but object is not put in my database.

my entity class:

@Entity
@Table(name ="Chain")
public class Chain implements Serializable{

@Id
@Column(name = "id")
  private Long id;
@Column(name = "date")
  private Date date;
@Column(name = "name")
  private String name;
//setters and getters
}

my dao class:

@Transactional
@Repository("ChainDao")
public class ChainDaoImpl implements ChainDao{


    private EntityManager em;


    @PersistenceContext
    public void setEntityManager(EntityManager em) {
        this. em = em;
    }

    public int saveChain(Chain chain) {
        chain.setDate(new Date());
        chain.setId((long)44);
        Boolean a;
        em.persist(chain);

        return 222;
    }
}

my xml context:

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" >
    <property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.xml"></property></bean>


    <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />

    <bean class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory"
            ref="entityManagerFactory" />
    </bean>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="entityManagerFactory" />
    </bean> 

and pereistence.xml:

<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
       <persistence-unit name="sample">
        <provider>org.hibernate.ejb.HibernatePersistence</provider>
        <!-- Scan for annotated classes and Hibernate mapping XML files -->
        <properties>
           <property name="hibernate.archive.autodetection" value="class, hbm"/>
           <property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
           <property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/database"/>
           <property name="hibernate.connection.username" value="postgres"/>
           <property name="hibernate.connection.password" value="pwd"/>
           <property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQLDialect"/>
           <property name="hibernate.show_sql" value="true"/>
        </properties>
        </persistence-unit>

    </persistence>

Do anyone have a idea what am i missing?

Was it helpful?

Solution

Are you getting a specific exception? It would be helpful to know what it is if you are.

There are a number of similar problems to this already on Stackoverflow:

Spring transactional context doesn't persist data

Spring, Hibernate & JPA: Calling persist on entitymanager does not seem to commit to database

These suggest that you should try adding em.flush() after the em.persist(chain), and altering the @transactional annotations

You should also check that you have enabled transactional annotations through a line such as :

<tx:annotation-driven transaction-manager="transactionManager"/> 

in your .xml configuration

OTHER TIPS

Try this:

em.getTransaction().begin();
em.persist(entity);
em.getTransaction().commit();

PS: You should set a generation method for your ID as well.

Can you post what exception are you getting? I will assume that your error is that your persistence.xml you don't specified your "Chain" Object.

You can specify using this tag

<exclude-unlisted-classes>false</exclude-unlisted-classes>

Or just

 <class>your.package.Chain</class>

Put this above provider tag.

Also, never set a number for a column tagged as @Id

When you use method save() with a Id column with setted value, hibernate will try to UPDATE NOT INSERT your data.

Do this: Create getEntityManager Method

public EntityManager getEntityManager() {
    return entityManager;
}

Then

@Transactional
public void saveChain(Chain chain) {

    chain.setDate(new Date());
    getEntityManager().persist(chain);
}

Adding these to your web.xml may solve this problem:

<!-- Open Entity Manager in View filter -->
<filter>
    <filter-name>openEntityManagerInViewFilter</filter-name>
    <filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
    <filter-name>openEntityManagerInViewFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

solved my problem using

org.springframework.transaction.jta.JtaTransactionManager

hope this work!

Use @EnableTransactionManagement in AppConfig Configuration file header

You can open the new Transaction and then commit your records.

@PersistenceUnit(unitName = "NameOfPersistenceUnit")
private EntityManagerFactory entityManagerFactory;

void someMethod(AccountCommodity accountCommodity){
     EntityManager entityManager = entityManagerFactory.createEntityManager();
     entityManager.getTransaction().begin();
     entityManager.persist(accountCommodity);
     entityManager.flush();
     entityManager.getTransaction().commit();
     entityManager.close();
}

You will need to assign id generation strategy as below:

@Entity
@Table(name ="Chain")
public class Chain implements Serializable{

@Id
@Column(name = "id")
    @GeneratedValue(strategy=GenerationType.IDENTITY)
  private Long id;
@Column(name = "date")
  private Date date;
@Column(name = "name")
  private String name;
//setters and getters
}

and in save method

  public int saveChain(Chain chain) {
        chain.setDate(new Date());
      //chain.setId((long)44);  remove this line
        Boolean a;
        em.persist(chain);

        return 222;
    }

if you assign Id, then hibernate/jpa will try to update record, which is not available, instead of inserting new record and I think will not throw exception.

I was able to fix the same problem by adding the Entity to persistence.xml:

<persistence-unit name="OwnerPersistenceUnit" transaction-type="RESOURCE_LOCAL">
    <provider>org.hibernate.ejb.HibernatePersistence</provider>
    <class>com.test.domain.local.Entity</class>
    <exclude-unlisted-classes />
    </persistence-unit>
</persistence>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top