Сохранение Spring-Hibernate не приводит к вставке

Я пытаюсь реализовать простой DAO. У меня есть Дао:

@Repository("iUserDao")
@Transactional(readOnly = true)
public class UserDao implements IUserDao {
    private EntityManager entityManager;

    @PersistenceContext
    public void setEntityManager(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    @Override
    public User getById(int id) {
        return entityManager.find(User.class, id);
    }

    @Override
    public boolean save(User user) {
        entityManager.persist(user);
        entityManager.flush();
        return true;
    }

    @Override
    public boolean update(User user) {
        entityManager.merge(user);
        entityManager.flush();
        return true;
    }

    @Override
    public boolean delete(User user) {
        user = entityManager.getReference(User.class, user.getId());
        if (user == null)
            return false;
        entityManager.remove(user);
        entityManager.flush();
        return true;
    }

И сущность:

@Entity
@Table(name = "users")
public class User {
    private int id;
    private Date creationDate;

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    public int getId() {
        return id;
    }

    public User() {
    }

    public User(Date creationDate) {
        this.creationDate = creationDate;
    }

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

    public Date getCreationDate() {
        return creationDate;
    }

    public void setCreationDate(Date creationDate) {
        this.creationDate = creationDate;
    }
}

Вот appContext.xml: `

<bean id="entityManagerFactory"
      class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"
      p:dataSource-ref="dataSource" p:jpaVendorAdapter-ref="jpaAdapter"
      p:persistenceUnitName="test">
    <property name="loadTimeWeaver">
        <bean
                class="org.springframework.instrument.classloading.InstrumentationLoadTimeWeaver"/>
    </property>
</bean>

<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"
      p:entityManagerFactory-ref="entityManagerFactory"/>
<bean id="jpaAdapter"
      class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter"
      p:database="MYSQL" p:showSql="true"/>

<bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>
<tx:annotation-driven/>`

Если я не вызываю flush () после persist () или merge () , вставка не выполняется. Это почему? Если я удалю @Transactional , то при сбросе я получаю сообщение об ошибке «транзакция не выполняется», но если удалить, то в БД ничего не вставлено.

6
задан AlexV 2 March 2011 в 14:33
поделиться