【Spring Boot 25】JdbcTemplate 配置类 ,设计模式面试题 java
return new JdbcTemplate(dataSource);
}
4、更详细的配置类
package com.guor.config;
import java.sql.SQLException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import com.alibaba.druid.pool.DruidDataSource;
@Configuration
@PropertySource(value = { "classpath:druidConfig.properties",
"classpath:jdbc.properties" }, ignoreResourceNotFound = true)
public class DataSourceConfig {
@Value("${driverClassName}")
private String driverClassName;
@Value("${url}")
private String url;
@Value("${duridUserName}")
private String username;
@Value("${password}")
private String password;
@Value("${filters}")
private String filters;
@Value("${initialSize}")
private int initialSize;
@Value("${maxActive}")
private int maxActive;
@Value("${minIdle}")
private int minIdle;
@Value("${maxWait}")
private int maxWait;
@Value("${validationQuery}")
private String validationQuery;
@Value("${testWhileIdle}")
private boolean testWhileIdle;
@Value("${testOnBorrow}")
private boolean testOnBorrow;
@Value("${testOnReturn}")
private boolean testOnReturn;
@Value("${maxPoolPreparedStatementPerConnectionSize}")
private int maxPoolPreparedStatementPerConnectionSize;
@Value("${removeAbandoned}")
private boolean removeAbandoned;
@Value("${removeAbandonedTimeout}")
private int removeAbandonedTimeout;
@Value("${timeBetweenEvictionRunsMillis}")
private int timeBetweenEvictionRunsMillis;
@Value("${minEvictableIdleTimeMillis}")
private int minEvictableIdleTimeMillis;
@Bean(initMethod="init",destroyMethod="close")
public DruidDataSource dataSource(){
DruidDataSource dataSource=new DruidDataSource();
try {
dataSource.setUrl(url);
dataSource.setDriverClassName(driverClassName);
dataSource.setUsername(username);
dataSource.setPassword(password);
dataSource.setFilters(filters);
dataSource.setInitialSize(initialSize);
dataSource.setMaxActive(maxActive);
dataSource.setMinIdle(minIdle);
dataSource.setMaxWait(maxWait);
dataSource.setValidationQuery(validationQuery);
dataSource.setTestWhileIdle(testWhileIdle);
dataSource.setTestOnBorrow(testOnBorrow);
dataSource.setTestOnReturn(testOnReturn);
dataSource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
dataSource.setRemoveAbandoned(removeAbandoned);
dataSource.setRemoveAbandonedTimeout(removeAbandonedTimeout);
dataSource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
dataSource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
System.out.println("连接池启动成功");
} catch (SQLException e) {
e.printStackTrace();
}
return dataSource;
}
}
5、事务的使用
@Service
public class UserServiceImpl implements UserService {
@Autowired
private JdbcTemplate jdbcTemplate;
@Override
@Transactional
public void insertUser(User user) {
String sql = "insert into user(id, name) values(?,?)";
jdbcTemplate.update(sql, user.getId(), user.getName());
//int num = 1/0; //放开测试事务。预期结果为添加失败,库中无数据。测试结果与预期一致
}
}
?6、dao 层代码简介
@Repository("userDao")
public class UserDaoImpl implements UserDao {
@Autowired
private JdbcTemplate jdbcTemplate;
//判断用户是否登录成功
public boolean isLogin(UserEntity paramUser) {
boolean flag=false;
String sqlStr="select * from user where userName=? and passWord=?";
List<UserEntity> userList=jdbcTemplate.query(sqlStr,
new Object[]{paramUser.getUserName(),paramUser.getPassWord()},
new BeanPropertyRowMapper(UserEntity.class));
if(userList!=null && userList.size()>0){
flag=true;
}
return flag;
}
}
四、API 介绍
1、执行 DDL 语句
(1)API 简介
//一般用于执行 DDL 语句
public int execute(final String sql)
(2)代码实例
public class Test01 {
public static void main(String[] args) {
// 创建表的 SQL 语句
String sql = "CREATE TABLE product("
"pid INT PRIMARY KEY AUTO_INCREMENT,"
"pname VARCHAR(20),"
"price DOUBLE"
");";
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
jdbcTemplate.execute(sql);
}
}
2、JdbcTemplate 实现增删改
(1)API 简介
//用于执行 INSERT、UPDATE、DELETE 等 DML 语句
public int update(String sql)
(2)代码实例
public class Test {
public static void main(String[] args) throws Exception {
insertTest();
updateTest();
deleteTest();
}
// JDBCTemplate 插入
public static void insertTest() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
String sql = "INSERT INTO user(id,name,age) VALUES (?, ?, ?)";
jdbcTemplate.update(sql, 1, "素小暖", 18);
}
// JDBCTemplate 更新
public static void updateTest() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
String sql = "UPDATE user SET age= ?, address = ? WHERE name=?";
int i = jdbcTemplate.update(sql, 19, "大连市高新园区", "素小暖");
System.out.println("影响的行数: " + i);
}
// JDBCTemplate 删除
public static void deleteTest() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
String sql = "DELETE FROM user WHERE id=?";
int i = jdbcTemplate.update(sql, 1);
System.out.println("影响的行数: " + i);
}
}
3、JdbcTemplate 查询-queryForInt 返回一个 int 整数
(1)API 简介
//执行查询语句,返回一个 int 类型的值
public int queryForInt(String sql)
(2)代码实例
// queryForInt 返回一个整数
public static void test01() throws Exception {
// String sql = "SELECT COUNT(*) FROM user";
String sql = "SELECT name FROM user WHERE id= ?"
;
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
int forInt = jdbcTemplate.queryForInt(sql, 2);
}
4、JdbcTemplate 查询-queryForLong 返回一个 long 整数
(1)API 简介
//执行查询语句,返回一个 long 类型的数据
public long queryForLong(String sql)
(2)代码实例
// queryForLong 返回一个 long 类型整数
public static void test02() throws Exception {
String sql = "SELECT COUNT(1) FROM user";
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
long forLong = jdbcTemplate.queryForLong(sql);
}
5、JdbcTemplate 查询-queryForObject 返回 String
(1)API 简介
//执行查询语句,返回一个指定类型的数据
public <T> T queryForObject(String sql, Class<T> requiredType)
(2)代码实例
public static void test03() throws Exception {
String sql = "SELECT name FROM user WHERE id= ?";
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
String str = jdbcTemplate.queryForObject(sql, 1, String.class);
}
6、JdbcTemplate 查询-queryForMap 返回一个 Map 集合
(1)API 简介
//执行查询语句,将一条记录放到一个 Map 中
public Map<String, Object> queryForMap(String sql)
(2)代码实例
public static void test04() throws Exception {
String sql = "SELECT * FROM user WHERE id= ? ";
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
Map<String, Object> map = jdbcTemplate.queryForMap(sql, 1);
}
7、JdbcTemplate 查询-queryForList 返回一个 List 集合
(1)API 简介
//执行查询语句,返回一个 List 集合,List 中存放的是 Map 类型的数据
public List<Map<String, Object>> queryForList(String sql)
(2)代码实例
public static void test05() throws Exception {
String sql = "SELECT * FROM user WHERE id< ?";
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, 10);
for (Map<String, Object> map : list) {
System.out.println(map);
}
}
8、JdbcTemplate 查询-RowMapper 返回自定义对象
(1)API 简介
//执行查询语句,返回一个 List 集合,List 中存放的是 RowMapper 指定类型的数据
public <T> List<T> query(String sql, RowMapper<T> rowMapper)
(2)使用步骤
定义 Product 类
创建 JdbcTemplate 对象
编写查询的 SQL 语句
使用 JdbcTemplate 对象的 query 方法,并传入 RowMapper 匿名内部类
在匿名内部类中将结果集中的一行记录转成一个 Product 对象
(3)代码实例
// query 使用 rowMap 做映射返回一个对象
public static void test06() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
// 查询数据的 SQL 语句
String sql = "SELECT * FROM user";
/**
使用 JdbcTemplate 对象的 query 方法,并传入 RowMapper 匿名内部类
在匿名内部类中将结果集中的一行记录转成一个 User 对象
*/
List<User> list = jdbcTemplate.query(sql, new RowMapper<User>() {
@Override
public Product mapRow(ResultSet arg0, int arg1) throws SQLException {
User user = new User();
user.setId(arg0.getInt("id"));
user.setName(arg0.getString("name"));
user.setAge(arg0.getInt("age"));
return p;
}
});
for (User user : list) {
System.out.println(user);
}
}
9、JdbcTemplate 查询-BeanPropertyRowMapper 返回自定义对象
(1)API 简介
//执行查询语句,返回一个 List 集合,List 中存放的是 RowMapper 指定类型的数据
public <T> List<T> query(String sql, RowMapper<T> rowMapper)
//BeanPropertyRowMapper 类实现了 RowMapper 接口
public class BeanPropertyRowMapper<T> implements RowMapper<T>
(2)使用步骤
定义 Product 类
创建 JdbcTemplate 对象
编写查询的 SQL 语句
使用 JdbcTemplate 对象的 query 方法,并传入 BeanPropertyRowMapper 对象
(3)代码实例
// query 使用 BeanPropertyRowMapper 做映射返回对象
public static void test07() throws Exception {
JdbcTemplate jdbcTemplate = new JdbcTemplate(DataSourceUtils.getDataSource());
// 查询数据的 SQL 语句
String sql = "SELECT * FROM user";
List<Product> list = jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(User.class));
for (User user : list) {
System.out.println(user);
}
}
10、批量插入
(1)API 简介
//批量插入
jdbcTemplate.batchUpdate(String sql, List<Object[]> paramList);
评论