准备工作
需要的依赖
<dependencies>
<!--spring jdbc Spring 持久化层支持jar包-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>6.0.2</version>
</dependency>
<!-- MySQL驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.30</version>
</dependency>
<!-- 数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.2.15</version>
</dependency>
</dependencies>
创建jdbc.properties
jdbc.user=root
jdbc.password=root
jdbc.url=jdbc:mysql://localhost:3306/spring?characterEncoding=utf8&useSSL=false
jdbc.driver=com.mysql.cj.jdbc.Driver
配置数据源
xml形式
<?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.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 导入外部属性文件 -->
<context:property-placeholder location="classpath:jdbc.properties" />
<!-- 配置数据源 -->
<bean id="druidDataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="username" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 配置 JdbcTemplate -->
<bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
<!-- 装配数据源 -->
<property name="dataSource" ref="druidDataSource"/>
</bean>
</beans>
配置类形式
@Configuration
@PropertySource("classpath:jdbc.properties")
public class AppConfig {
@Value("${jdbc.url}")
private String jdbcUrl;
@Value("${jdbc.driver}")
private String jdbcDriver;
@Value("${jdbc.user}")
private String jdbcUser;
@Value("${jdbc.password}")
private String jdbcPassword;
// 注册 PropertySourcesPlaceholderConfigurer bean 以支持 @Value 注解 (spring4.3之前)
// 创建资源文件解析器,spring4.3之前必须要的,不要就无法解析。
// @Bean
// public static PropertySourcesPlaceholderConfigurer propertyConfig() {
// return new PropertySourcesPlaceholderConfigurer();
// }
// 配置数据源
@Bean
public DataSource druidDataSource() {
DruidDataSource dataSource = new DruidDataSource();
dataSource.setUrl(jdbcUrl);
dataSource.setDriverClassName(jdbcDriver);
dataSource.setUsername(jdbcUser);
dataSource.setPassword(jdbcPassword);
return dataSource;
}
// 配置 JdbcTemplate
@Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
}
}
@Configuration
:这个注解可以加在类上,让这个类的功能等同于一个bean xml配置文件
@Bean
:这个注解类似于bean.xml配置文件中的bean元素,用来在Spring容器中注册一个Bean。@Bean注解用在方法上,表示通过方法来定义一个Bean,默认将方法名称作为Bean名称,将方法返回值作为Bean对象,注册到Spring容器中。
@PropertySource
:注解用于指定资源文件读取的位置,它不仅能读取properties文件
,也能读取xml文件
,并且通过YAML解析器,配合自定义PropertySourceFactory实现解析YAML文件。
@Value
:使用 @PropertySource
注解导入了 Properties 文件后,就可以使用 @Value
注解处理 Properties 文件中的值。
PropertySourcesPlaceholderConfigurer
:spring4.3之前,除了使用@PropertySource注解之外,还要手动注册一个资源文件解析器PropertySourcesPlaceholderConfigurer到IOC容器中。并且如果使用Bean注解注册资源文件解析器,方法要是static方法。但是spring4.3之后,就可以直接使用,因为spring会使用默认的DefaultPropertySourceFactory解析。
准备数据库与测试表
CREATE TABLE `t_emp` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL COMMENT '姓名',
`age` int(11) DEFAULT NULL COMMENT '年龄',
`sex` varchar(2) DEFAULT NULL COMMENT '性别',
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
实现CURD
自动注入JDBC
@SpringJUnitConfig(classes = AppConfig.class)
public class JdbcTest {
@Autowired
private JdbcTemplate jdbcTemplate;
}
增删改功能
@Test
void test1(){
//1 添加操作
//第一步 编写sql语句
String sql = "INSERT INTO t_emp VALUES(NULL,?,?,?)";
//第二步 调用jdbcTemplate的方法,传入相关参数
// Object[] params = {"东方不败", 20, "未知"};
// int rows = jdbcTemplate.update(sql,params);
int rows = jdbcTemplate.update(sql,"林平之", 20, "未知");
System.out.println(rows);
}
@Test
void test2(){
String sql = "update t_emp set name=? where id=?";
int rows = jdbcTemplate.update(sql,"岳不群",1);
System.out.println(rows);
}
@Test
void test3(){
String sql = "delete from t_emp where id=?";
int rows = jdbcTemplate.update(sql,1);
System.out.println(rows);
}
查询功能
//查询:返回对象
@Test
void test4(){
//写法一
String sql = "select * from t_emp where id=?";
// public <T> T queryForObject(String sql, RowMapper<T> rowMapper, @Nullable Object... args)
// T mapRow(ResultSet rs, int rowNum) throws SQLException;
Emp empResult = jdbcTemplate.queryForObject(sql,
(rs, rowNum) -> {
Emp emp = new Emp();
emp.setId(rs.getInt("id"));
emp.setName(rs.getString("name"));
emp.setAge(rs.getInt("age"));
emp.setSex(rs.getString("sex"));
return emp;
}, 2);
System.out.println(empResult);
}
@Test
void test5(){
// 写法二
String sql = "select * from t_emp where id=?";
Emp emp = jdbcTemplate.queryForObject(sql,
new BeanPropertyRowMapper<>(Emp.class),2);
System.out.println(emp);
}
//查询:返回list集合
@Test
public void testSelectList() {
String sql = "select * from t_emp";
List<Emp> list = jdbcTemplate.query(sql,
new BeanPropertyRowMapper<>(Emp.class));
System.out.println(list);
}
//查询:返回单个值
@Test
public void testSelectValue() {
String sql = "select count(*) from t_emp";
Integer count = jdbcTemplate.queryForObject(sql, Integer.class);
System.out.println(count);
}
转载请注明来源,欢迎对文章中的引用来源进行考证,欢迎指出任何有错误或不够清晰的表达。可以在下面评论区评论,也可以邮件至 1909773034@qq.com