我有SpringMVC / Hibernate Web应用程序。当我尝试更新其中一个条目时没有任何反应。
我尝试使用以下代码更新条目:org.hibernate.Session.merge(object)
我没有任何例外。
我启用mysql来记录收到的所有请求,在日志中我发现有更新语句,但在此之后有一个rollback
显然取消了更新。这是mysql日志
168 Query SET sql_mode='STRICT_TRANS_TABLES'
168 Query SET autocommit=0
156 Query SET autocommit=0
156 Query select tasks0_.id as id1_0_0_, tasks0_.assigneeId as assignee7_0_0_, tasks0_.description as descript2_0_0_, tasks0_.dueDate as dueDate3_0_0_, tasks0_.name as name4_0_0_, tasks0_.shortName as shortNam5_0_0_, tasks0_.status as status6_0_0_ from tasks tasks0_ where tasks0_.id=2
156 Query select user0_.id as id1_1_0_, user0_.email as email2_1_0_, user0_.fullName as fullName3_1_0_, user0_.password as password4_1_0_, user0_.username as username5_1_0_ from users user0_ where user0_.id=1
156 Query update tasks set assigneeId=1, description='task1 desc', dueDate='2012-01-01', name='nameaddsaqqq1111111', shortName='task 1 shrt name', status='READY' where id=2
156 Query rollback
156 Query SET autocommit=1
168 Query commit
168 Query SET autocommit=1
我不知道什么可能导致回滚。有没有人有想法?
控制器的代码:
@Controller
public class TaskController {
@Autowired
private TasksService tasksService;
@RequestMapping(value = "/task/update", method = RequestMethod.POST)
public ModelAndView editTask(@Valid Tasks task, BindingResult result) {
if (result.hasErrors()) {
return new ModelAndView("owners/createOrUpdateOwnerForm");
} else {
Tasks t = tasksService.findTaskById(task.getId());
update(task, t);
t.setName("addsaasddsa");
tasksService.update(t);
ModelAndView modelAndView = new ModelAndView("task/editOrCreate");
modelAndView.addObject("task",
tasksService.findTaskById(task.getId()));
return modelAndView;
}
}
服务代码:
public interface TasksService {
public void update(Tasks task);
}
服务实施的代码:
@Transactional
@Service
public class TasksServiceImpl implements TasksService {
@Autowired
TaskDAO taskDao;
@Override
public void update(Tasks task) {
taskDao.updates(task);
}
}
DAO的代码:
public interface TaskDAO {
public void updates(Tasks task);
}
DAO实施代码:
@Repository
public class TaskDAOImpl extends DbDaoImpl<Tasks> implements TaskDAO {
@Override
public void updates(Tasks task) {
update(task);
}
}
DbDaoImpl的代码:
import org.hibernate.SessionFactory;
import org.hibernate.Session;
public abstract class DbDaoImpl<T> implements Dao<T> {
@Autowired
private SessionFactory factory;
protected Session getSession() {
return factory.getCurrentSession();
}
@Override
@SuppressWarnings("unchecked")
public T update(final T entity) {
return (T) getSession().merge(entity);
}
}
public interface Dao<T> extends Serializable {
T update(final T entity);
}
hibernate配置属性:
dataSource.driverClassName=com.mysql.jdbc.Driver
dataSource.url=jdbc\:mysql\://localhost\:3306/qwerty
dataSource.username=root
dataSource.password=root
hibernate.dialect=org.hibernate.dialect.MySQLDialect
JPA配置的代码:
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = { "com.task.tracker.DAO", "my.pack" } /*
* basePackageClasses
* =
* Application
* .
* class
*/)
class JpaConfig implements TransactionManagementConfigurer {
@Value("${dataSource.driverClassName}")
private String driver;
@Value("${dataSource.url}")
private String url;
@Value("${dataSource.username}")
private String username;
@Value("${dataSource.password}")
private String password;
@Value("${hibernate.dialect}")
private String dialect;
private static final String HIBERNATE_CONFIGURATION_FILE = "hibernate.properties";
@Bean
public DataSource configureDataSource() {
DriverManagerDataSource config = new DriverManagerDataSource();
config.setDriverClassName(driver);
config.setUrl(url);
config.setUsername(username);
config.setPassword(password);
config.setConnectionProperties(hibernateConfiguration());
return config;
}
@Bean
public LocalContainerEntityManagerFactoryBean configureEntityManagerFactory() {
LocalContainerEntityManagerFactoryBean entityManagerFactoryBean = new LocalContainerEntityManagerFactoryBean();
entityManagerFactoryBean.setDataSource(configureDataSource());
entityManagerFactoryBean.setPackagesToScan("my.pack",
"com.task.tracker.DAO");
entityManagerFactoryBean
.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Properties jpaProperties = new Properties();
jpaProperties.put(org.hibernate.cfg.Environment.DIALECT, dialect);
entityManagerFactoryBean.setJpaProperties(jpaProperties);
return entityManagerFactoryBean;
}
@Bean
// @Qualifier(value = ComponentName.BEAN_SESSION_FACTORY)
public LocalSessionFactoryBean sessionFactory() {
final LocalSessionFactoryBean localSessionFactoryBean = new LocalSessionFactoryBean();
localSessionFactoryBean
.setHibernateProperties(hibernateConfiguration());
localSessionFactoryBean.setAnnotatedPackages(new String[] { "my.pack",
"com.task.tracker.DAO" });
localSessionFactoryBean.setPackagesToScan("my.pack",
"com.task.tracker.DAO");
return localSessionFactoryBean;
}
/**
* Loads the hibernate properties from the <b>hibernate.properties</b>
* configuration file.
*
* @return The {@link Properties} object holding all hibernate
* configurations.
*/
@Bean
// @Qualifier(value = ComponentName.HIBERNATE_PROPERTIES)
public Properties hibernateConfiguration() {
final ClassLoader loader = Thread.currentThread()
.getContextClassLoader();
final URL url = loader.getResource(HIBERNATE_CONFIGURATION_FILE);
final Properties properties = new Properties();
try {
properties.load(url.openStream());
} catch (IOException ioe) {
System.out.println("sfdsfsdf");
}
return properties;
}
@Bean
public PlatformTransactionManager annotationDrivenTransactionManager() {
return new JpaTransactionManager();
}
@Bean
public org.springframework.orm.hibernate4.HibernateTransactionManager getTransMang() {
org.springframework.orm.hibernate4.HibernateTransactionManager tr = new org.springframework.orm.hibernate4.HibernateTransactionManager(
sessionFactory().getObject());
return tr;
}
}
安全配置的代码:
@Configuration
@EnableWebMvcSecurity
class SecurityConfig extends WebSecurityConfigurerAdapter {
@Bean
public UserService userService() {
return new UserService();
}
@Bean
public TokenBasedRememberMeServices rememberMeServices() {
return new TokenBasedRememberMeServices("remember-me-key",
userService());
}
@Bean
public PasswordEncoder passwordEncoder() {
return new StandardPasswordEncoder();
}
@Override
protected void configure(AuthenticationManagerBuilder auth)
throws Exception {
auth.eraseCredentials(true).userDetailsService(userService());
}
@Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/", "/favicon.ico", "/resources/**", "/signup")
.permitAll().anyRequest().authenticated().and().formLogin()
.loginPage("/signin").permitAll().failureUrl("/signin?error=1")
.loginProcessingUrl("/authenticate").and().logout()
.logoutUrl("/logout").permitAll()
.logoutSuccessUrl("/signin?logout").and().rememberMe()
.rememberMeServices(rememberMeServices())
.key("remember-me-key");
http.csrf().disable();
}
}
应用程序配置:
@Configuration
@ComponentScan(basePackages = { "com.task.tracker.services", "com.task.tracker.DAO.impl" }, excludeFilters = @Filter({
Controller.class, Configuration.class }))
class ApplicationConfig {
@Bean
public static PropertyPlaceholderConfigurer propertyPlaceholderConfigurer() {
PropertyPlaceholderConfigurer ppc = new PropertyPlaceholderConfigurer();
ppc.setLocation(new ClassPathResource("/persistence.properties"));
return ppc;
}
}
答案 0 :(得分:0)
问题在于JpaConfig
我有两个bean返回PlatformTransactionManager
一个返回JpaTransactionManager
而另一个返回HibernateTransactionManager
。解决方案是删除JpaTransactionManager
。
感谢所有评论此问题的人。