Spring JDBC实现查询

Posted noaman_wgs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring JDBC实现查询相关的知识,希望对你有一定的参考价值。

1 db.properties

1 jdbc.user=root
2 jdbc.password=920614
3 jdbc.driverClass=com.mysql.jdbc.Driver
4 jdbc.jdbcUrl=jdbc:mysql:///spring?useUnicode=true&characterEncoding=utf-8
5 
6 jdbc.initPoolSize=5
7 jdbc.maxPoolSize=10

2 applicationContext.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:c="http://www.springframework.org/schema/c"
 6     xmlns:context="http://www.springframework.org/schema/context"
 7     xmlns:jdbc="http://www.springframework.org/schema/jdbc"
 8     xmlns:p="http://www.springframework.org/schema/p"
 9     xmlns:tx="http://www.springframework.org/schema/tx"
10     xmlns:util="http://www.springframework.org/schema/util"
11     xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
12         http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
13         http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
14         http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-4.0.xsd
15         http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
16         http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
17 
18 
19     <context:component-scan base-package="com.spring.jdbc"></context:component-scan>
20     <!-- 导入资源文件 -->
21     <context:property-placeholder location="classpath:db.properties"/>
22     <!-- 配置C3P0数据源 -->
23     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
24         <property name="user" value="${jdbc.user}"></property>
25         <property name="password" value="${jdbc.password}"></property>
26         <property name="driverClass" value="${jdbc.driverClass}"></property>
27         <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property>
28         
29         <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
30         <property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property>
31         
32     </bean>
33     
34     <!-- 配置Spring的JdbcTemplate -->
35     <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
36         <property name="dataSource" ref="dataSource"></property>
37     </bean>
38     
39     <!-- 配置 NamedParameterJdbcTemplate, 
40         该对象可以使用具名参数, 其没有无参数的构造器, 所以必须为其构造器指定参数 -->
41     <bean id="namedParameterJdbcTemplate" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
42         <constructor-arg ref="dataSource"></constructor-arg>
43     </bean>
44     
45     <!-- 配置事务管理器 -->
46     <bean id="transactionManager" 
47           class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
48           <property name="dataSource" ref="dataSource"></property>
49     </bean>
50     
51     <!-- 启用事务注解 -->
52     <tx:annotation-driven transaction-manager="transactionManager"/>
53 
54 </beans>

3 com.spring.jdbc

实体类

 1 package com.spring.jdbc;
 2 
 3 public class Employee {
 4     private int id;
 5     private String lastName;
 6     private String email;
 7     
 8     private int deptId;
 9     
10     
11     public int getDeptId() {
12         return deptId;
13     }
14     public void setDeptId(int deptId) {
15         this.deptId = deptId;
16     }
17     public int getId() {
18         return id;
19     }
20     public void setId(int id) {
21         this.id = id;
22     }
23     public String getLastName() {
24         return lastName;
25     }
26     public void setLastName(String lastName) {
27         this.lastName = lastName;
28     }
29     public String getEmail() {
30         return email;
31     }
32     public void setEmail(String email) {
33         this.email = email;
34     }
35     @Override
36     public String toString() {
37         return "Employee [id=" + id + ", lastName=" + lastName + ", email="
38                 + email + ", deptId=" + deptId + "]";
39     }
40     
41     
42 }

EmployeeDao.java

 1 package com.spring.jdbc;
 2 
 3 import org.springframework.beans.factory.annotation.Autowired;
 4 import org.springframework.jdbc.core.BeanPropertyRowMapper;
 5 import org.springframework.jdbc.core.JdbcTemplate;
 6 import org.springframework.jdbc.core.RowMapper;
 7 import org.springframework.stereotype.Repository;
 8 
 9 @Repository
10 public class EmployeeDao {
11     
12     @Autowired
13     private JdbcTemplate jdbcTemplate;
14     
15     public Employee get(int id){
16         String sql="SELECT id,last_name lastName,email,dept_id FROM employees WHERE id=?";
17         RowMapper<Employee> rowMapper=new BeanPropertyRowMapper<>(Employee.class);
18         Employee employee=jdbcTemplate.queryForObject(sql, rowMapper,id);
19         
20         return employee;
21         
22         
23     }
24 }
  1 package com.spring.jdbc;
  2 
  3 import java.sql.SQLException;
  4 import java.util.ArrayList;
  5 import java.util.HashMap;
  6 import java.util.List;
  7 import java.util.Map;
  8 
  9 import javax.sql.DataSource;
 10 
 11 import org.junit.Test;
 12 import org.springframework.context.ApplicationContext;
 13 import org.springframework.context.support.ClassPathXmlApplicationContext;
 14 import org.springframework.jdbc.core.BeanPropertyRowMapper;
 15 import org.springframework.jdbc.core.JdbcTemplate;
 16 import org.springframework.jdbc.core.RowMapper;
 17 import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
 18 import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
 19 import org.springframework.jdbc.core.namedparam.SqlParameterSource;
 20 
 21 public class JdbcTest {
 22 
 23     private ApplicationContext ctx=null;
 24     private JdbcTemplate jdbcTemplate=null;
 25     private EmployeeDao employeeDao ;
 26     private DepartmentDao departmentDao ;
 27     private NamedParameterJdbcTemplate namedParameterJdbcTemplate=null;
 28     {
 29         ctx=new ClassPathXmlApplicationContext("beans-dataSource.xml");
 30         jdbcTemplate =(JdbcTemplate) ctx.getBean("jdbcTemplate");
 31         employeeDao = ctx.getBean(EmployeeDao.class);
 32         departmentDao = ctx.getBean(DepartmentDao.class);
 33         namedParameterJdbcTemplate=(NamedParameterJdbcTemplate) ctx.getBean("namedParameterJdbcTemplate");
 34         
 35     }
 36     
 37     
 38     
 39     /**
 40      * 使用具名参数时, 可以使用 update(String sql, SqlParameterSource paramSource) 方法进行更新操作
 41      * 1. SQL 语句中的参数名和类的属性一致!
 42      * 2. 使用 SqlParameterSource 的 BeanPropertySqlParameterSource 实现类作为参数. 
 43      */
 44     @Test
 45     public void testNamedParameterJdbcTemplate2(){
 46         String sql="INSERT INTO employees(last_name,email,dept_id) VALUES(:lastName,:email,:deptId)";
 47         Employee employee=new Employee();
 48         employee.setLastName("LKQ");
 49         employee.setEmail("[email protected]");
 50         employee.setDeptId(2);
 51         
 52         SqlParameterSource  sqlParameterSource =new  BeanPropertySqlParameterSource(employee);
 53         namedParameterJdbcTemplate.update(sql, sqlParameterSource);
 54         
 55     }
 56     /**
 57      * 可以为参数起名字. 
 58      * 1. 好处: 若有多个参数, 则不用再去对应位置, 直接对应参数名, 便于维护
 59      * 2. 缺点: 较为麻烦. 
 60      */
 61     @Test
 62     public void testNamedParameterJdbcTemplate(){
 63         String sql="INSERT INTO employees(last_name,email,dept_id) VALUES(:name,:email,:deptid)";
 64         Map<String,Object> paramMap=new HashMap<>();
 65         paramMap.put("name", "XJP");
 66         paramMap.put("email", "[email protected]");
 67         paramMap.put("deptid",001);
 68         
 69         namedParameterJdbcTemplate.update(sql, paramMap);
 70     }
 71     
 72     
 73     
 74     @Test
 75     public void testDepartmentDao(){
 76         System.out.println(departmentDao.get(2));
 77     }
 78     @Test
 79     public void testEmployeeDao(){
 80         System.out.println(employeeDao.get(2));
 81     }
 82     
 83     /**
 84      *  从数据库中获取记录对象集合
 85      */
 86     @Test
 87     public void testQueryForList(){
 88         String sql="SELECT id,last_name lastName,email,dept_id FROM employees WHERE id>?";
 89         RowMapper<Employee> rowMapper=new BeanPropertyRowMapper<>(Employee.class);
 90         List<Employee> employees=jdbcTemplate.query(sql, rowMapper,8);
 91         
 92         System.out.println(employees);
 93     }
 94     
 95     
 96     /**
 97      *  从数据库中获取单个列的值,统计查询
 98      */
 99     @Test
100     public void testQueryForObject2(){
101         String sql="SELECT count(id) FROM employees";
102         long count=jdbcTemplate.queryForObject(sql, Long.class);
103         System.out.println(count);
104     }
105     
106     
107     /**
108      *  从数据库中获取一条记录, 实际得到对应的一个对象
109      */
110     @Test
111     public void testQueryForObject(){
112         String sql="SELECT id,last_name lastName,email,dept_id FROM employees WHERE id=?";
113         RowMapper<Employee> rowMapper=new BeanPropertyRowMapper<>(Employee.class);
114         Employee employee=jdbcTemplate.queryForObject(sql, rowMapper,2);
115         System.out.println(employee);
116     }
117     
118     /**
119      * 执行批量更新: 批量的 INSERT, UPDATE, DELETE
120      * 最后一个参数是 Object[] 的 List 类型: 因为修改一条记录需要一个 Object 的数组, 那么多条不就需要多个 Object 的数组吗
121      */
122     @Test
123     public void testBatchUpdate(){
124         String sql="INSERT INTO employees(last_name,email,dept_id) VALUES(?,?,?)";
125         
126         List<Object[]> batchArgs=new ArrayList<>();
127         batchArgs.add(new Object[]{"AA", "[email protected]", 1});
128         batchArgs.add(new Object[]{"BB", "[email protected]", 2});
129         batchArgs.add(new Object[]{"CC", "[email protected]", 3});
130         batchArgs.add(new Object[]{"DD", "[email protected]", 3});
131         batchArgs.add(new Object[]{"EE", "[email protected]", 2});
132         
133         jdbcTemplate.batchUpdate(sql, batchArgs);
134     }
135     /**
136      * 执行 INSERT, UPDATE, DELETE
137      */
138     @Test
139     public void testUpdate(){
140         String sql="UPDATE employees SET last_name = ? WHERE id=?";
141         jdbcTemplate.update(sql,"王根深",2);
142     }
143     @Test
144     public void testDataSource() throws SQLException{
145         DataSource dataSource =(DataSource) ctx.getBean("dataSource");
146         System.out.println(dataSource.getConnection());
147     }
148 }

 

以上是关于Spring JDBC实现查询的主要内容,如果未能解决你的问题,请参考以下文章

部分代码片段

使用Spring JdbcTemplate实现数据库操作

Spring Jdbc 自定义 ORM——sql查询对应Java数据对象

JDBC操作数据库之查询数据

Spring JDBC Template 无法执行 FROM 子句中包含嵌套查询的查询

Spring Data JDBC 中的乐观锁