解析Spring第四天(Spring中的事物、Spring框架来管理模板类)

  • JDBC模板技术:

    Spring框架中提供了很多持久层的模板类来简化编程,使用模板类编写程序会变的简单

    • template 模板
    • 都是Spring框架提供XxxTemplate

    提供了JDBC模板,Spring框架提供的

    • JdbcTemplate类,Connection 表示连接,管理事务 Statement ResultSet
  • 如何使用JDBC模板类?
  • 在数据库中新增表结构和数据
     1 DROP TABLE IF EXISTS `account`;
     2 CREATE TABLE `account` (
     3   `id` int(11) NOT NULL AUTO_INCREMENT,
     4   `name` varchar(40) DEFAULT NULL,
     5   `money` double DEFAULT NULL,
     6   PRIMARY KEY (`id`)
     7 ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=utf8;
     8 
     9 -- ----------------------------
    10 -- Records of account
    11 -- ----------------------------
    12 INSERT INTO `account` VALUES ('1', 'aaa', '1000');
    13 INSERT INTO `account` VALUES ('2', 'bbb', '1000');
    14 INSERT INTO `account` VALUES ('3', 'ccc', '1000');
    15 INSERT INTO `account` VALUES ('4', '熊大', '700');
    16 INSERT INTO `account` VALUES ('5', '熊二', '1200');
    17 INSERT INTO `account` VALUES ('6', '熊三', '800');
  • 创建一个普通的Maven工程,引入坐标
 1 <dependencies>
 2     <dependency>
 3         <groupId>org.springframework</groupId>
 4         <artifactId>spring-context</artifactId>
 5         <version>5.0.2.RELEASE</version>
 6     </dependency>
 7     <dependency>
 8         <groupId>commons-logging</groupId>
 9         <artifactId>commons-logging</artifactId>
10         <version>1.2</version>
11     </dependency>
12     <dependency>
13         <groupId>log4j</groupId>
14         <artifactId>log4j</artifactId>
15         <version>1.2.12</version>
16     </dependency>
17     <dependency>
18         <groupId>junit</groupId>
19         <artifactId>junit</artifactId>
20         <version>4.12</version>
21     </dependency>
22     <dependency>
23         <groupId>org.springframework</groupId>
24         <artifactId>spring-test</artifactId>
25         <version>5.0.2.RELEASE</version>
26     </dependency>
27     
28     <dependency>
29         <groupId>aopalliance</groupId>
30         <artifactId>aopalliance</artifactId>
31         <version>1.0</version>
32     </dependency>
33     <dependency>
34         <groupId>org.springframework</groupId>
35         <artifactId>spring-aspects</artifactId>
36         <version>5.0.2.RELEASE</version>
37     </dependency>
38     <dependency>
39         <groupId>org.aspectj</groupId>
40         <artifactId>aspectjweaver</artifactId>
41         <version>1.8.13</version>
42     </dependency>
43     <dependency>
44         <groupId>mysql</groupId>
45         <artifactId>mysql-connector-java</artifactId>
46         <version>5.1.6</version>
47     </dependency>
48     <dependency>
49         <groupId>org.springframework</groupId>
50         <artifactId>spring-jdbc</artifactId>
51         <version>5.0.2.RELEASE</version>
52     </dependency>
53     <dependency>
54         <groupId>org.springframework</groupId>
55         <artifactId>spring-tx</artifactId>
56         <version>5.0.2.RELEASE</version>
57     </dependency>
58   </dependencies>
  • 使用Spring框架来管理模板类,Spring管理内置的连接池
     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:context="http://www.springframework.org/schema/context"
     5        xmlns:aop="http://www.springframework.org/schema/aop"
     6        xsi:schemaLocation="
     7                 http://www.springframework.org/schema/beans
     8                 http://www.springframework.org/schema/beans/spring-beans.xsd
     9                 http://www.springframework.org/schema/context
    10                 http://www.springframework.org/schema/context/spring-context.xsd
    11                 http://www.springframework.org/schema/aop
    12                 http://www.springframework.org/schema/aop/spring-aop.xsd">
    13 14     <!--配置连接池-->
    15     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    16         <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    17         <property name="url" value="jdbc:mysql:///spring_db" />
    18         <property name="username" value="root" />
    19         <property name="password" value="root" />
    20     </bean>
    21 22     <!--配置jdbc模板-->
    23     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    24         <property name="dataSource" ref="dataSource" />
    25     </bean>
    26 27 </beans>
  • 测试jdbcTemplate
     
    package cn.tx.test;
    ​
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    ​
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(value = "classpath:applicationContext_jdbc.xml")
    public class Demo1_1 {
    ​
        @Autowired
        private JdbcTemplate jdbcTemplate;
    ​
        /**
         * 测试的方式
         */
        @Test
        public void run1(){
            jdbcTemplate.update("insert into account values (null,?,?)","熊二",500);
        }
    ​
    }
  • Spring框架管理开源的连接池

  • 配置开源的连接池,使用Druid的连接池,引入坐标
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.10</version>
    </dependency>
  • 新建 一个属性文件后缀为.properties。配置连接数据库的基本信息
    1 jdbc.driverClassName=com.mysql.jdbc.Driver
    2     jdbc.url=jdbc:mysql:///spring_db
    3     jdbc.username=root
    4     jdbc.password=root
  • 在xml的文件中配置读取属性文件,连接数据库和配置jdbc模板
     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:context="http://www.springframework.org/schema/context"
     5        xmlns:aop="http://www.springframework.org/schema/aop"
     6        xsi:schemaLocation="
     7                 http://www.springframework.org/schema/beans
     8                 http://www.springframework.org/schema/beans/spring-beans.xsd
     9                 http://www.springframework.org/schema/context
    10                 http://www.springframework.org/schema/context/spring-context.xsd
    11                 http://www.springframework.org/schema/aop
    12                 http://www.springframework.org/schema/aop/spring-aop.xsd">
    13 14     <!--配置连接池,使用的是Spring框架内置的连接池
    15     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    16         <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    17         <property name="url" value="jdbc:mysql:///spring_db" />
    18         <property name="username" value="root" />
    19         <property name="password" value="root" />
    20     </bean>
    21     -->
    22 23     <!--使用开源连接池
    24     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    25         <property name="driverClassName" value="com.mysql.jdbc.Driver" />
    26         <property name="url" value="jdbc:mysql:///spring_db" />
    27         <property name="username" value="root" />
    28         <property name="password" value="root" />
    29     </bean>
    30     -->
    31 32     <!--加载属性文件
    33     <bean id="placeholderConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
    34         <property name="location" value="classpath:jdbc.properties" />
    35     </bean>
    36     -->
    37 38     <!--第二种写法:使用提供标签的方式-->
    39     <context:property-placeholder location="classpath:jdbc.properties" />
    40 41     <!--加载属性的文件-->
    42     <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
    43         <property name="driverClassName" value="${jdbc.driverClassName}" />
    44         <property name="url" value="${jdbc.url}" />
    45         <property name="username" value="${jdbc.username}" />
    46         <property name="password" value="${jdbc.password}" />
    47     </bean>
    48 49     <!--配置jdbc模板-->
    50     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
    51         <property name="dataSource" ref="dataSource" />
    52     </bean>
    53 54 </beans>
  • 对数据的基本操作做测试,增删改查
    package cn.tx.test;
    ​
    import cn.tx.demo1.Account;
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.jdbc.core.RowMapper;
    import org.springframework.test.context.ContextConfiguration;
    import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
    ​
    import java.sql.ResultSet;
    import java.sql.SQLException;
    import java.util.List;
    ​
    
    @RunWith(SpringJUnit4ClassRunner.class)
    @ContextConfiguration(value = "classpath:applicationContext_jdbc.xml")
    public class Demo1_1 {
    ​
        @Autowired
        private JdbcTemplate jdbcTemplate;
    ​
        /**
         * 测试的方式
         */
        @Test
        public void run1(){
            jdbcTemplate.update("insert into account values (null,?,?)","熊四",800);
        }
    ​
        /**
         * 修改
         */
        @Test
        public void run2(){
            jdbcTemplate.update("update account set name = ?,money = ? where id = ?","光头强",100,7);
        }
    ​
        /**
         * 删除
         */
        @Test
        public void run3(){
            jdbcTemplate.update("delete from account where id = ?",7);
        }
    ​
        /**
         * 通过id查询
         */
        @Test
        public void run4(){
            Account account = jdbcTemplate.queryForObject("select * from account where id = ?", new BeanMapper(), 6);
            System.out.println(account);
        }
    ​
        /**
         * 查询所有的数据
         */
        @Test
        public void run5(){
            List<Account> list = jdbcTemplate.query("select * from account", new BeanMapper());
            for (Account account : list) {
                System.out.println(account);
            }
        }
    ​
    }
    ​
    /**
     * 实现类,用来进行数据封装的
     */
    class BeanMapper implements RowMapper<Account>{
    ​
        /**
         * 是一行一行进行数据封装的
         * @param resultSet
         * @param i
         * @return
         * @throws SQLException
         */
        @Override
        public Account mapRow(ResultSet resultSet, int i) throws SQLException {
            Account account = new Account();
            account.setId(resultSet.getInt("id"));
            account.setName(resultSet.getString("name"));
            account.setMoney(resultSet.getDouble("money"));
            return account;
        }
    ​
    }

猜你喜欢

转载自www.cnblogs.com/LBJLAKERS/p/11752615.html