首页 文章

spring mybatis事务被提交

提问于
浏览
0

我正在尝试使用mybatis spring事务管理我的问题是即使抛出异常,事务也会被提交 . 对此相对较新,非常感谢任何帮助 . 以下是代码片段

spring xml配置

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">

        <property name="location">

            <value>classpath:Config.properties</value>

        </property>

    </bean>
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
     <property name="driverClassName" value="${db.driver}"/>
    <property name="url" value="${db.url}"/>
    <property name="username" value="${db.user}"/>
    <property name="password" value="${db.pass}"/>
    <property name="defaultAutoCommit" value="false" />
    </bean>



     <bean id="transactionManager"      class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>


  <tx:annotation-driven transaction-manager="transactionManager" />


<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:Configuration.xml" />
        <property name="dataSource" ref="dataSource" />
    </bean>

    <bean class="org.mybatis.spring.SqlSessionTemplate" id="sqlSessionTemplate">
        <constructor-arg ref="sqlSessionFactory"/>
   </bean>

服务类

@Transactional(rollbackFor=Exception.class, propagation=Propagation.REQUIRED)
public void insertNotes(String noteTypeId,String confidentialValue,String summaryValue,String notes ,String notesId,String noteTypeValue,
        String claimNumber,String notepadId,String mode)
{


        NotepadExample notepadExample= new NotepadExample();

        //to be moved into dao class marked with transaction boundaries
        Notepad notepad = new Notepad();
        notepad.setAddDate(new Date());
        notepad.setAddUser("DummyUser");
        if("true".equalsIgnoreCase(confidentialValue))
            confidentialValue="Y";
        else
            confidentialValue="N";
        notepad.setConfidentiality(confidentialValue);
        Long coverageId=getCoverageId(claimNumber);
        notepad.setCoverageId(coverageId);
        notepad.setDescription(summaryValue);

        notepad.setEditUser("DmyEditUsr");
        //notepad.setNotepadId(new Long(4)); //auto sequencing
        System.out.println(notes);
        notepad.setNotes(notes);
        notepad.setNoteType(noteTypeValue); //Do we really need this?
        notepad.setNoteTypeId(Long.parseLong(notesId));
        if("update".equalsIgnoreCase(mode))
        {
            notepad.setNotepadId(new Long(notepadId));
            notepad.setEditDate(new Date());
            notepadMapper.updateByPrimaryKeyWithBLOBs(notepad);

        }
        else
            notepadMapper.insertSelective(notepad);

              throw new java.lang.UnsupportedOperationException();





}

不知道我哪里错了...

当前呼叫来自控制器,如下所示

@Controller
public class NotesController {

    private static final Logger logger = LoggerFactory
            .getLogger(NotesController.class);

    @Autowired
    private Utils utility;

    @Autowired
     NotepadService notepadService;


    public  @ResponseBody List<? extends Object> insertNotes(HttpServletRequest request,
        HttpServletResponse response,@RequestParam("noteTypeValue") String noteTypeId,
    @RequestParam("confidentialValue")String confidentialValue,
    @RequestParam("summaryValue")String summaryValue,
    @RequestParam("notes")String notes ,
    @RequestParam("notesId")String notesId,
    @RequestParam("noteTypeValue")String noteTypeValue,
    @RequestParam("claimNumber")String claimNumber,
    @RequestParam("notepadId")String notepadId,
    @RequestParam("mode")String mode) {

        try {
            notepadService.insertNotes(noteTypeId, confidentialValue, summaryValue, notes, notesId, noteTypeValue, claimNumber, notepadId, mode);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;  
    }
}

2 回答

  • 1

    您可以尝试使用事务模板 . 从方法中删除@Tranasactional注释,并将代码移到xml文件中 .

    <bean id="trTemplate" class="org.springframework.transaction.support.TransactionTemplate">
    <property name="timeout" value="30"/>
    <property name="transactionManager" ref="transactionManager"/>
    </bean>
    

    创建Trasactiontemplate的对象并从控制器调用insertNotes,如下所示

    @Autowired
    private TransactionTemplate transactionTemplate;
    
    transactionTemplate.execute(new TransactionCallbackWithoutResult() {
    
            @Override
            protected void doInTransactionWithoutResult(TransactionStatus transactionStatus)  {
    
    
                try {
                    insertNotes();
                } catch (Exception e) {
                    transactionStatus.setRollbackOnly();
                    logger.error("Exception ocurred when calling insertNotes", e);  
    
                    throw new RuntimeException(e);
                }
            }
        });
    

    注意:在调用insertNotes方法之前,必须使所有参数都为final

  • 0

    我遇到过同样的问题 . Spring 天我也比较新 . 但据我说,这取决于你如何调用insertNotes()方法 . 如果你从另一个本地方法调用它,那么它将无法工作,因为spring无法知道它被调用并启动事务 .

    如果您通过使用包含insertNotes()方法的类的自动对象从另一个类的方法调用它,那么它应该工作 .

    例如

    class ABC
    {
     @Autowired
     NotesClass notes;
    
       public void testMethod() {
          notes.insertNotes();
       }
    }
    
    
    class NotesClass
    {
       @Transactional(rollbackFor=Exception.class, propagation=Propagation.REQUIRED)  
       public void insertNotes(String noteTypeId,
                               String confidentialValue,
                               String summaryValue,String notes ,
                               String notesId,String noteTypeValue, 
                               String claimNumber,
                               String notepadId,
                               String mode) {
                    //Your code
       }
    }
    

相关问题