13

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?

Grzzzzzzzzzzzzz
  • 1,301
  • 4
  • 20
  • 33
  • 1
    Don't assign a ID to your entity, and let hibernate assign it on save (by using one of ID generation mechanisms). – Amir Pashazadeh Dec 07 '12 at 09:06
  • if i use `@GeneratedValue(strategy = GenerationType.AUTO)` i get `org.hibernate.exception.SQLGrammarException: could not get next sequence value` – Grzzzzzzzzzzzzz Dec 07 '12 at 09:07
  • Please check your spring-transaction configuration, I had similar problem , and it was due to improper transaction config – Dhananjay Dec 07 '12 at 09:19
  • what is wrong with this one? – Grzzzzzzzzzzzzz Dec 07 '12 at 09:23
  • i have the same problem with spring and eclipselink... did you get an appropriate solution.. i hav tried everything roryb suggested to no avail... – Sorter Jul 26 '13 at 18:44
  • OMG, i spent some hours with this problem =P .. In my case I'm using Camel, Spring and Hibernate + JPA.. I forgot a little detail. Was missing the **@Transactional** annotation in My **@Service** method. Thanks for **the hint about flush**. I've just put the flush and the long awaited exception appears in the log. nice link about possible causes : http://www.scarba05.co.uk/blog/2010/02/hibernate-jpa-is-swallowing-my-data-no-save-no-error/ – Eduardo Fabricio Jan 08 '14 at 22:24

9 Answers9

10

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

Community
  • 1
  • 1
RoryB
  • 1,047
  • 7
  • 28
7

Try this:

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

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

Peter Adrian
  • 279
  • 1
  • 5
1

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);
}
Bernardo Vale
  • 3,224
  • 4
  • 21
  • 34
  • Still no exception and no record in database – Grzzzzzzzzzzzzz Dec 07 '12 at 09:16
  • 1
    OMG, i spent some hours with this problem =P .. In my case I'm using Camel, Spring and Hibernate + JPA.. I forgot a little detail. Was missing the **@Transactional** annotation in My **@Service** method. Thanks for **the hint about flush**. I've just put the flush and the long awaited exception appears in the log. nice link about possible causes : http://www.scarba05.co.uk/blog/2010/02/hibernate-jpa-is-swallowing-my-data-no-save-no-error/ – Eduardo Fabricio Jan 08 '14 at 22:21
  • thanks you have saved my time. It was due to em.flush(). – Sai prateek Sep 06 '14 at 08:10
0

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>
ElvisKang
  • 77
  • 5
0

solved my problem using

org.springframework.transaction.jta.JtaTransactionManager

hope this work!

Wilson Campusano
  • 616
  • 9
  • 21
0

Use @EnableTransactionManagement in AppConfig Configuration file header

0

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();
}
-1

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.

Bernardo Vale
  • 3,224
  • 4
  • 21
  • 34
Jigar Parekh
  • 6,163
  • 7
  • 44
  • 64
-1

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>
kryger
  • 12,906
  • 8
  • 44
  • 65
hlopezvg
  • 555
  • 5
  • 11