为什么实体没有在Spring 3.2的JPA / Hibernate设置中保留?

时间:2015-08-05 15:36:14

标签: spring hibernate jpa

当我试图坚持一个物体没有任何反应(例外,错误等),我没有找到原因。

我怀疑是问题是Spring的事务控制,因为查询工作正常。

我使用Spring 3.2和JPA 2,JPA实现是Hibernate 4.2.18。

实体

@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() {
}

托管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();

        }

    }
}

@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;
}

在em.persist(e)之后,日志显示了这个

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.

这是我的配置文件

<?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>    

我的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>

3 个答案:

答案 0 :(得分:0)

扫描实体的软件包显示的内容不是您的日志显示的内容 实体类。 您的类是br.com.mycompany.sales.model.Dolar,应该包含实体类的包定义如此br.com.mycompany.sales.dao。将类移动到该包或更改类的包名称。

答案 1 :(得分:0)

首先,您应该向我们展示您尝试保存实例的代码。尝试调用下面的方法,我认为它会起作用。

    @Override
@Transactional
public final T salvar(T e)

如果你的GenericDaoImpl尝试使用它。

答案 2 :(得分:0)

我解决了更新Spring依赖的问题。


fa-re
word
word-ed
wo-ded
wor
text
uncial

我更新到版本2.0.8并且事务控制工作正常。