首先创建数据库 test01
/创建学生表
CREATE TABLE `student` (
`id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`studentName` VARCHAR(30) DEFAULT NULL COMMENT '姓名',
`email` VARCHAR(30) DEFAULT NULL COMMENT '邮箱',
`deptId` INT(11) DEFAULT NULL COMMENT '宿舍号',
PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8
在eclipse 中创建 maven项目 jdk1.8.0_181 + 4.3.20.RELEASE + mysql5.1.38
pom.xml文件内容如下 里面最主要是spring 和 mysql 和 junit的依赖 必须保证添加
<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.bocan</groupId>
<artifactId>test01</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<name>test01</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<spring.version>4.3.20.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<!-- spring 核心包 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring 上下文对象 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- spring 集成的jdbc 操作数据库 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring-context-support -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- 日志 -->
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.16</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-simple</artifactId>
<version>1.7.5</version>
<scope>test</scope>
</dependency>
<!-- mysql 依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
</dependencies>
<!-- 统一jdk版本为jdk1.8 -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
接下来是dataSource.properties的内容 文件保存在 src/main/resources目录下
jdbc.user=root
jdbc.password=123456
jdbc.driverClass=com.mysql.jdbc.Driver
jdbc.jdbcUrl=jdbc:mysql:///test01
#jdbc.initPoolSize=5
#jdbc.maxPoolSize=10
接下来就是applicationContext.xml 的内容 文件保存在 src/main/resources目录下
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 导入资源文件 -->
<context:property-placeholder location="classpath:dataSource.properties"></context:property-placeholder>
<!-- 配置数据源 -->
<bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${jdbc.driverClass}"></property>
<property name="url" value="${jdbc.jdbcUrl}"></property>
<property name="username" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
<!-- <property name="initialPoolSize" value="${jdbc.initPoolSize}"></property>
<property name="maxPoolSize" value="${jdbc.maxPoolSize}"></property> -->
</bean>
<!-- 配置jdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dataSource"></property>
</bean>
<bean id="mainJdbc" class="org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate">
<constructor-arg ref="dataSource" />
</bean>
</beans>
接下来创建student实体类
package com.bocan.test01;
/**
* 学生实体类
*/
public class Student {
private int id;
private String studentName;
private String email;
private int deptId;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getDeptId() {
return deptId;
}
public void setDeptId(int deptId) {
this.deptId = deptId;
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", studentName='" + studentName + '\'' +
", email='" + email + '\'' +
", deptId=" + deptId +
'}';
}
}
接下来 创建一个测试的基类
package com.bocan.test01;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
* spring 测试基类
* @author asus
*
*/
@RunWith(SpringJUnit4ClassRunner.class) //使用junit4进行测试
@ContextConfiguration(locations={"classpath:applicationContext.xml"}) //加载配置文件
public class BaseJunit4Test {
}
接下来写测试类
package com.bocan.test01;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import org.junit.Test;
import org.springframework.beans.factory.annotation.Autowired;
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.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.jdbc.core.namedparam.SqlParameterSource;
/**
* 测试类
* @author asus
*
*/
public class JdbcTest01 extends BaseJunit4Test {
//自动注入
@Autowired
private DataSource dataSource;
//自动注入
@Autowired
private JdbcTemplate jdbcTemplate;
//自动注入
@Autowired
private NamedParameterJdbcTemplate mainJdbc;
@Test
public void testConnection(){
try {
System.out.println(dataSource.getConnection());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
@Test
public void testUpdate(){
String sql = "UPDATE student SET email = ?,deptId=? WHERE id = ?";
jdbcTemplate.update(sql,"[email protected]",2,2);
System.out.println("test complete");
}
/**
* 从数据库中获取一条记录,实际得到一个对象
* 需要调用中这个方法: queryForObject(java.lang.String sql,@NotNull org.springframework.jdbc.core.RowMapper<T> rowMapper,java.lang.Object... args)
* 1.其中的RowMapper指定如何去映射结果集的行,常用的实现类为BeanPropertyRowMapper<>(Student.class);
* 2.使用SQL中的列的别名完成列名和类的属性名的映射
* 3.不支持级联属性
*/
@Test
public void testQueryForObject(){
String sql = "SELECT id,studentName,email ,deptId FROM student WHERE id = ?";
RowMapper<Student> rowMapper = new BeanPropertyRowMapper<>(Student.class);
Student student = jdbcTemplate.queryForObject(sql, rowMapper,1);
System.out.println(student);
}
/**
* 查找实体类集合
*/
@Test
public void testQueryForList(){
//编写sql语句
String sql ="SELECT id,studentName,email ,deptId FROM student WHERE id > ?";
RowMapper<Student> rowMapper = new BeanPropertyRowMapper<>(Student.class);
List<Student> list = jdbcTemplate.query(sql, rowMapper,0);
System.out.println(list);
}
/**
* 统计
*/
@Test
public void testQueryForCount(){
String sql = "SELECT COUNT(id) FROM student";
int count = jdbcTemplate.queryForObject(sql, Integer.class);
System.out.println("记录数:"+count);
}
@Test
public void testNamedParameterJdbcTemplate(){
//sql语句 id 是自增的
String sql = "INSERT INTO student(studentName,email,deptId) VALUES(:name,:email,:deptId)";
//存储参数 键值对 的字典
Map<String,Object> paramMap = new HashMap<String,Object>();
//将要赋予的键值对 存储到paramMap 不考虑插入参数的顺序 但是要保证类型正确
paramMap.put("email", "[email protected]");
paramMap.put("deptId", 2);
paramMap.put("name", "Harden");
mainJdbc.update(sql, paramMap);
}
/**
* 将java代码创建的实体类对象 直接插入到数据库表中
*/
@Test
public void testNamedParameterJdbcTemplate2(){
//这里要注意 插入的sql语句中 value中的参数名:studentName,:email,:deptId 必须与 Student类中的变量一致
String sql = "INSERT INTO student(studentName,email,deptId) VALUES(:studentName,:email,:deptId)";
//创建实体类
Student student = new Student();
//student.setId(5); 主键自增 可不写
student.setStudentName("Tom");
student.setEmail("[email protected]");
student.setDeptId(1);
SqlParameterSource paramSource = new BeanPropertySqlParameterSource(student);
mainJdbc.update(sql, paramSource);
}
@Test
public void testDelete(){
//删除 类似这种删除对象 通常直接 写完整语句就行 在方法名后的括号 传入参数,然后拼接到SQL语句后面
String sql = "DELETE FROM student WHERE id = 4";
//method1 方法1
//mainJdbc.update(sql, new HashMap<String,Object>());
//方法2 方便点
mainJdbc.getJdbcOperations().update(sql);
}
}
这个我参考这大神的代码在结合自己的理解 https://blog.csdn.net/a1610770854/article/details/51914147