My entityManager persist() gets id from sequence and puts it to my Image object but the Image object itself is not showing up in the database. EntityManager.flush() gives an error so I can't commit this way. Here is my code.
@Repository public class ImageDaoImpl extends BaseDao implements ImageDao { @PersistenceContext protected EntityManager entityManager; @Override @Transactional public void create(Image image) { JpaTemplate jpaTemplate = getJpaTemplate(entityManager); jpaTemplate.persist(image); }
@Repository public class BaseDao { private JpaTemplate jpaTemplate; public JpaTemplate getJpaTemplate(EntityManager entityManager){ if(jpaTemplate == null) jpaTemplate = new JpaTemplate(entityManager); return jpaTemplate; }
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" p:dataSource-ref="dataSource"> <property name="jpaVendorAdapter"> <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"> <property name="showSql" value="true" /> <property name="generateDdl" value="true" /> <property name="databasePlatform" value="org.hibernate.dialect.PostgreSQLDialect" /> </bean> </property> <property name="persistenceUnitName" value="sample"></property> </bean> <!-- DataSource Setup --> <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"> <property name="driverClassName" value="org.postgresql.Driver" /> <property name="url" value="jdbc:postgresql://localhost:5432/imageCapture" /> <property name="username" value="myusername" /> <property name="password" value="mypassword" /> </bean> <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"> <property name="entityManagerFactory" ref="entityManagerFactory" /> </bean> <tx:annotation-driven transaction-manager="transactionManager" />
The EntityManager. persist() operation is used to insert a new object into the database. persist does not directly insert the object into the database: it just registers it as new in the persistence context (transaction).
To save data in database permanently JPA needs to insert data using insert/update/delete statements and then commit this data. Committing a transaction is always necessary. Flush() method executes only insert/update/delete statements without commiting the data, so the transaction and data can be rolled back.
This generally happens when Transaction in not applied.. I doubt @Transactional interceptor is not intercepting properly.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With