Java进阶知识24 Spring对JDBC的支持

1、最主要的代码  

Spring 配置文件(beans.xml)

 1     <!-- 连接池 -->
 2     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
 3         <!-- 注册驱动 -->
 4         <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
 5         <!-- 数据库连接 -->
 6         <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/school"></property>
 7         <!-- 用户 -->
 8         <property name="user" value="root"></property>
 9         <!-- 密码 -->
10         <property name="password" value="123456"></property>
11         <!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 --> 
12         <property name="initialPoolSize" value="3"></property>
13         <!--连接池中保留的最大连接数。Default: 15 -->
14         <property name="maxPoolSize" value="100"></property>
15         <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
16           属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
17          如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
18         <property name="maxStatements" value="200"></property>
19         <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
20         <property name="acquireIncrement" value="2"></property>
21     </bean>
22 
23     <!-- Spring提供的,用来代替JDBC连接数据库等操作 -->
24     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
25         <property name="dataSource" ref="dataSource"></property>
26     </bean>
27     
28     <!-- Dao层 -->
29     <bean id="userDao" class="com.shore.dao.impl.UserDao">
30         <!-- jdbcTemplate:Spring提供的,用来 在做CRUD操作时,替代打开/获取连接等等(Connection、Statement、ResultSet),固定步骤 -->
31         <property name="jdbcTemplate" ref="jdbcTemplate"></property>
32     </bean>

2、完整代码例子  

我用到的jar包:

    

实例演示:

数据库建表语句

1 create database school; -- 创建数据库
2 use school; -- 使用school数据库
3 4 create table user( -- 创建user表 5 id int(4) primary key auto_increment, 6 name varchar(20) not null, 7 age int(4) not null 8 );

User 实体类

 1 package com.shore.entity;
 2 
 3 /**
 4  * @author DSHORE/2019-11-9
 5  * 
 6  */
 7 public class User {
 8     private Integer id;
 9     private String name;
10     private Integer age;
11 
12     public Integer getId() {
13         return id;
14     }
15     public void setId(Integer id) {
16         this.id = id;
17     }
18 
19     public String getName() {
20         return name;
21     }
22     public void setName(String name) {
23         this.name = name;
24     }
25 
26     public Integer getAge() {
27         return age;
28     }
29     public void setAge(Integer age) {
30         this.age = age;
31     }
32 }

IUserDao 接口类

 1 package com.shore.dao;
 2 
 3 import java.util.List;
 4 
 5 import com.shore.entity.User;
 6 
 7 /**
 8  * @author DSHORE/2019-11-9
 9  * 
10  */
11 public interface IUserDao {
12     
13     public void save(User user);//
14     public void delete(Integer id);//
15     public void update(User user);//
16     public User findById(Integer id);//根据id查询
17     public List<User> listAll();//查询所有
18 }

UserDao 接口实现类

 1 package com.shore.dao.impl;
 2 
 3 import java.sql.ResultSet;
 4 import java.sql.SQLException;
 5 import java.util.List;
 6 
 7 import org.springframework.jdbc.core.JdbcTemplate;
 8 import org.springframework.jdbc.core.RowMapper;
 9 
10 import com.shore.dao.IUserDao;
11 import com.shore.entity.User;
12 
13 /**
14  * @author DSHORE/2019-11-9
15  *
16  */
17 public class UserDao implements IUserDao {
18     //注入jdbcTemplate(Spring提供的)
19     private JdbcTemplate jdbcTemplate;
20     public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
21         this.jdbcTemplate = jdbcTemplate;
22     }
23     
24     @Override  //添加
25     public void save(User user) {
26         String sql = "insert into user(name,age) values(?,?)";
27         jdbcTemplate.update(sql, user.getName(),user.getAge());
28     }
29 
30     @Override  //删除
31     public void delete(Integer id) {
32         jdbcTemplate.update("delete from user where id = ?", id);
33     }
34 
35     @Override  //修改
36     public void update(User user) {
37         String sql = "update user set age = ? where id = ?";
38         jdbcTemplate.update(sql, user.getAge(), user.getId());
39     }
40 
41     @Override  //根据id查询
42     public User findById(Integer id) {
43         String sql = "select * from user where id=?";
44         List<User> list = jdbcTemplate.query(sql, new MyResult(), id);
45         if (list != null && list.size() > 0) {
46             return list.get(0);
47         }
48         return null;
49     }
50 
51     @Override  //查询所有
52     public List<User> listAll() {
53         String sql = "select * from user";
54         List<User> list = jdbcTemplate.query(sql, new MyResult());
55         return list;
56     }
57 
58     //内部类     此处的作用:把findById()和listAll()的公共部分代码提出来
59     class MyResult implements RowMapper<User>{
60         @Override
61         // 要把每一行封装成一个User对象
62         public User mapRow(ResultSet rs, int rowNum) throws SQLException {
63             User user = new User();
64             user.setId(rs.getInt("id"));
65             user.setName(rs.getString("name"));
66                 return user;
67         }
68     }
69 }

Spring 配置文件(beans.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     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/tx
10        http://www.springframework.org/schema/tx/spring-tx.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="com.mchange.v2.c3p0.ComboPooledDataSource">
16         <!-- 注册驱动 -->
17         <property name="driverClass" value="com.mysql.jdbc.Driver"></property>
18         <!-- 数据库连接 -->
19         <property name="jdbcUrl" value="jdbc:mysql://localhost:3306/school"></property>
20         <!-- 用户 -->
21         <property name="user" value="root"></property>
22         <!-- 密码 -->
23         <property name="password" value="root"></property>
24         <!--初始化时获取三个连接,取值应在minPoolSize与maxPoolSize之间。Default: 3 --> 
25         <property name="initialPoolSize" value="3"></property>
26         <!--连接池中保留的最大连接数。Default: 15 -->
27         <property name="maxPoolSize" value="100"></property>
28         <!--JDBC的标准参数,用以控制数据源内加载的PreparedStatements数量。但由于预缓存的statements
29           属于单个connection而不是整个连接池。所以设置这个参数需要考虑到多方面的因素。
30          如果maxStatements与maxStatementsPerConnection均为0,则缓存被关闭。Default: 0-->
31         <property name="maxStatements" value="200"></property>
32         <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。Default: 3 -->
33         <property name="acquireIncrement" value="2"></property>
34     </bean>
35 
36     <!-- Spring提供的,用来代替JDBC连接数据库等操作 -->
37     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
38         <property name="dataSource" ref="dataSource"></property>
39     </bean>
40     
41     <!-- Dao层 -->
42     <bean id="userDao" class="com.shore.dao.impl.UserDao">
43         <!-- jdbcTemplate:Spring提供的,用来 在做CRUD操作时,替代打开/获取连接等等(Connection、Statement、ResultSet),固定步骤 -->
44         <property name="jdbcTemplate" ref="jdbcTemplate"></property>
45     </bean>
46 </beans>

测试类

 1 package com.shore.test;
 2 
 3 import java.util.List;
 4 
 5 import org.junit.Test;
 6 import org.springframework.context.ApplicationContext;
 7 import org.springframework.context.support.ClassPathXmlApplicationContext;
 8 
 9 import com.shore.dao.IUserDao;
10 import com.shore.entity.User;
11 
12 /**
13  * @author DSHORE/2019-11-9
14  *
15  */
16 public class MyTest {
17     
18     private static ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
19     
20     @Test  //添加
21     public void testSaveUser() {
22         User user = new User();
23         user.setName("李四");//插入两条数据:张三,18 和 李四,20
24         user.setAge(20);
25         IUserDao userDao = (IUserDao) context.getBean("userDao");
26         userDao.save(user);
27     }
28     
29     @Test  //删除
30     public void testDelete() {
31         IUserDao userDao = (IUserDao) context.getBean("userDao");
32         userDao.delete(3);
33     }
34     
35     @Test  //修改
36     public void testUpdate() {
37         IUserDao userDao = (IUserDao) context.getBean("userDao");
38         User user = userDao.findById(2);
39         user.setAge(26);
40         userDao.update(user);
41     }
42     
43     @Test  //根据id查询
44     public void testFindById() {
45         IUserDao userDao = (IUserDao) context.getBean("userDao");
46         User user = userDao.findById(2);
47         System.out.println(user); //返回值:com.shore.entity.User@7df1bd98
48     }
49     
50     @Test  //查询所有
51     public void testListAll() {
52         IUserDao userDao = (IUserDao) context.getBean("userDao");
53         List<User> users = userDao.listAll();
54         System.out.println(users); //返回值:[com.shore.entity.User@58ca3783, com.shore.entity.User@4402a6ff]
55     }
56 }

以上代码,均测试成功。

 

 

 

 

 

 

原创作者:DSHORE

作者主页:http://www.cnblogs.com/dshore123/

原文出自:https://www.cnblogs.com/dshore123/p/11827880.html

欢迎转载,转载务必说明出处。(如果本文对您有帮助,可以点击一下右下角的 推荐,或评论,谢谢!

posted @ 2019-11-09 21:05  DSHORE  阅读(258)  评论(0编辑  收藏  举报