0
我用java配置Spring應用:Spring Java配置。交易問題
@Controller
@RequestMapping("/")
public class MainController {
@Inject
@Named("dbDaoService")
IDaoService dbDaoService;
@RequestMapping(value="/saveNoteAsync", method = RequestMethod.POST)
public @ResponseBody String saveNoteAsync(@RequestBody CreateRequest createRequest, HttpServletRequest request) {
Notes newNote = new Notes(
createRequest.getTitle(),
createRequest.getNote(),
tagService.getTagMask(createRequest.getTags())
);
Long newId = dbDaoService.createNotes(newNote);
return ""+newId;
}
}
DBService:
@Service("dbDaoService")
public class DBDaoService implements IDaoService {
@PersistenceContext(unitName = "MyEntityManager")
private EntityManager entityManager;
private List<Tags> tags = null;
@Override
@Transactional
public Long createNotes(Notes data) {
entityManager.persist(data);
return data.getId();
}
}
配置類
@Configuration
@EnableWebMvc
@ComponentScan("ru.mypackage")
public class WebConfig extends WebMvcConfigurerAdapter {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
registry.addResourceHandler("/WEB-INF/views/**").addResourceLocations("/views/");
}
@Bean
public InternalResourceViewResolver getViewResolver() {
InternalResourceViewResolver resolver = new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
resolver.setViewClass(JstlView.class);
return resolver;
}
@Bean
public BasicDataSource getBasicDataSource(){
BasicDataSource bds = new BasicDataSource();
bds.setDriverClassName("com.mysql.jdbc.Driver");
bds.setUrl("jdbc:mysql://localhost:3306/test");
bds.setUsername("root");
bds.setPassword("root");
return bds;
}
@Bean
public HibernateJpaVendorAdapter getHibernateJpaVendorAdapter(){
HibernateJpaVendorAdapter hjva = new HibernateJpaVendorAdapter();
hjva.setShowSql(true);
hjva.setGenerateDdl(true);
hjva.setDatabasePlatform("org.hibernate.dialect.MySQLDialect");
return hjva;
}
@Bean
public LocalContainerEntityManagerFactoryBean getEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setPersistenceUnitName("MyEntityManager");
em.setDataSource(getBasicDataSource());
em.setJpaVendorAdapter(getHibernateJpaVendorAdapter());
em.setPackagesToScan("ru.eastwind.persistance");
return em;
}
@Bean
public HibernateJpaDialect getHibernateJpaDialect(){
return new HibernateJpaDialect();
}
@Bean
public JpaTransactionManager getJpaTransactionManager(){
JpaTransactionManager jtm = new JpaTransactionManager();
jtm.setEntityManagerFactory(getEntityManagerFactory().getObject());
jtm.setJpaDialect(getHibernateJpaDialect());
return jtm;
}
}
在線路entityManager.persist(數據);我得到的錯誤:
javax.persistence.TransactionRequiredException:沒有
但所有選擇查詢沃金的正確的事務EntityManager的!請幫忙。
嘗試連線。 – duffymo
並向我們展示@Configuration類,其中u定義了entitymanager和transactionManager –
添加了配置文件,請參閱更新 – user2611714