[英]No transactional EntityManager available when Persisting an object
嘗試持久化對象時, 沒有事務性EntityManager可用異常。
我有一個帶有以下配置類的Spring項目:
@Configuration
@ComponentScan
@EnableTransactionManagement
@EnableJpaRepositories
public class SpringConfiguration {
@Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean emf(DataSource dataSource) {
LocalContainerEntityManagerFactoryBean emf =new LocalContainerEntityManagerFactoryBean();
emf.setDataSource(dataSource);
Properties jpaProperties = new Properties();
jpaProperties.put("hibernate.hbm2ddl.auto", "create-drop");
jpaProperties.put("hibernate.show_sql", "true");
emf.setJpaProperties(jpaProperties);
emf.setPackagesToScan(
new String[] {"ds.core.entity"});
emf.setJpaVendorAdapter(
new HibernateJpaVendorAdapter());
return emf;
}
@Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(EntityManagerFactory emf,DataSource dataSource) {
JpaTransactionManager tm =
new JpaTransactionManager();
tm.setEntityManagerFactory(emf);
tm.setDataSource(dataSource);
return tm;
}
和一個實體類:
@Entity
public class Type {
@Id @GeneratedValue
private Long id;
private String name;
}
和Jpa實現類:
@Repository
public class JpaTypeRepo implements TypeRepo {
@PersistenceContext
private EntityManager em;
@Override
public Type insertRecord(Type data) {
em.persist(data);
return data;
}
}
最后是帶有Init()
的服務類:
@Transactional
@Service
public class InitDbService {
@Autowired
private TypeRepo typeRepo;
@PostConstruct
public void init() {
Type type=new Type();
type.setName("newName");
typeRepo.insertRecord(type);
}}
只需將@Transactional批注添加到類:JpaTypeRepo,如下所示:
@Transactional
@Repository
public class JpaTypeRepo implements TypeRepo {
@PersistenceContext
private EntityManager em;
@Override
public Type insertRecord(Type data) {
em.persist(data);
return data;
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.