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?
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
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>
Related
I am trying to upgrade Spring from 4.0.6 to 4.3.9 version. While doing so I am getting following error "javax.persistence.TransactionRequiredException: No EntityManager with actual transaction available for current thread". Entire code was working fine earlier but I am getting this error just because of library upgrade. Hibernate version which is being used in my project is 4.3.7.
Here is my applicationcontext.xml
<beans default-autowire="byName"
xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:jaxws="http://cxf.apache.org/jaxws"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://cxf.apache.org/jaxws http://cxf.apache.org/schemas/jaxws.xsd">
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="persistenceUnitName" value="premier" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false" />
</bean>
</property>
</bean>
<bean id="dataSource"
class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:#***:1521:PSPRODDB" />
<property name="username" value="**" />
<property name="password" value="*****" />
</bean>
<!-- entity manager configuration -->
<!--<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />-->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="transactionManager" />
<!-- externals -->
<bean id="mapperFactory" class="org.dozer.spring.DozerBeanMapperFactoryBean">
<property name="mappingFiles" value="classpath*:dozerBeanMapping.xml" />
</bean>
</beans>
My Entity class
#SuppressWarnings("serial")
#Entity
#Table(name = "ROLES")
#NamedQueries({
#NamedQuery(name = "RoleModuleMO.findById", query = "SELECT rolemodule FROM RoleModuleMO rolemodule WHERE rolemodule.id =:id");
#Proxy(lazy = false)
#EntityListeners(value = SimpleAuditListener.class)
public class RoleModuleMO implements Serializable, SimpleAuditable {
public RoleModuleMO () {
}
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "ROLEMODULE_ID_SQ")
#SequenceGenerator(name = "ROLEMODULE_ID_SQ", sequenceName = "ROLEMODULE_ID_SQ")
private Long id;
#Column(name="ISVISIBLE", nullable = false)
private Boolean isVisible;
#Column(name="ISENABLED", nullable = false)
private Boolean isEnabled;
#Column(name="NAME", nullable = false)
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Boolean getVisible() {
return isVisible;
}
public void setVisible(Boolean visible) {
isVisible = visible;
}
public Boolean getEnabled() {
return isEnabled;
}
public void setEnabled(Boolean enabled) {
isEnabled = enabled;
}
}
My Service class
#Transactional
public class RolesServiceImpl implements RolesService {
#PersistenceContext
private EntityManager em;
private RolesDAO rolesDAO;
private Mapper mapper;
public RolesServiceImpl(RolesDAO rolesDAO, Mapper mapper) {
this.rolesDAO = rolesDAO;
this.mapper = mapper;
}
#Transactional
public RoleModule saveOrUpdateModule(RoleModule vo) {
RoleModuleMO mo = new RoleModuleMO();
mapper.map(vo, mo);
mo = rolesDAO.saveOrUpdateModule(mo);
vo = mapper.map(mo, RoleModule.class);
return vo;
}
}
This was working in spring 4.0.6 and after upgrading to 4.3.9 facing the error.
Is there any changes made by spring community which is causing this error or there is something else which I need to change?
Thanks in advance.
Is it possible to create native queries that make use of an existing transaction created via #Transactional?
Most of the questions here seem to be about making native queries at all. Also, answers such as the one from Spring + Hibernate Transaction -- Native SQL rollback failure suggest it might not be possible.
What I do to test the isolation is to run some deletes and add a breakpoint to investigate the database.
Here is what I tried so far:
#Transactional(value = "someManager")
public class SpringJpaSomeDao implements SomeDao {
#PersistenceContext(unitName = "someUnit")
#Qualifier("entityManagerFactorySome")
private EntityManager em;
#Resource
#Qualifier("someManager")
private PlatformTransactionManager transactionManager;
#Override
#Transactional(value = "someManager", propagation = Propagation.SUPPORTS)
public void runNative(String sql){
TransactionTemplate transactionTemplate = new TransactionTemplate(transactionManager);
transactionTemplate.setPropagationBehavior(TransactionDefinition.PROPAGATION_SUPPORTS);
transactionTemplate.execute(new TransactionCallbackWithoutResult() {
#Override
protected void doInTransactionWithoutResult(TransactionStatus status) {
em.createNativeQuery(sql).executeUpdate();
}
});
}
Some part of the persistence.xml
<persistence-unit name="someUnit" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>java:comp/env/jdbc/someDS</non-jta-data-source>
<!-- some classes here -->
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<!-- some dialect -->
</properties>
</persistence-unit>
The code is invoked from some controller which also has #Transactional annotations giving the deletes to the Dao.
#Transactional(value = "someManager", propagation = Propagation.SUPPORTS)
public void deleteEntireDatabase() {
List<String> deletions = new ArrayList<>();
deletions.add("DELETE FROM something;");
for (String currentDeletion : deletions) {
someDao.runNative(currentDeletion);
}
}
#Override
#Transactional(value = "someManager", propagation = Propagation.REQUIRES_NEW, rollbackFor = {Exception.class})
public void deleteAndFill(JobExecutionProgress progress) {
deleteEntireDatabase();
// more code
}
Excerpt from spring-dao.xml:
<tx:annotation-driven />
<bean id="entityManagerFactorySome" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="someDataSource" />
<property name="persistenceUnitName" value="someUnit" />
<property name="jpaProperties">
<props>
<!-- some dialect -->
</props>
</property>
</bean>
<bean id="someDao" class="xyz.model.controller.SpringJpaSomeDao"/>
<bean id="someManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactorySome" />
<qualifier value="someManager"></qualifier>
</bean>
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
Of course, I also tried some variations such as different Propagations, and using the entityManager obtained from elsewhere:
EntityManagerFactory emf = ((JpaTransactionManager) transactionManager).getEntityManagerFactory();
EntityManager em2 = EntityManagerFactoryUtils.getTransactionalEntityManager(emf);
Now, what I will do if everything else fails is manual transaction management.
Is this something that has worked for one of your applications or is it unknown if this might be a setup problem?
Actually, it turns out the alter table statements mentioned in the comment seem to have been the problem. Not sure how resetting the auto_increment can empty the table, but that seemed to be the case.
I need to configure spring + JPA (EntityManager) + Hibernate .
If I had to fetch = FetchType.LAZY run server success
If I had to fetch = FetchType.EAGER run server error:
I using tomcat 7
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is javax.persistence.PersistenceException: [PersistenceUnit: fmis2] Unable to build EntityManagerFactory
...
Caused by: javax.persistence.PersistenceException: [PersistenceUnit: fmis2] Unable to build EntityManagerFactory
...
Caused by: org.hibernate.loader.MultipleBagFetchException: can not simultaneously fetch multiple bags
Please help me. Where I was wrong.
Thanks
Config applicationContext.xml
<context:annotation-config />
<context:component-scan base-package="com.evnit.fmis" />
<jpa:repositories base-package="com.evnit.fmis" />
<!-- START -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceXmlLocation" value="classpath:META-INF/jpa-persistence.xml" />
<property name="persistenceUnitName" value="fmis2" />
<property name="dataSource" ref="fmis2dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="false" />
<property name="databasePlatform" value="org.hibernate.dialect.SQLServerDialect" />
<property name="database" value="SQL_SERVER" />
</bean>
</property>
<property name="loadTimeWeaver">
<bean
class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver" />
</property>
</bean>
<bean id="fmis2dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
</bean>
<bean id="txManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
</bean>
<tx:annotation-driven transaction-manager="txManager" />
jpa-persistence.xml
<persistence-unit name="fmis2" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<jar-file>/WEB-INF/lib/accounting-inf-1.0-SNAPSHOT.jar</jar-file>
<jar-file>/WEB-INF/lib/masterdata-inf-1.0-SNAPSHOT.jar</jar-file>
<jar-file>/WEB-INF/lib/congno-backend-1.0-SNAPSHOT.jar</jar-file>
<jar-file>/WEB-INF/lib/congcudungcu-backend-1.0-SNAPSHOT.jar</jar-file>
<jar-file>/WEB-INF/lib/taisan-backend-1.0-SNAPSHOT.jar</jar-file>
<jar-file>/WEB-INF/lib/vattu-backend-1.0-SNAPSHOT.jar</jar-file>
<jar-file>/WEB-INF/lib/muahang-backend-1.0-SNAPSHOT.jar</jar-file>
</persistence-unit>
Java Code entity
package com.evnit.fmis.accounting.entity;
#Entity
#Table(name = "ChungTu", schema = "ketoan")
public class ChungTu implements java.io.Serializable {
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "chungTu")
public List<DinhKhoan> getDinhKhoans() {
return this.dinhKhoans;
}
public void setDinhKhoans(List<DinhKhoan> dinhKhoans) {
this.dinhKhoans = dinhKhoans;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "chungTu")
public List<Uynhiemchi> getUynhiemchis() {
return this.uynhiemchis;
}
public void setUynhiemchis(List<Uynhiemchi> uynhiemchis) {
this.uynhiemchis = uynhiemchis;
}
}
#Entity
#Table(name = "DinhKhoan", schema = "ketoan")
public class DinhKhoan implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private ChungTu chungTu;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "IdChungtu")
public ChungTu getChungTu() {
return this.chungTu;
}
public void setChungTu(ChungTu chungTu) {
this.chungTu = chungTu;
}
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER, mappedBy = "dinhKhoan")
public List<HoaDonVat> getHoaDonVats() {
return this.hoaDonVats;
}
public void setHoaDonVats(List<HoaDonVat> hoaDonVats) {
this.hoaDonVats = hoaDonVats;
}
}
#Entity
#Table(name = "Uynhiemchi", schema = "ketoan")
public class Uynhiemchi implements java.io.Serializable {
private ChungTu chungTu;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "IdChungtu", nullable = true)
public ChungTu getChungTu() {
return this.chungTu;
}
public void setChungTu(ChungTu chungTu) {
this.chungTu = chungTu;
}
}
#Entity
#Table(name = "HoaDonVAT", schema = "ketoan")
public class HoaDonVat implements java.io.Serializable {
private DinhKhoan dinhKhoan;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "IdDinhKhoan")
public DinhKhoan getDinhKhoan() {
return this.dinhKhoan;
}
public void setDinhKhoan(DinhKhoan dinhKhoan) {
this.dinhKhoan = dinhKhoan;
}
}
Java Code Dao
public abstract class CommonDao {
#PersistenceContext(unitName = "fmis2")
protected EntityManager entityManager;
}
The problem is the Hibernate specification: he doesn't allow more than one list noted with EAGER. There are some options to bypass this problem:
Use LAZY lists. If you need 'to simulate' a eager relation, use yourList.size() to populate before the query;
Use Set instead List in your data structures.
Other explanations:
Hibernate cannot simultaneously fetch multiple bags
Multiple fetches with EAGER type in Hibernate with JPA
Regards.
When I try to persist an object nothing happens (Exception, error, etc) and I didn't find the cause.
My suspect is that the problem is the transactional control of Spring, because the queries work fine.
I'm using Spring 3.2 with JPA 2 and the JPA implementation is the Hibernate 4.2.18.
Entity
#Entity
#Table(name = "DOLAR")
#NamedQueries({
#NamedQuery(name = Dolar.FIND_ALL, query = "SELECT d FROM Dolar d"),
#NamedQuery(name = Dolar.FIND_BY_EMPRESA, query = "SELECT d FROM Dolar d WHERE d.empresa = :e")
})
public class Dolar implements Serializable, AbstractEntity {
#Transient
private static final long serialVersionUID = 1L;
#Transient
public static final String FIND_BY_EMPRESA = "Dolar.findByEmpr";
#Transient
public static final String FIND_ALL = "Dolar.findAll";
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
#Column(name="ID")
private Long id;
#OneToOne
#JoinColumn(name = "EMPRESA_ID")
private Empresa empresa;
#Column(name = "VALOR")
private BigDecimal valor;
public Dolar() {
}
Managed bean
#Controller("dolarMB")
#Scope(ViewScope.VIEW_SCOPE)
public class DolarMB extends AbstractMB<Dolar> implements Serializable {
private static final long serialVersionUID = 7711019409135908863L;
private static final Logger LOGGER = Logger.getLogger(DolarMB.class);
#Autowired
private DaoDolar dao;
private List<Dolar> lista;
private Dolar cadastro;
private Empresa empresa;
#PostConstruct
public void init(){
cadastro = new Dolar();
LOGGER.info("init:\n" + cadastro);
}
public void salvar() {
if (!validate()){
LOGGER.info("erro no cadastro");
}else{
cadastro = dao.salvar(cadastro);
limparFiltro();
}
}
}
Dao
#Repository
public class DolarDaoImpl extends GenericDaoImpl<Dolar> implements DolarDao{
#Override
public Dolar recuperarPorEmpresa(Empresa e) {
Query q = getConexao().createNamedQuery(Dolar.FIND_BY_EMPRESA);
q.setParameter("empr", e);
return (Dolar) q.getSingleResult();
}
}
#Repository
public abstract class GenericDaoImpl<T extends AbstractEntity> implements GenericDao<T> {
#PersistenceContext
private EntityManager em;
private Class<T> clazz;
private Method m;
public GenericDaoImpl() {
carregarClass();
carregarMetodoId();
}
#Override
#Transactional
public final T salvar(T e) {
if (e == null)
return null;
try {
if (m.invoke(e) != null) {
e = em.merge(e);
} else {
em.persist(e);
}
return e;
} catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
Logger.getLogger(getClass()).error(e1);
} catch (Exception e2) {
Logger.getLogger(getClass()).error(e2);
}
return null;
}
After the em.persist(e), the log show me this
08-04-2015 18:04:15 DEBUG (TransactionSynchronizationManager.java:136) - Retrieved value [org.springframework.orm.jpa.EntityManagerHolder#46e82828] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean#7113aac4] bound to thread [http-nio-8080-exec-7]
- Retrieved value [org.springframework.orm.jpa.EntityManagerHolder#46e82828] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean#7113aac4] bound to thread [http-nio-8080-exec-7]
08-04-2015 18:04:15 TRACE (AbstractSaveEventListener.java:499) - Transient instance of: br.com.mycompany.sales.model.Dolar
- Transient instance of: br.com.mycompany.sales.model.Dolar
08-04-2015 18:04:15 TRACE (DefaultPersistEventListener.java:202) - Saving transient instance
- Saving transient instance
08-04-2015 18:04:15 TRACE (AbstractSaveEventListener.java:167) - Saving [br.com.mycompany.sales.model.Dolar#<null>]
- Saving [br.com.mycompany.sales.model.Dolar#<null>]
08-04-2015 18:04:15 TRACE (ActionQueue.java:192) - Adding an EntityIdentityInsertAction for [br.com.mycompany.sales.model.Dolar] object
- Adding an EntityIdentityInsertAction for [br.com.mycompany.sales.model.Dolar] object
08-04-2015 18:04:15 TRACE (ActionQueue.java:208) - Adding insert with no non-nullable, transient entities: [EntityIdentityInsertAction[br.com.mycompany.sales.model.Dolar#<delayed:2>]]
- Adding insert with no non-nullable, transient entities: [EntityIdentityInsertAction[br.com.mycompany.sales.model.Dolar#<delayed:2>]]
08-04-2015 18:04:15 TRACE (ActionQueue.java:232) - Adding resolved non-early insert action.
- Adding resolved non-early insert action.
08-04-2015 18:04:15 TRACE (UnresolvedEntityInsertActions.java:214) - No unresolved entity inserts that depended on [[br.com.mycompany.sales.model.Dolar#<delayed:2>]]
- No unresolved entity inserts that depended on [[br.com.mycompany.sales.model.Dolar#<delayed:2>]]
08-04-2015 18:04:15 TRACE (UnresolvedEntityInsertActions.java:121) - No entity insert actions have non-nullable, transient entity dependencies.
- No entity insert actions have non-nullable, transient entity dependencies.
08-04-2015 18:06:30 DEBUG (TransactionSynchronizationManager.java:136) - Retrieved value [org.springframework.orm.jpa.EntityManagerHolder#46e82828] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean#7113aac4] bound to thread [http-nio-8080-exec-7]
- Retrieved value [org.springframework.orm.jpa.EntityManagerHolder#46e82828] for key [org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean#7113aac4] bound to thread [http-nio-8080-exec-7]
08-04-2015 18:06:30 TRACE (AbstractSaveEventListener.java:482) - Persistent instance of: br.com.mycompany.sales.model.Dolar
- Persistent instance of: br.com.mycompany.sales.model.Dolar
08-04-2015 18:06:30 TRACE (DefaultPersistEventListener.java:174) - Ignoring persistent instance
- Ignoring persistent instance
08-04-2015 18:06:30 TRACE (UnresolvedEntityInsertActions.java:121) - No entity insert actions have non-nullable, transient entity dependencies.
- No entity insert actions have non-nullable, transient entity dependencies.
This is my configuration file
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd">
<!-- Datasource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="driverClass" value="${database.driver}" />
<property name="user" value="${database.user}" />
<property name="password" value="${database.password}" />
<property name="jdbcUrl" value="${database.url}"/>
<!-- C3P0 properties -->
<property name="acquireIncrement" value="1" />
<property name="maxPoolSize" value="4" />
<property name="minPoolSize" value="1" />
<property name="maxIdleTime" value="120" />
<property name="initialPoolSize" value="1" />
</bean>
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="persistenceUnitName" value="SALES-HOMOLOG" />
<property name="dataSource" ref="dataSource" />
<property name="jpaDialect" ref="jpaDialect" />
<property name="packagesToScan">
<list>
<value>br.com.mycompany.sales.model</value>
</list>
</property>
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">${database.dialect}</prop>
<prop key="hibernate.hbm2ddl.auto">${database.hbm2ddl.auto}</prop>
<prop key="hibernate.show_sql">${database.showSql}</prop>
<prop key="hibernate.format_sql">${database.formatSql}</prop>
</props>
</property>
</bean>
<bean id="jpaDialect" class="org.springframework.orm.jpa.vendor.HibernateJpaDialect"/>
<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="${database.showSql}" />
<property name="generateDdl" value="true" />
<property name="databasePlatform" value="${database.dialect}" />
</bean>
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<tx:annotation-driven transaction-manager="transactionManager"/>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory" />
<property name="dataSource" ref="dataSource" />
</bean>
</beans>
my persistence.xml
<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="SALES-HOMOLOG" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>br.com.mycompany.sales.model.Dolar</class>
<class>br.com.mycompany.sales.model.Empresa</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
</persistence-unit>
</persistence>
The packages to scan entities shows something else than your logs shows as
entity class.
Your class is br.com.mycompany.sales.model.Dolar and the package that should hold the entity classes is defined like this br.com.mycompany.sales.dao. Either move the class to that package or change the package name on the class.
first off you should show us the code that where you are trying to save the instance. try calling the method below and I think it will work.
#Override
#Transactional
public final T salvar(T e)
this if from your GenericDaoImpl try using this.
I solved the problem updating a dependency of Spring.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-dao</artifactId>
<version>2.0.3</version>
</dependency>
I updated to version 2.0.8 and the transaction control worked.
Trough the entity manager I'm tryng to persist the entity in the database but I don manage to persists it. Here goes my configuration.
I have this Entity:
#Entity
#Table(name = "User")
public class UserModel implements Serializable, ModelItem {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(nullable = false)
private String username;
#Column(nullable = false)
private String password;
#Column(nullable = false)
private String name;
private String surname;
private String notes;
private String cellphone;
#Column(nullable = false)
private String email;
private Boolean enabled;
//get and set methods
.....
}
and my import bean that does the persistence:
#Repository
public class ImportServiceImpl implements ImportService {
#PersistenceContext
protected EntityManager entityManager;
#Transactional
public boolean importExample() {
User u= new User();
u.setUsername("username");
u.setPassword("password");
u.setName("name");
u.setEmail("email");
entityManager.persist(u);
}
}
The spring configuration for the entity manager and the db connction:
<tx:annotation-driven transaction-manager="transactionManager" />
<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" />
<tx:annotation-driven />
<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>
<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="jpaVendorAdapter">
<bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="showSql" value="true" /> <!-- Prints used SQL to stdout -->
<property name="generateDdl" value="true" /> <!-- Generates tables. -->
<property name="databasePlatform" value="org.hibernate.dialect.MySQL5Dialect" />
</bean>
</property>
</bean>
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="com.mysql.jdbc.Driver"/>
<property name="url">
<value>${db.url}</value>
</property>
<property name="username">
<value>${db.username}</value>
</property>
<property name="password">
<value>${db.password}</value>
</property>
</bean>
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
<property name="dataSource" ref="dataSource"/>
</bean>
and my persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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_1_0.xsd"
version="1.0">
<persistence-unit name="application" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/testdata"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.password" value="password"/>
<property name="hibernate.connection.username" value="root"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>
So when I run my example I don't get any error but entity is not persisted. I also tryied to add entityManager.flush() after persist but in this case i get this error:
javax.persistence.TransactionRequiredException: no transaction is in progress
at org.hibernate.ejb.AbstractEntityManagerImpl.flush(AbstractEntityManagerImpl.java:793)
So I'm thinking my Transactional bean is not well binded to the method, but I can not understand the reason. Somebody knows why?
I also noticed in STS that for this transaction are generated 2 beans with same data it looks strange (I don't know if it is a bug of STS or is a problem in my configuration that creates 2 beans):
I've faced an issue similar to the one described.
I found the problem in incorrect usage of #Transactional notation, in particular I've wrongly used javax.transaction.Transactional instead of org.springframework.transaction.annotation.Transactional
A detailed description of the difference can be found here at javax.transaction.Transactional vs org.springframework.transaction.annotation.Transactional
Maybe try specifying the persistence unit name "application" in your #PersistenceContext annotation?
#PersistenceContext(unitname = "application")
I also faced the same issue, as Repoker said Persistence provider is ok but my transaction manager was screwed. I added transactionManager bean in my application-config.xml like this
<bean id="transactionManager" cass="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="myEntityManagerFactory" />
</bean>
and It works fine now!!
you can use entityManager.flush() just after persist and merge it could solve your problem
You have <tx:annotation-driven /> twice in your context config. I'm not sure that is a legal config.
I had a similar issue where #Transactional didn't persist entity in the DB using EntityManager. To solve this problem we can commit the transaction manually.
entityManager.getTransaction().begin();
entityManager.persist(post);
entityManager.getTransaction().commit();