话不多说,直接上:
1. 导入坐标
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.trc</groupId>
<artifactId>spring04_jdbc</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.26</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>utf-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
2. 实体类
package com.trc.domain;
/**
* Created by Tangcancan on 2019/11/25 11:05
*/
public class Account {
private int id;
private String name;
private String money;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMoney() {
return money;
}
public void setMoney(String money) {
this.money = money;
}
@Override
public String toString() {
return "Account{" +
"id=" + id +
", name='" + name + '\'' +
", money='" + money + '\'' +
'}';
}
}
3. 自定义RowMapper实现
package com.trc.template;
import org.springframework.jdbc.core.RowMapper;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
/**
* Created by Tangcancan on 2019/11/25 12:31
*/
public class MyRowMapper<T> implements RowMapper<T> {
public Class<T> cls;
public MyRowMapper(Class<T> cls) {
this.cls = cls;
}
@Override
public T mapRow(ResultSet rs, int row) throws SQLException {
//需要1.对象 2.数据 把数据封装带对象中,返回
try {
ResultSetMetaData metaData = rs.getMetaData();
int columnCount = metaData.getColumnCount();//获取列的数量
Constructor<T> cons = cls.getConstructor();
T t = cons.newInstance();//创建实例
for (int i = 1; i <= columnCount; i++) {
String columnName = metaData.getColumnName(i);//通过列编号获取对应的名称
Field field = cls.getDeclaredField(columnName);//通过列名获取对应的成员变量
//(要求数据库字段名与成员变量名称保持一致)
field.setAccessible(true);//暴力反射
Object value = rs.getObject(i);//获取对应字段的名称
field.set(t, value);//设置值
}
return t;
} catch (ReflectiveOperationException e) {
e.printStackTrace();
}
return null;
}
}
4. Template的自定义
package com.trc.template;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Tangcancan on 2019/11/25 9:35
*/
public class MyTemplate {
//创建数据源
private DataSource dataSource;
//构造方法
public MyTemplate() {
}
public MyTemplate(DataSource dataSource) {
this.dataSource = dataSource;
}
public DataSource getDataSource() {
return dataSource;
}
public void setDataSource(DataSource dataSource) {
this.dataSource = dataSource;
}
/**
* 增删改操作
*
* @param sql
* @param args
* @return 影响的行数
*/
public int update(String sql, Object... args) throws SQLException {
//获取连接对象
Connection conn = dataSource.getConnection();
//创建执行对象
PreparedStatement pstmt = conn.prepareStatement(sql);
for (int i = 1; i <= args.length; i++) {
//设置参数
pstmt.setObject(i, args[i-1]);
}
return pstmt.executeUpdate();
}
/**
* 查询操作
*
* @param sql
* @param rowMapper
* @param args
* @param <T>
* @return 返回结果集
*/
//泛型方法:具体类型由传递的参数beanPropertyRowMapper的泛型T决定
public <T> List<T> query(String sql, MyRowMapper<T> rowMapper, Object... args) throws SQLException {
Connection conn = dataSource.getConnection();
PreparedStatement pstmt = conn.prepareStatement(sql);
for (int i = 1; i <= args.length; i++) {
pstmt.setObject(i, args[i]);
}
ResultSet rs = pstmt.executeQuery();
List<T> list = new ArrayList<>();
//循环遍历,封装成对象
while (rs.next()) {
int row = rs.getRow();
T mapRow = rowMapper.mapRow(rs, row);
list.add(mapRow);
}
return list;
}
/**
* 查询单个对象
*
* @param sql
* @param rowMapper
* @param args
* @param <T>
* @return 返回单个结果集
* @throws SQLException
*/
public <T> T queryForObject(String sql, MyRowMapper<T> rowMapper, Object... args) throws SQLException {
return (T) query(sql, rowMapper, args);
}
}
5. 测试类
package com.trc.test;
import com.alibaba.druid.pool.DruidDataSource;
import com.trc.domain.Account;
import com.trc.template.MyRowMapper;
import com.trc.template.MyTemplate;
import java.sql.SQLException;
import java.util.List;
/**
* 简单的测试
* Created by Tangcancan on 2019/11/25 11:06
*/
public class Test {
//增删改查
public static void main(String[] args) {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setDriverClassName("com.mysql.jdbc.Driver");
dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/lesson");
dataSource.setUsername("root");
dataSource.setPassword("123");
//
MyTemplate myTemplate = new MyTemplate(dataSource);
//测试增删改
int row = 0;
try {
row = myTemplate.update("insert into accout values(?,?,?)", null, "tom", "5321");
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println(row);
//测试查询
List<Account> list = null;
try {
list = myTemplate.query("select * from accout", new MyRowMapper<>(Account.class));
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println(list);
}
}
6. 可能有些细节需要完成!Over!