Support for JDBC in Spring Learning
To make JDBC easier to use, Spring defines an abstraction layer on the jdbc api to establish a JDBC access framework. as the core of Spring JDBC framework, JDBC templates are designed to provide template methods for different types of JDBC operations. each template method can control the entire process and cover specific tasks in the process. in this way, you can minimize the workload of database access while keeping the flexibility possible. the JdbcTemplate class is designed to be thread-safe. Therefore, you can declare a single instance in the IOC container and inject the instance into all DAO instances. update database with SQL statements and parameters: public int update (String SQL, Object... args) throws DataAccessException batch update database: public int [] batchUpdate (String SQL, List <Object []> batchArgs) query single row: public <T> T queryForObject (String SQL, parameterizedRowsMapper <T> rm, Object... args) throws DataAccessException query multiple rows: public <T> List <T> query (String SQL, parameterizedRowsMapper <T> rm, Object... args) throws DataAccessException Single-value query: public <T> T queryForObject (String SQL, Class <T> requiredType, Object... args) throws DataAccessException
// Configuration file db. propertiesjdbc. user = rootjdbc. password = 1230jdbc. driverClass = com. mysql. jdbc. driverjdbc. jdbcUrl = jdbc: mysql: // springjdbc. initPoolSize = 5jdbc. maxPoolSize = 10 // IOC configuration <? Xml version = "1.0" encoding = "UTF-8"?> <Beans xmlns = "http://www.springframework.org/schema/beans" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xmlns: context = "http://www.springframework.org/schema/context" xmlns: tx = "http://www.springframework.org/schema/tx" xsi: schemaLocation = "http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/tx http: // w Ww.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd "> <context: component-scan base-package =" com. atguigu. spring "> </context: component-scan> <! -- Import the resource file --> <context: property-placeholder location = "classpath: db. properties"/> <! -- Configure the C3P0 data source --> <bean id = "dataSource" class = "com. mchange. v2.c3p0. comboPooledDataSource "> <property name =" user "value =" $ {jdbc. user} "> </property> <property name =" password "value =" $ {jdbc. password} "> </property> <property name =" jdbcUrl "value =" $ {jdbc. jdbcUrl} "> </property> <property name =" driverClass "value =" $ {jdbc. driverClass} "> </property> <property name =" initialPoolSize "value =" $ {jdbc. initPoolSize }"> </Property> <property name = "maxPoolSize" value = "$ {jdbc. maxPoolSize}"> </property> </bean> <! -- Configure Spirng's JdbcTemplate --> <bean id = "jdbcTemplate" class = "org. springframework. jdbc. core. jdbcTemplate "> <property name =" dataSource "ref =" dataSource "> </property> </bean> </beans> // test JdbcTemplate package com. atguigu. spring. jdbc; import java. SQL. SQLException; import java. util. arrayList; import java. util. hashMap; import java. util. list; import java. util. map; import javax. SQL. dataSource; import org. junit. te St; import org. springframework. context. applicationContext; import org. springframework. context. support. classPathXmlApplicationContext; import org. springframework. jdbc. core. beanPropertyRowMapper; import org. springframework. jdbc. core. jdbcTemplate; import org. springframework. jdbc. core. rowMapper; import org. springframework. jdbc. core. namedparam. beanPropertySqlParameterSource; import org. springframework. jdbc. co Re. namedparam. namedParameterJdbcTemplate; import org. springframework. jdbc. core. namedparam. sqlParameterSource; public class JDBCTest {private ApplicationContext ctx = null; private JdbcTemplate jdbcTemplate; private EmployeeDao employeeDao; private DepartmentDao departmentDao; private vertex ;{ ctx = new vertex ("applicationContex T. xml "); jdbcTemplate = (JdbcTemplate) ctx. getBean ("jdbcTemplate"); employeeDao = ctx. getBean (EmployeeDao. class); departmentDao = ctx. getBean (DepartmentDao. class); namedParameterJdbcTemplate = ctx. getBean (NamedParameterJdbcTemplate. class);}/*** when using a named parameter, you can use the update (String SQL, SqlParameterSource paramSource) method to perform the update operation * 1. the parameter names and class attributes in the SQL statement are the same! * 2. use the BeanPropertySqlParameterSource implementation class of SqlParameterSource as the parameter. * // @ Test public void testNamedParameterJdbcTemplate2 () {String SQL = "INSERT INTO employees (last_name, email, dept_id)" + "VALUES (: lastName,: email,: dpetId )"; employee employee = new Employee (); employee. setLastName ("XYZ"); employee. setEmail ("xyz@sina.com"); employee. setDpetId (3); SqlParameterSource paramSource = new BeanProperty SqlParameterSource (employee); namedParameterJdbcTemplate. update (SQL, paramSource);}/*** can be a parameter name. * 1. benefit: if there are multiple parameters, you do not need to go to the corresponding location, directly corresponding to the parameter name, easy to maintain * 2. disadvantages: relatively troublesome. * // @ Test public void testNamedParameterJdbcTemplate () {String SQL = "INSERT INTO employees (last_name, email, dept_id) VALUES (: ln,: email,: deptid )"; map <String, Object> paramMap = new HashMap <> (); paramMap. put ("ln", "FF"); paramMap. put ("email ", "Ff@atguigu.com"); paramMap. put ("deptid", 2); namedParameterJdbcTemplate. update (SQL, paramMap) ;}@ Test public void testDepartmentDao () {System. out. println (departmentDao. get (1) ;}@ Test public void testEmployeeDao () {System. out. println (employeeDao. get (1);}/*** get the value of a single column or perform a statistical query * use queryForObject (String SQL, Class <Long> requiredType) */@ Test public void testQueryForObject2 () {String SQL = "S ELECT count (id) FROM employees "; long count = jdbcTemplate. queryForObject (SQL, Long. class); System. out. println (count);}/*** query the collection of Object Classes * Note that the queryForList method is not called */@ Test public void testQueryForList () {String SQL = "SELECT id, last_name lastName, email FROM employees WHERE id>? "; RowMapper <Employee> rowMapper = new BeanPropertyRowMapper <> (Employee. class); List <Employee> employees = jdbcTemplate. query (SQL, rowMapper, 5); System. out. println (employees);}/*** get a record from the database and actually get the corresponding object * Note that queryForObject (String SQL, Class <Employee> requiredType, object... args) method! * You need to call queryForObject (String SQL, RowMapper <Employee> rowMapper, Object... args) * 1. the RowMapper specifies how to map rows in the result set. The common implementation class is BeanPropertyRowMapper * 2. use the column alias in SQL to map column names and Class Attribute names. for example, last_name lastName * 3. cascade attributes are not supported. jdbcTemplate is a JDBC tool instead of An ORM framework */@ Test public void testQueryForObject () {String SQL = "SELECT id, last_name lastName, email, dept_id as \" department. id \ "FROM employees WHERE I D =? "; RowMapper <Employee> rowMapper = new BeanPropertyRowMapper <> (Employee. class); Employee employee = jdbcTemplate. queryForObject (SQL, rowMapper, 1); System. out. println (employee);}/*** execute batch UPDATE: Batch INSERT, UPDATE, DELETE * The last parameter is the List type of Object: because modifying a record requires an array of objects, isn't multiple objects required? */@ Test public void testBatchUpdate () {String SQL = "INSERT INTO employees (last_name, email, dept_id) VALUES (?,?,?) "; List <Object []> batchArgs = new ArrayList <> (); batchArgs. add (new Object [] {"AA", "aa@atguigu.com", 1}); batchArgs. add (new Object [] {"BB", "bb@atguigu.com", 2}); batchArgs. add (new Object [] {"CC", "cc@atguigu.com", 3}); batchArgs. add (new Object [] {"DD", "dd@atguigu.com", 3}); batchArgs. add (new Object [] {"EE", "ee@atguigu.com", 2}); jdbcTemplate. batchUpdate (SQL, batchArgs);}/*** execute INSERT, UPDATE, DEL ETE */@ Test public void testUpdate () {String SQL = "UPDATE employees SET last_name =? WHERE id =? "; JdbcTemplate. update (SQL, "Jack", 5) ;}@ Test public void testDataSource () throws SQLException {DataSource dataSource = ctx. getBean (DataSource. class); System. out. println (dataSource. getConnection () ;}// the dao code package com. atguigu. spring. jdbc; import org. springframework. beans. factory. annotation. autowired; import org. springframework. jdbc. core. beanPropertyRowMapper; import org. springframework. jdbc. c Ore. jdbcTemplate; import org. springframework. jdbc. core. rowMapper; import org. springframework. stereotype. repository; @ Repositorypublic class EmployeeDao {@ Autowired private JdbcTemplate jdbcTemplate; public Employee get (Integer id) {String SQL = "SELECT id, last_name lastName, email FROM employees WHERE id =? "; RowMapper <Employee> rowMapper = new BeanPropertyRowMapper <> (Employee. class); Employee employee = jdbcTemplate. queryForObject (SQL, rowMapper, id); return employee ;}}