我正在尝试实现一个简单的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则刷新时会出现“没有正在进行的事务”的错误,但是如果删除刷新,则不会插入到数据库中。
flush()
persist()
merge()
@Transactional
之所以这样工作是因为您使用标记了事务为只读@Transactional(readOnly = true)。
@Transactional(readOnly = true)
如您所见,由于您仍然可以通过flush()手动调用保留更改,因此它不会使您的事务实际上是只读的。但是,它在事务结束时禁用自动刷新,因此,如果没有手动刷新,更改将不会持久。
您需要readOnly从类级别的注释中删除,或在具有方法级别的注释的非只读方法上覆盖它:
readOnly
@Override @Transactional(readOnly = false) public boolean save(User user) { ... }
还要注意,事务划分通常应用于服务层方法,而不是DAO方法。特别是,在编写DAO方法时,您实际上并不知道哪些事务应该是只读的,哪些不是只读的。如以下示例所示,此信息仅在设计服务层时可用:
public class UserService { @Autowired UserDAO dao; @Transactional(readOnly = true) public User getUserById(int id) { return dao.getById(id); // getById() can participate in effectively read-only transaction } @Transactional public void changeUserName(int id, String newName) { User u = dao.getById(id); // Or not u.setName(newName); // Change will be flushed at the end of transaction } }