一、目录结构

二、代码

1、JdbcConfig

 1 package cn.bijian.config;
 2 
 3 import com.mchange.v2.c3p0.ComboPooledDataSource;
 4 import org.springframework.beans.factory.annotation.Value;
 5 import org.springframework.context.annotation.Bean;
 6 import org.springframework.context.annotation.Configuration;
 7 import org.springframework.context.annotation.Scope;
 8 import org.springframework.jdbc.core.JdbcTemplate;
 9 
10 import javax.sql.DataSource;
11 
12 @Configuration
13 public class JdbcConfig {
14     @Value("${jdbc.driver}")
15     private String driver;
16     @Value("${jdbc.url}")
17     private String url;
18     @Value("${jdbc.username}")
19     private String username;
20     @Value("${jdbc.password}")
21     private String password;
22 
23     @Bean("jdbcTemplate")
24     @Scope("prototype")
25     public JdbcTemplate createJdbcTemplate(DataSource dataSource){
26         return new JdbcTemplate(dataSource);
27     }
28 
29     @Bean("datasource")
30     public DataSource createDataSource(){
31         try{
32             ComboPooledDataSource ds = new ComboPooledDataSource();
33             ds.setDriverClass(driver);
34             ds.setJdbcUrl(url);
35             ds.setUser(username);
36             ds.setPassword(password);
37             return ds;
38         }catch (Exception e){
39             throw new RuntimeException(e);
40         }
41     }
42 }

2、SpringConfiguration

 1 package cn.bijian.config;
 2 
 3 
 4 import org.springframework.context.annotation.*;
 5 import org.springframework.transaction.annotation.EnableTransactionManagement;
 6 
 7 @Configuration
 8 @ComponentScan("cn.bijian")
 9 @PropertySource("classpath:jdbcConfig.properties")
10 @Import({JdbcConfig.class,TransactionConfig.class})
11 @EnableTransactionManagement
12 public class SpringConfiguration {
13 
14 }

3、TransactionConfig

 1 package cn.bijian.config;
 2 
 3 import org.springframework.context.annotation.Bean;
 4 import org.springframework.jdbc.datasource.DataSourceTransactionManager;
 5 import org.springframework.transaction.PlatformTransactionManager;
 6 
 7 import javax.sql.DataSource;
 8 
 9 /*
10     和事务相关的配置类
11  */
12 public class TransactionConfig {
13     @Bean("transactionManager")
14     public PlatformTransactionManager createPlatformTransactionManager(DataSource dataSource){
15         return new DataSourceTransactionManager(dataSource);
16     }
17 }

4、AccountDao

 1 package cn.bijian.dao;
 2 
 3 
 4 import cn.bijian.model.Account;
 5 
 6 import java.util.List;
 7 
 8 public interface AccountDao {
 9     Account findById(Integer id);
10 
11     Account findAccountByName(String name);
12 
13     void updateAccount(Account account);
14 
15     void saveAccount(Account account);
16 
17     void deleteAccount(Integer id);
18 
19     List<Account> findAll();
20 
21     int findOne(Float money);
22 }

5、AccountDaoImpl

 1 package cn.bijian.dao.Impl;
 2 
 3 import cn.bijian.dao.AccountDao;
 4 import cn.bijian.model.Account;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.jdbc.core.BeanPropertyRowMapper;
 7 import org.springframework.jdbc.core.JdbcTemplate;
 8 import org.springframework.stereotype.Repository;
 9 
10 import java.util.List;
11 /*
12     注解配置
13  */
14 @Repository("accountDao")
15 public class AccountDaoImpl implements AccountDao {
16     @Autowired
17     private JdbcTemplate jdbcTemplate;
18 
19 //    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
20 //        this.jdbcTemplate = jdbcTemplate;
21 //    }
22 
23     @Override
24     public Account findById(Integer id) {
25         List<Account> accounts = jdbcTemplate.query("select * from account where id=?", new BeanPropertyRowMapper<Account>(Account.class), id);
26         return accounts.isEmpty()?null:accounts.get(0);
27     }
28 
29     @Override
30     public Account findAccountByName(String name) {
31         List<Account> accounts = jdbcTemplate.query("select * from account where name=?", new BeanPropertyRowMapper<Account>(Account.class), name);
32         if (accounts.isEmpty()){
33             return null;
34         }
35         if (accounts.size()>1){
36             throw new RuntimeException("结果集不唯一");
37         }
38         return accounts.get(0);
39     }
40 
41     @Override
42     public void updateAccount(Account account) {
43         jdbcTemplate.update("update account set name =?, money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
44     }
45 
46     @Override
47     public void saveAccount(Account account) {
48         jdbcTemplate.update("insert into account(name,money) values (?,?)",account.getName(),account.getMoney());
49     }
50 
51     @Override
52     public void deleteAccount(Integer id) {
53         jdbcTemplate.update("delete from account where id = ?",id);
54     }
55 
56     @Override
57     public List<Account> findAll() {
58         List<Account> accounts = jdbcTemplate.query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
59         return accounts;
60     }
61 
62     @Override
63     public int findOne(Float money) {
64         Integer total = jdbcTemplate.queryForObject("select count(*) from account where money>?", Integer.class, money);
65         return total;
66     }
67 }

6、AccountDaoImpl2

 1 package cn.bijian.dao.Impl;
 2 
 3 
 4 import cn.bijian.dao.AccountDao;
 5 import cn.bijian.model.Account;
 6 import org.springframework.jdbc.core.BeanPropertyRowMapper;
 7 import org.springframework.jdbc.core.support.JdbcDaoSupport;
 8 import org.springframework.stereotype.Repository;
 9 
10 import java.util.List;
11 
12 /*
13     xml配置
14  */
15 
16 public class AccountDaoImpl2 extends JdbcDaoSupport implements AccountDao {
17 
18     @Override
19     public Account findById(Integer id) {
20         List<Account> accounts = getJdbcTemplate().query("select * from account where id=?", new BeanPropertyRowMapper<Account>(Account.class), id);
21         return accounts.isEmpty()?null:accounts.get(0);
22     }
23 
24     @Override
25     public Account findAccountByName(String name) {
26         List<Account> accounts = getJdbcTemplate().query("select * from account where name=?", new BeanPropertyRowMapper<Account>(Account.class), name);
27         if (accounts.isEmpty()){
28             return null;
29         }
30         if (accounts.size()>1){
31             throw new RuntimeException("结果集不唯一");
32         }
33         return accounts.get(0);
34     }
35 
36     @Override
37     public void updateAccount(Account account) {
38         getJdbcTemplate().update("update account set name =?, money = ? where id = ?",account.getName(),account.getMoney(),account.getId());
39     }
40 
41     @Override
42     public void saveAccount(Account account) {
43         getJdbcTemplate().update("insert into account(name,money) values (?,?)",account.getName(),account.getMoney());
44     }
45 
46     @Override
47     public void deleteAccount(Integer id) {
48         getJdbcTemplate().update("delete from account where id = ?",id);
49     }
50 
51     @Override
52     public List<Account> findAll() {
53         List<Account> accounts = getJdbcTemplate().query("select * from account", new BeanPropertyRowMapper<Account>(Account.class));
54         return accounts;
55     }
56 
57     @Override
58     public int findOne(Float money) {
59         Integer total = getJdbcTemplate().queryForObject("select count(*) from account where money>?", Integer.class, money);
60         return total;
61     }
62 
63 }

7、Account

 1 package cn.bijian.model;
 2 
 3 import java.io.Serializable;
 4 
 5 public class Account implements Serializable {
 6     private Integer id;
 7     private String name;
 8     private Float money;
 9 
10     public Integer getId() {
11         return id;
12     }
13 
14     public void setId(Integer id) {
15         this.id = id;
16     }
17 
18     public String getName() {
19         return name;
20     }
21 
22     public void setName(String name) {
23         this.name = name;
24     }
25 
26     public Float getMoney() {
27         return money;
28     }
29 
30     public void setMoney(Float money) {
31         this.money = money;
32     }
33 
34     @Override
35     public String toString() {
36         return "Account{" +
37                 "id=" + id +
38                 ", name='" + name + '\'' +
39                 ", money=" + money +
40                 '}';
41     }
42 }

8、AccountService

 1 package cn.bijian.service;
 2 
 3 
 4 
 5 import cn.bijian.model.Account;
 6 
 7 import java.util.List;
 8 
 9 public interface AccountService {
10 
11     Account findById(Integer id);
12 
13     Account findAccountByName(String name);
14 
15     void updateAccount(Account account);
16 
17     void saveAccount(Account account);
18 
19     void deleteAccount(Integer id);
20 
21     List<Account> findAll();
22 
23     int findOne(Float money);
24 
25     public void transfer(String sourceName, String targetName, Float money);
26 }

9、AccountServiceImpl

 1 package cn.bijian.service.impl;
 2 
 3 
 4 import cn.bijian.dao.AccountDao;
 5 import cn.bijian.dao.Impl.AccountDaoImpl;
 6 import cn.bijian.dao.Impl.AccountDaoImpl2;
 7 import cn.bijian.model.Account;
 8 import cn.bijian.service.AccountService;
 9 import org.springframework.beans.factory.annotation.Autowired;
10 import org.springframework.stereotype.Service;
11 import org.springframework.transaction.annotation.Transactional;
12 
13 import java.util.List;
14 @Service("accountService")
15 @Transactional  //尽量选择xml的配置方式
16 public class AccountServiceImpl implements AccountService {
17     @Autowired
18     private AccountDao accountDao = new AccountDaoImpl();
19 //    private AccountDao accountDao = new AccountDaoImpl2();
20 
21 //    public void setAccountDao(AccountDao accountDao) {
22 //        this.accountDao = accountDao;
23 //    }
24 
25     @Override
26     public Account findById(Integer id) {
27         return accountDao.findById(id);
28     }
29 
30     @Override
31     public Account findAccountByName(String name) {
32         return accountDao.findAccountByName(name);
33     }
34 
35     @Override
36     public void updateAccount(Account account) {
37         accountDao.updateAccount(account);
38     }
39 
40     @Override
41     public void saveAccount(Account account) {
42         accountDao.saveAccount(account);
43     }
44 
45     @Override
46     public void deleteAccount(Integer id) {
47         accountDao.deleteAccount(id);
48     }
49 
50     @Override
51     public List<Account> findAll() {
52         return accountDao.findAll();
53     }
54 
55     @Override
56     public int findOne(Float money) {
57         return accountDao.findOne(money);
58     }
59 
60     @Override
61     public void transfer(String sourceName, String targetName, Float money) {
62         System.out.println("transfer开始执行!");
63         Account source = accountDao.findAccountByName(sourceName);
64         Account target = accountDao.findAccountByName(targetName);
65         source.setMoney(source.getMoney() - money);
66         target.setMoney(target.getMoney() + money);
67         accountDao.updateAccount(source);
68 //        int i = 1/0;
69         accountDao.updateAccount(target);
70     }
71 }

10、bean.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <beans xmlns="http://www.springframework.org/schema/beans"
 3        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 4        xmlns:aop="http://www.springframework.org/schema/aop"
 5        xmlns:tx="http://www.springframework.org/schema/tx"
 6        xmlns:context="http://www.springframework.org/schema/context"
 7        xsi:schemaLocation="
 8         http://www.springframework.org/schema/beans
 9         http://www.springframework.org/schema/beans/spring-beans.xsd
10         http://www.springframework.org/schema/tx
11         http://www.springframework.org/schema/tx/spring-tx.xsd
12         http://www.springframework.org/schema/aop
13         http://www.springframework.org/schema/aop/spring-aop.xsd
14         http://www.springframework.org/schema/context
15         http://www.springframework.org/schema/context/spring-context.xsd">
16 
17 
18 <!--    <bean id="accountDao" class="cn.bijian.dao.Impl.AccountDaoImpl">-->
19 <!--        <property name="jdbcTemplate" ref="jdbcTemplate"></property>-->
20 <!--    </bean>-->
21 
22 <!--    <bean id="accountDao" class="cn.bijian.dao.Impl.AccountDaoImpl2">-->
23 <!--        <property name="dataSource" ref="dataSource"></property>-->
24 <!--    </bean>-->
25 
26 <!--    <bean id="accountService" class="cn.bijian.service.impl.AccountServiceImpl">-->
27 <!--        <property name="accountDao" ref="accountDao"></property>-->
28 <!--    </bean>-->
29 
30 <!--    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">-->
31 <!--        <property name="dataSource" ref="dataSource"></property>-->
32 <!--    </bean>-->
33 
34 <!--    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">-->
35 <!--        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>-->
36 <!--        <property name="url" value="jdbc:mysql://localhost:3306/spring?serverTimezone=UTC"></property>-->
37 <!--        <property name="username" value="root"></property>-->
38 <!--        <property name="password" value="123456"></property>-->
39 <!--    </bean>-->
40 
41 <!--    &lt;!&ndash;第一步:配置事务管理器&ndash;&gt;-->
42 <!--    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">-->
43 <!--        <property name="dataSource" ref="dataSource"></property>-->
44 <!--    </bean>-->
45 <!--    &lt;!&ndash;第二步:配置事务的通知引用事务管理器&ndash;&gt;-->
46 <!--    <tx:advice id="txAdvice" transaction-manager="transactionManager">-->
47 <!--        &lt;!&ndash;第三步:配置事务的属性-->
48 <!--        read-only:是否是只读事务。默认false,不只读。-->
49 <!--        isolation:指定事务的隔离级别。默认值是使用数据库的默认隔离级别。-->
50 <!--        propagation:指定事务的传播行为。-->
51 <!--        timeout:指定超时时间。默认值为:-1。永不超时。-->
52 <!--        rollback-for:用于指定一个异常,当执行产生该异常时,事务回滚。产生其他异常,事务不回滚。没有默认值,任何异常都回滚。-->
53 <!--        no-rollback-for:用于指定一个异常,当产生该异常时,事务不回滚,产生其他异常时,事务回滚。没有默认值,任何异常都回滚。&ndash;&gt;-->
54 <!--        <tx:attributes>-->
55 <!--            <tx:method name="transfer" propagation="REQUIRED" read-only="false"/>-->
56 <!--            <tx:method name="find*" propagation="SUPPORTS" read-only="true"/>-->
57 <!--        </tx:attributes>-->
58 <!--    </tx:advice>-->
59 <!--    &lt;!&ndash;第四步:配置AOP切入点表达式&ndash;&gt;-->
60 <!--    <aop:config>-->
61 <!--        <aop:pointcut id="pt" expression="execution(* cn.bijian.service.impl.*.*(..))"/>-->
62 <!--        &lt;!&ndash;第五步:配置切入点表达式和事务通知的对应关系&ndash;&gt;-->
63 <!--        <aop:advisor advice-ref="txAdvice" pointcut-ref="pt"></aop:advisor>-->
64 <!--    </aop:config>-->
65 
66     <!--!!!!!!!!!!!!!!!!!!注解!!!!!!!!!!!!!!!!!!!-->
67     <context:component-scan base-package="cn.bijian"></context:component-scan>
68 
69     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
70         <property name="dataSource" ref="dataSource"></property>
71     </bean>
72 
73     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
74         <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"></property>
75         <property name="url" value="jdbc:mysql://localhost:3306/spring?serverTimezone=UTC"></property>
76         <property name="username" value="root"></property>
77         <property name="password" value="123456"></property>
78     </bean>
79 
80     <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
81         <property name="dataSource" ref="dataSource"></property>
82     </bean>
83 
84     <!--开启spring对注解事务的支持-->
85     <tx:annotation-driven transaction-manager="transactionManager"></tx:annotation-driven>
86 
87 
88 </beans>

11、JdbcConfig.properties

1 jdbc.driver = com.mysql.cj.jdbc.Driver
2 jdbc.url = jdbc:mysql://localhost:3306/spring?serverTimezone=UTC
3 jdbc.username = root
4 jdbc.password = 123456

12、AccountServiceTest

 1 package cn.bijian;
 2 
 3 import cn.bijian.config.SpringConfiguration;
 4 import cn.bijian.model.Account;
 5 import cn.bijian.service.AccountService;
 6 import org.junit.Test;
 7 import org.junit.runner.RunWith;
 8 import org.springframework.beans.factory.annotation.Autowired;
 9 import org.springframework.test.context.ContextConfiguration;
10 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
11 
12 import java.util.List;
13 
14 @RunWith(SpringJUnit4ClassRunner.class)
15 //@ContextConfiguration(locations = "classpath:bean.xml")
16 @ContextConfiguration(classes = SpringConfiguration.class)
17 public class AccountServiceTest {
18     @Autowired
19     private AccountService accountService;
20 
21     @Test
22     public void testFindById(){
23         Account account = accountService.findById(1);
24         System.out.println(account);
25     }
26 
27     @Test
28     public void testFindAccountByName(){
29         Account account = accountService.findAccountByName("aaa");
30         System.out.println(account);
31     }
32 
33     @Test
34     public void testUpdateAccount(){
35         Account account = accountService.findById(14);
36         account.setName("dddd");
37         accountService.updateAccount(account);
38     }
39 
40     @Test
41     public void testSaveAccount(){
42         Account account = new Account();
43         account.setName("ddd");
44         account.setMoney(1200f);
45         accountService.saveAccount(account);
46     }
47 
48     @Test
49     public void testDeleteAccount(){
50         accountService.deleteAccount(14);
51     }
52 
53     @Test
54     public void testFindAll(){
55         List<Account> accounts = accountService.findAll();
56         for (Account account:accounts) {
57             System.out.println(account);
58         }
59     }
60 
61     @Test
62     public void testFindOne(){
63         int total = accountService.findOne(800f);
64         System.out.println(total);
65     }
66 
67     @Test
68     public void testTransfer(){
69         accountService.transfer("aaa","bbb",100f);
70     }
71 }

13、pom.xml

  1 <?xml version="1.0" encoding="UTF-8"?>
  2 
  3 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  4   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  5   <modelVersion>4.0.0</modelVersion>
  6 
  7   <groupId>cn.bijian</groupId>
  8   <artifactId>Spring_review_5</artifactId>
  9   <version>1.0-SNAPSHOT</version>
 10 
 11   <properties>
 12     <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
 13     <maven.compiler.source>1.7</maven.compiler.source>
 14     <maven.compiler.target>1.7</maven.compiler.target>
 15   </properties>
 16 
 17   <dependencies>
 18     <dependency>
 19       <groupId>org.mybatis</groupId>
 20       <artifactId>mybatis</artifactId>
 21       <version>3.5.6</version>
 22     </dependency>
 23 
 24     <dependency>
 25       <groupId>mysql</groupId>
 26       <artifactId>mysql-connector-java</artifactId>
 27       <version>8.0.21</version>
 28     </dependency>
 29 
 30     <dependency>
 31       <groupId>log4j</groupId>
 32       <artifactId>log4j</artifactId>
 33       <version>1.2.17</version>
 34     </dependency>
 35 
 36     <dependency>
 37       <groupId>junit</groupId>
 38       <artifactId>junit</artifactId>
 39       <version>4.12</version>
 40       <scope>test</scope>
 41     </dependency>
 42 
 43     <dependency>
 44       <groupId>org.apache.tomcat.maven</groupId>
 45       <artifactId>tomcat7-maven-plugin</artifactId>
 46       <version>2.2</version>
 47     </dependency>
 48 
 49     <dependency>
 50       <groupId>org.slf4j</groupId>
 51       <artifactId>slf4j-log4j12</artifactId>
 52       <version>1.6.6</version>
 53     </dependency>
 54 
 55     <dependency>
 56       <groupId>dom4j</groupId>
 57       <artifactId>dom4j</artifactId>
 58       <version>1.6.1</version>
 59     </dependency>
 60 
 61     <dependency>
 62       <groupId>jaxen</groupId>
 63       <artifactId>jaxen</artifactId>
 64       <version>1.1.6</version>
 65     </dependency>
 66 
 67     <dependency>
 68       <groupId>org.springframework</groupId>
 69       <artifactId>spring-context</artifactId>
 70       <version>5.0.3.RELEASE</version>
 71     </dependency>
 72 
 73     <dependency>
 74       <groupId>c3p0</groupId>
 75       <artifactId>c3p0</artifactId>
 76       <version>0.9.1.2</version>
 77     </dependency>
 78 
 79     <dependency>
 80       <groupId>commons-dbutils</groupId>
 81       <artifactId>commons-dbutils</artifactId>
 82       <version>1.7</version>
 83     </dependency>
 84 
 85     <dependency>
 86       <groupId>org.springframework</groupId>
 87       <artifactId>spring-test</artifactId>
 88       <version>5.0.2.RELEASE</version>
 89     </dependency>
 90 
 91     <dependency>
 92       <groupId>org.springframework</groupId>
 93       <artifactId>spring-aop</artifactId>
 94       <version>5.0.3.RELEASE</version>
 95     </dependency>
 96 
 97     <dependency>
 98       <groupId>org.springframework</groupId>
 99       <artifactId>spring-core</artifactId>
100       <version>5.0.3.RELEASE</version>
101     </dependency>
102 
103     <dependency>
104       <groupId>org.aspectj</groupId>
105       <artifactId>aspectjweaver</artifactId>
106       <version>1.8.9</version>
107     </dependency>
108 
109     <dependency>
110       <groupId>org.springframework</groupId>
111       <artifactId>spring-jdbc</artifactId>
112       <version>5.0.3.RELEASE</version>
113     </dependency>
114 
115     <dependency>
116       <groupId>org.springframework</groupId>
117       <artifactId>spring-tx</artifactId>
118       <version>5.0.3.RELEASE</version>
119     </dependency>
120   </dependencies>
121 
122 </project>

 

posted on 2021-11-01 22:22  晨曦生辉耀匕尖  阅读(104)  评论(0编辑  收藏  举报