[英]No transactional EntityManager available when Persisting an object
I have got No transactional EntityManager available exception when I tried to persist an object. 尝试持久化对象时, 没有事务性EntityManager可用异常。
I have a Spring project with the following configuration class: 我有一个带有以下配置类的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;
}
And an entity class: 和一个实体类:
@Entity
public class Type {
@Id @GeneratedValue
private Long id;
private String name;
}
and Jpa implementation class : 和Jpa实现类:
@Repository
public class JpaTypeRepo implements TypeRepo {
@PersistenceContext
private EntityManager em;
@Override
public Type insertRecord(Type data) {
em.persist(data);
return data;
}
}
And finally a Service Class with Init()
: 最后是带有
Init()
的服务类:
@Transactional
@Service
public class InitDbService {
@Autowired
private TypeRepo typeRepo;
@PostConstruct
public void init() {
Type type=new Type();
type.setName("newName");
typeRepo.insertRecord(type);
}}
just add @Transactional annotation to the class :JpaTypeRepo as following: 只需将@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.