Sto provando a implementare un DAO semplice. Ho un Dao:Spring-Hibernate persist non risulta nell'inserimento
@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;
}
E un'entità:
@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;
}
}
Ecco 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/>`
A meno che io chiamo flush()
dopo persist()
o merge()
l'inserto a non eseguito. Perché è quello? Se rimuovo @Transactional
allora ottengo errore su "nessuna transazione è in corso" su flush, ma se rimuovere svuota nulla inserito nel DB.
ho cambiato il '@ Transactional' false e ancora non c'è inserti. Per quanto riguarda la demarcazione delle transazioni, lo terrò a mente, grazie. Anche rimuovere '@ Transactional' non è stato d'aiuto. – AlexV
@AlexV: sembra strano. Come chiamate questi metodi? – axtavt
Non sai cosa intendi per come chiamo questi metodi. Ho un test unitario in cui chiamo il metodo DAO 'save()'. – AlexV