持久化对象时没有可用的事务性 EntityManager
Posted
技术标签:
【中文标题】持久化对象时没有可用的事务性 EntityManager【英文标题】:No transactional EntityManager available when Persisting an object 【发布时间】:2015-05-29 21:01:39 【问题描述】:当我尝试持久化对象时,没有可用的事务性 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);
【问题讨论】:
【参考方案1】:只需在类中添加@Transactional 注释:JpaTypeRepo 如下:
@Transactional
@Repository
public class JpaTypeRepo implements TypeRepo
@PersistenceContext
private EntityManager em;
@Override
public Type insertRecord(Type data)
em.persist(data);
return data;
【讨论】:
以上是关于持久化对象时没有可用的事务性 EntityManager的主要内容,如果未能解决你的问题,请参考以下文章