1
2
3
4
5
6
7
8
9
10
11
12
13
14
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 }