springboot成神之——spring jdbc的使用
本文介绍spring jdbc的使用
目录结构

pom配置
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
properties配置
spring.datasource.url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true&useSSL=false&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=123
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
server.tomcat.uri-encoding=UTF-8
server.port=8888
model层User类
package com.springlearn.learn.model;
public class User{
private Integer id;
private String name;
private Integer age;
private String sex;
public User(Integer id, String name, Integer age, String sex) {
this.id = id;
this.name = name;
this.age = age;
this.sex = sex;
}
public Integer getId() {
return id;
}
public String getName() {
return name;
}
public Integer getAge() {
return age;
}
public String getSex() {
return sex;
}
public void setId(Integer id) {
this.id = id;
}
public void setName(String name) {
this.name = name;
}
public void setAge(Integer age) {
this.age = age;
}
public void setSex(String sex) {
this.sex = sex;
}
}
Dao层QueryForListDao
/**
* 第一种用法
* List<String> list = this.getJdbcTemplate().queryForList(sql, String.class)
*
* 第二种用法
* List<Map<String, Object>> list = this.getJdbcTemplate().queryForList(sql);
* for (Map<String, Object> item : users) {
* System.out.println("UserName: " + item.get("name") + "Age: " + item.get("age") + "Sex: " + item.get("sex"));
* }
*
* 第三种用法
* SqlRowSet rowset = this.getJdbcTemplate().queryForRowSet(sql, new Object[]{3},new int[]{Types.INTEGER});
*
* SqlRowSet rowset = listdao.getUsersList();
* while(rowset.next()) {
* System.out.println("UserName: " + rowset.getString("name") + "Age: " + rowset.getInt("age") + "Sex: " + rowset.getString("sex"));
* }
*
* 第四种方式
* rowmapper的使用,在我的文章 https://www.cnblogs.com/ye-hcj/p/9618588.html#mapper%E5%B1%82 已经讲过
*
* 第五种方式
* String sql = "select * from test where id=?;";
*
* RowCallbackHandler handler = new RowCallbackHandler(){
*
* @Override
* public void processRow(ResultSet rs) throws SQLException {
* System.out.println("id:" + rs.getInt("id") + "UserName: " + rs.getString("name") + "Age: " + rs.getInt("age") + "Sex: " + rs.getString("sex"));
* }
* };
*
* this.getJdbcTemplate().query(sql, handler, 3);
*
* listdao.getUsersList();
*
* 第六种方式,如下
*
* 第七中方式,queryForObject 用法和上面类似
*/
package com.springlearn.learn.Dao;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Types;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.sql.DataSource;
import com.springlearn.learn.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowCallbackHandler;
import org.springframework.jdbc.core.support.JdbcDaoSupport;
import org.springframework.jdbc.support.rowset.SqlRowSet;
import org.springframework.stereotype.Repository;
@Repository
public class QueryForListDao extends JdbcDaoSupport{
@Autowired
public QueryForListDao(DataSource dataSource) {
this.setDataSource(dataSource);
}
class ListResultSetExtractor implements ResultSetExtractor<List<User>>{
@Override
public List<User> extractData(ResultSet rs) throws SQLException, DataAccessException {
List<User> list = new ArrayList<User>();
while(rs.next()) {
list.add(new User(rs.getInt("id"), rs.getString("name"), rs.getInt("age"), rs.getString("sex")));
}
return list;
}
}
public List<User> getUsersList() {
String sql = "select * from test where id=?;";
ListResultSetExtractor ls = new ListResultSetExtractor();
List<User> list = this.getJdbcTemplate().query(sql, ls, 2);
return list;
}
}
config层AppConfiguration
package com.springlearn.learn.config;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.context.annotation.PropertySource;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.datasource.DriverManagerDataSource;
@Configuration
@ComponentScan(basePackages = "com.springlearn.learn.*")
@PropertySource("classpath:application.properties")
public class AppConfiguration{
@Autowired
private Environment env;
@Primary
@Bean(name="dataSource")
public DataSource dataSource() {
DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("spring.datasource.driver-class-name"));
dataSource.setUrl(env.getProperty("spring.datasource.url"));
dataSource.setUsername(env.getProperty("spring.datasource.username"));
dataSource.setPassword(env.getProperty("spring.datasource.password"));
return dataSource;
}
}
程序入口DemoApplication
package com.springlearn.learn;
import java.util.List;
import java.util.Map;
import com.springlearn.learn.Dao.QueryForListDao;
import com.springlearn.learn.config.AppConfiguration;
import com.springlearn.learn.model.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.jdbc.support.rowset.SqlRowSet;
public class DemoApplication {
public static void main(String[] args) {
ApplicationContext context = new AnnotationConfigApplicationContext(AppConfiguration.class);
QueryForListDao listdao = (QueryForListDao)context.getBean(QueryForListDao.class);
List<User> list = listdao.getUsersList();
for (User user : list) {
System.out.println("id:" + user.getId()+ "UserName: " + user.getName() + "Age: " + user.getAge() + "Sex: " + user.getSex());
}
}
}
springboot成神之——spring jdbc的使用的更多相关文章
- springboot成神之——spring boot,spring jdbc和spring transaction的使用
本文介绍spring boot,spring jdbc和spring transaction的使用 项目结构 依赖 application model层 mapper层 dao层 exception层 ...
- springboot成神之——spring文件下载功能
本文介绍spring文件下载功能 目录结构 DemoApplication WebConfig TestController MediaTypeUtils 前端测试 本文介绍spring文件下载功能 ...
- springboot成神之——spring的文件上传
本文介绍spring的文件上传 目录结构 配置application DemoApplication WebConfig TestController 前端上传 本文介绍spring的文件上传 目录结 ...
- springboot成神之——ioc容器(依赖注入)
springboot成神之--ioc容器(依赖注入) spring的ioc功能 文件目录结构 lang Chinese English GreetingService MyRepository MyC ...
- springboot成神之——springboot入门使用
springboot创建webservice访问mysql(使用maven) 安装 起步 spring常用命令 spring常见注释 springboot入门级使用 配置你的pom.xml文件 配置文 ...
- springboot成神之——mybatis和mybatis-generator
项目结构 依赖 generator配置文件 properties配置 生成文件 使用Example 本文讲解如何在spring-boot中使用mybatis和mybatis-generator自动生成 ...
- springboot成神之——application.properties所有可用属性
application.properties所有可用属性 # =================================================================== # ...
- springboot成神之——springboot+mybatis+mysql搭建项目简明demo
springboot+mybatis+mysql搭建项目简明demo 项目所需目录结构 pom.xml文件配置 application.properties文件配置 MyApplication.jav ...
- springboot成神之——swagger文档自动生成工具
本文讲解如何在spring-boot中使用swagger文档自动生成工具 目录结构 说明 依赖 SwaggerConfig 开启api界面 JSR 303注释信息 Swagger核心注释 User T ...
随机推荐
- Sublime Text C# 编译(csharp.sublime-build)
制作: 1. 配置环境变量PATH C# 7.0 C:\Program Files (x86)\Microsoft Visual Studio\\Enterprise\MSBuild\15.0\Bin ...
- 51nod 1161 组合数,规律
http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1161 显然,题目可以转化为矩阵求解,但复杂度显然时空都不允许,我们如果自 ...
- HDU 4725 建图
http://acm.hdu.edu.cn/showproblem.php?pid=4725 The Shortest Path in Nya Graph Time Limit: 2000/1000 ...
- 【spark】【问题】textFile找不到文件
2018/5/9 关于textFile读取文件的问题 问题描述: 今天第一次使用spark-shell来读取文件,我在本地建立了一个text.txt文件,然后用textFile读取生成rdd. 但是执 ...
- 【scala】元组
元组跟list类似,元组也是不可边的,但是元组可以容纳不同类型的元素. 元组用起来很简单,要实例化一个新的元组,只需要将对象放在圆括号当中,用逗号隔开即可. val pair = (99,“Luftb ...
- STM32F407: USART 遇到的问题
今天初次使用STM32F407进行USART串口通讯实验,按照f103的代码写完了,发现没法发送数据, 查看文档后发现是由于没有将端口映射到USART1,然后添加如下代码: 1 GPIO_PinAFC ...
- 【IDEA】笔记
引言 IDEA是JAVA开发的一个神器,熟悉它能极大提高我们的开发效率.正所谓工欲善其事,必先利其器. 快捷键 快捷键 介绍 Ctrl + F 在当前文件进行文本查找 (必备) Ctrl + R 在当 ...
- LeetCode OJ:Perfect Squares(完美平方)
Given a positive integer n, find the least number of perfect square numbers (for example, 1, 4, 9, 1 ...
- 20165210 Java第五次实验报告
20165210 实验五 网络编程与安全 网络编程与安全一: 实验要求: 两人一组结对编程: 参考http://www.cnblogs.com/rocedu/p/6766748.html#SECDSA ...
- Android的方法和属性(1)
1.Activity常用的方法 View findViewById(int id) //根据组件的ID取得组件对象 setContentView(int layoutResID) //设置布局文件,设 ...