19

我正在尝试使用 Hibernate 和 JPA 设置 Spring,但是在尝试持久化对象时,似乎没有将任何内容添加到数据库中。

我正在使用以下内容:

<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
    <property name="url" value="${jdbc.url}"/>
    <property name="driverClassName" value="${jdbc.driverClassName}"/>
    <property name="username" value="${jdbc.username}"/>
    <property name="password" value="${jdbc.password}"/>
</bean>

<bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
    <property name="dataSource" ref="dataSource" />
    <property name="persistenceUnitName" value="BankingWeb" />
    <property name="jpaVendorAdapter">
        <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
            <property name="generateDdl" value="true" />
            <property name="showSql" value="true" />
            <property name="databasePlatform" value="${hibernate.dialect}" />
        </bean>
    </property>
</bean>

<tx:annotation-driven/>

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

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

<bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

<bean name="accountManager" class="ssel.banking.dao.jpa.AccountManager" />
<bean name="userManager" class="ssel.banking.dao.jpa.UserManager" />

在 AccountManager 中,我正在做:

@Repository
public class AccountManager implements IAccountManager {

    @PersistenceContext private EntityManager em;

    /* -- 8< -- Query methods omitted -- 8< -- */

    public Account storeAccount(Account ac) {
    ac = em.merge(ac);
        em.persist(ac);
        return ac;
    }
}

ac 来自哪里:

    Account ac = new Account();
    ac.setId(mostRecent.getId()+1);
    ac.setUser(user);
    ac.setName(accName);
    ac.setDate(new Date());
    ac.setValue(0);
    ac = accountManager.storeAccount(ac);
    return ac;

有没有人可以指出我做错了什么?持久调用返回而不抛出异常。如果之后我这样做em.contains(ac),这将返回 true。

如果有人需要,以下是 Account 的定义方式:

@SuppressWarnings("serial")
@Entity
@NamedQueries({
        @NamedQuery(name = "Account.AllAccounts", query = "SELECT a FROM Account a"),
        @NamedQuery(name = "Account.Accounts4User", query = "SELECT a FROM Account a WHERE user=:user"), 
        @NamedQuery(name = "Account.Account4Name", query = "SELECT a FROM Account a WHERE name=:name"),
        @NamedQuery(name = "Account.MaxId", query = "SELECT MAX(a.id) FROM Account a"),
        @NamedQuery(name = "Account.Account4Id", query = "SELECT a FROM Account a WHERE id=:id"),
    })
public class Account extends AbstractNamedDomain {
    @Temporal(TemporalType.DATE)
    @Column(name = "xdate")
    private Date date;

    private double value;

    @ManyToOne(cascade={CascadeType.PERSIST, CascadeType.MERGE})
    @JoinColumn(name="userid")
    private User user;

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    @OneToMany(cascade={CascadeType.PERSIST, CascadeType.MERGE}, fetch=FetchType.EAGER)
    @OrderBy("date")
    private List<AccountActivity> accountActivity = new ArrayList<AccountActivity>();

    public List<AccountActivity> getAccountActivity() {
        return accountActivity;
    }

    public void setAccountActivity(List<AccountActivity> accountActivity) {
        this.accountActivity = accountActivity;
    }

    public Date getDate() {
        return date;
    }

    public void setDate(Date date) {
        this.date = date;
    }

    public double getValue() {
        return value;
    }

    public void setValue(double value) {
        this.value = value;
    }

    public void addAccountActivity(AccountActivity activity) {
        // Make sure ordering is maintained, JPA only does this on loading
        int i = 0;
        while (i < getAccountActivity().size()) {
            if (getAccountActivity().get(i).getDate().compareTo(activity.getDate()) <= 0)
                break;
            i++;
        }
        getAccountActivity().add(i, activity);
    }
}

@MappedSuperclass public abstract class AbstractNamedDomain extends AbstractDomain {

    private String name;

    public AbstractNamedDomain() {

    }

    public AbstractNamedDomain(String name) {

        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

@MappedSuperclass public abstract class AbstractDomain implements Serializable {

    @Id @GeneratedValue
    private long id = NEW_ID;

    public static long NEW_ID = -1;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id; 
    }

    public boolean isNew() {

        return id==NEW_ID;
    }
}
4

4 回答 4

18

多亏了 eric 和 Juan Manuel 的回答,我才发现交易没有提交。

将 @Transactional 添加到 storeAccount 方法就可以了!

于 2008-12-17T15:56:19.117 回答
5

我实际上遇到了另一种可能发生这种情况的方式。

在注入的 EntityManager 中,如果您像这样指定 persistence.xml,则不会发生更新:

<persistence-unit name="primary" transaction-type="RESOURCE_LOCAL">

您需要删除事务类型属性并使用默认值 JTA。

于 2012-07-01T23:43:12.230 回答
1

可能您使事务保持活动状态,并且在其他运行支持活动事务的方法结束之前它不会调用“提交”(所有“投票”用于提交,没有“投票”用于回滚。)

如果您确定要保留的实体没问题,您可以这样做:

@TransactionManagement(TransactionManagementType.BEAN)
public class AccountManager implements IAccountManager { ..}

并管理您的实体持久性添加:

@Resource
private SessionContext sessionContext;

public Account storeAccount(Account ac) {
    sessionContext.getUserTransaction().begin();
    ac = em.merge(ac);
    em.persist(ac);
    sessionContext.getUserTransaction().commit();
    return ac;
}
于 2008-12-17T15:34:19.927 回答
1

您不需要显式调用persist 方法。合并操作将在提交时将更改写入数据库。

于 2009-03-05T03:31:07.663 回答