View Javadoc
1   /*
2    *    Copyright 2016-2025 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();
41          row.setId(1);
42          row.setName("Fred");
43          mapper.insert(row);
44      }
45  
46      @Transactional(propagation = Propagation.REQUIRES_NEW)
47      public void updateRecordAndCommit() {
48          NameRecord row = new NameRecord();
49          row.setId(1);
50          row.setName("Barney");
51          mapper.updateByPrimaryKey(row);
52      }
53  
54      public void updateRecordAndRollback() {
55          TransactionStatus txStatus = transactionManager.getTransaction(new DefaultTransactionDefinition());
56          NameRecord row = new NameRecord();
57          row.setId(1);
58          row.setName("Barney");
59          mapper.updateByPrimaryKey(row);
60          transactionManager.rollback(txStatus);
61      }
62  
63      @Transactional(propagation = Propagation.REQUIRES_NEW)
64      public Optional<NameRecord> getRecord() {
65          return mapper.selectByPrimaryKey(1);
66      }
67  
68      @Transactional(propagation = Propagation.REQUIRES_NEW)
69      public void resetDatabase() {
70          mapper.deleteAll();
71      }
72  }