View Javadoc
1   /*
2    *    Copyright 2016-2026 the original author or authors.
3    *
4    *    Licensed under the Apache License, Version 2.0 (the "License");
5    *    you may not use this file except in compliance with the License.
6    *    You may obtain a copy of the License at
7    *
8    *       https://www.apache.org/licenses/LICENSE-2.0
9    *
10   *    Unless required by applicable law or agreed to in writing, software
11   *    distributed under the License is distributed on an "AS IS" BASIS,
12   *    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13   *    See the License for the specific language governing permissions and
14   *    limitations under the License.
15   */
16  package issues.gh324.spring;
17  
18  import java.util.Optional;
19  
20  import org.springframework.beans.factory.annotation.Autowired;
21  import org.springframework.stereotype.Service;
22  import org.springframework.transaction.PlatformTransactionManager;
23  import org.springframework.transaction.TransactionStatus;
24  import org.springframework.transaction.annotation.Propagation;
25  import org.springframework.transaction.annotation.Transactional;
26  import org.springframework.transaction.support.DefaultTransactionDefinition;
27  
28  import issues.gh324.NameRecord;
29  import issues.gh324.NameTableMapper;
30  
31  @Service
32  public class SpringNameService {
33      @Autowired
34      private NameTableMapper mapper;
35      @Autowired
36      private PlatformTransactionManager transactionManager;
37  
38      @Transactional(propagation = Propagation.REQUIRES_NEW)
39      public void insertRecord() {
40          NameRecord row = new NameRecord(1, "Fred");
41          mapper.insert(row);
42      }
43  
44      @Transactional(propagation = Propagation.REQUIRES_NEW)
45      public void updateRecordAndCommit() {
46          NameRecord row = new NameRecord(1, "Barney");
47          mapper.updateByPrimaryKey(row);
48      }
49  
50      public void updateRecordAndRollback() {
51          TransactionStatus txStatus = transactionManager.getTransaction(new DefaultTransactionDefinition());
52          NameRecord row = new NameRecord(1, "Barney");
53          mapper.updateByPrimaryKey(row);
54          transactionManager.rollback(txStatus);
55      }
56  
57      @Transactional(propagation = Propagation.REQUIRES_NEW)
58      public Optional<NameRecord> getRecord() {
59          return mapper.selectByPrimaryKey(1);
60      }
61  
62      @Transactional(propagation = Propagation.REQUIRES_NEW)
63      public void resetDatabase() {
64          mapper.deleteAll();
65      }
66  }