java - hibernate交spring事物托管后插入数据无效,不发送sql语句,不报错,但能查询到数据。
黄舟
黄舟 2017-04-18 09:45:13
0
2
598

hibernate交spring事务托管后插入数据无效,不发送sql语句,不报错,但能查询到数据。
如果手动执行sessionFactory.getCurrentSession().flush()可以立即写入到数据库。
不手动的话无法自动事务提交。
怀疑是spring事务管理没起作用。
(学生党刚学框架,不妥当的地方还请明示)

dao层代码:

public class UserDao implements IUserDao{ private SessionFactory sessionFactory; public SessionFactory getSessionFactory() { return sessionFactory; } public void setSessionFactory(SessionFactory sessionFactory) { this.sessionFactory = sessionFactory; } public boolean addUser(User user) { LogUtil.getLog().info("正在执行user插入操作~"); try { sessionFactory.getCurrentSession().save(user); } catch (Exception e) { LogUtil.getLog().error(e); return false; } return true; }

controller层:

if(code.equals(checkCode)){ if(userDao.addUser(user)){ //将用户信息加进session中 return "redirect:/returnIndex"; }else{ model.addAttribute("message", "系统异常,注册失败!"); return "forward:/user/returnRegiste"; } }else{ model.addAttribute("message", "验证码错误!"); return "forward:/user/returnRegiste"; }

xml配置:

  root  20 100 20 com.mysql.jdbc.Driver jdbc:mysql://localhost:3306/db_shop?useUnicode=true&characterEncoding=UTF-8      edu.hnuc.entity.User      update edu.hnuc.util.UTF8CharacterDialect true                         

文件结构:

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all (2)
PHPzhong

There is no transaction configured in your configuration file, how can it be automatically submitted? You can definitely only submit the transaction manually in the code
The simplest way is this

   

Then add @Transactional on your dao method
Update the answer in the comment

Write like this

    左手右手慢动作

    1. Since springMVC and hibernate are used, why not use spring’s hibernateTemplate?

    2. You configure sessinFactory and transactionManager in your spring configuration file, but your DAO obtains the session from the sessionFactory itself, and there is no relevant transaction control code... I think it is because of this that the transaction is not submitted. It's like if you use a connection pool, but create a connection yourself using JDBCDriver, then the connection pool will definitely not be able to manage this Connection, because it doesn't even know there is such a connection...

    Finally, I give you a suggestion: In the code during the debugging phase, it is better to add e.printStackTrace(), and it is best to add throw e, so that the upstream code knows that there is a problem in this layer. Otherwise, it may be due to human factors. (For example, forgetting to write "LogUtil.getLog().error(e);" or others) causes the exception message to be swallowed. If such an exception occurs, locating the problem will be very cumbersome.

      Latest Downloads
      More>
      Web Effects
      Website Source Code
      Website Materials
      Front End Template
      About us Disclaimer Sitemap
      php.cn:Public welfare online PHP training,Help PHP learners grow quickly!