持久化对象时没有可用的事务性EntityManager

时间:2015-05-29 21:01:39

标签: java spring jpa persistent

当我试图保留一个对象时,我有没有事务性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 个答案:

答案 0 :(得分:0)

只需在类中添加@Transactional注释:JpaTypeRepo 如下:

@Transactional
@Repository
public class JpaTypeRepo implements TypeRepo {
  @PersistenceContext
  private EntityManager em;
  @Override
  public Type insertRecord(Type data) {
    em.persist(data);
    return data;
  }
}