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(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 }