本文介绍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的使用的更多相关文章

  1. springboot成神之——spring boot,spring jdbc和spring transaction的使用

    本文介绍spring boot,spring jdbc和spring transaction的使用 项目结构 依赖 application model层 mapper层 dao层 exception层 ...

  2. springboot成神之——spring文件下载功能

    本文介绍spring文件下载功能 目录结构 DemoApplication WebConfig TestController MediaTypeUtils 前端测试 本文介绍spring文件下载功能 ...

  3. springboot成神之——spring的文件上传

    本文介绍spring的文件上传 目录结构 配置application DemoApplication WebConfig TestController 前端上传 本文介绍spring的文件上传 目录结 ...

  4. springboot成神之——ioc容器(依赖注入)

    springboot成神之--ioc容器(依赖注入) spring的ioc功能 文件目录结构 lang Chinese English GreetingService MyRepository MyC ...

  5. springboot成神之——springboot入门使用

    springboot创建webservice访问mysql(使用maven) 安装 起步 spring常用命令 spring常见注释 springboot入门级使用 配置你的pom.xml文件 配置文 ...

  6. springboot成神之——mybatis和mybatis-generator

    项目结构 依赖 generator配置文件 properties配置 生成文件 使用Example 本文讲解如何在spring-boot中使用mybatis和mybatis-generator自动生成 ...

  7. springboot成神之——application.properties所有可用属性

    application.properties所有可用属性 # =================================================================== # ...

  8. springboot成神之——springboot+mybatis+mysql搭建项目简明demo

    springboot+mybatis+mysql搭建项目简明demo 项目所需目录结构 pom.xml文件配置 application.properties文件配置 MyApplication.jav ...

  9. springboot成神之——swagger文档自动生成工具

    本文讲解如何在spring-boot中使用swagger文档自动生成工具 目录结构 说明 依赖 SwaggerConfig 开启api界面 JSR 303注释信息 Swagger核心注释 User T ...

随机推荐

  1. cenOs7安装redis

    1.安装redis redis 目前没有官方 RPM 安装包,我们需要从源代码编译,而为了要编译就需要安装 Make 和 GCC. 如果没有安装过 GCC 和 Make,那么就使用 yum 安装 -- ...

  2. WindowManager实现悬浮可拖动效果

    现在360手机卫士有个流量统计的效果,开启流量统计后,在桌面上会出现一个显示流量的窗体,在任何界面都可以自由拖动. 模仿这个功能,做了一个统计手机信号强度的Demo, 界面效果如下: 从上面的截图可以 ...

  3. Arcgis Add-In开发入门实例

    作为一个本科侧重于应用,工作之后却做了开发的程序员来说,做GIS,开发应该是一门必修课,只是,苦于各种原因吧,做GIS应用的人会开发的很少,做GIS开发的大部分都是计算机出身,痛心疾首啊-- 不好意思 ...

  4. 转:C++模板特化的概念

    http://blog.csdn.net/yesterday_record/article/details/7304025 很久没有看C++,在看STL源码剖析时,看到一个function templ ...

  5. Epoll 实例

    服务端调试: [test@cs2 epoll]$ g++ epoll_server.cpp -o epoll_server -lpthread [test@cs2 epoll]$ ./epoll_se ...

  6. 你所不知道的,Java 中操作符的秘密?

    在 Java 编程的过程中,我们对数据的处理,都是通过操作符来实现的.例如,用于赋值的赋值操作符.用于运算的运算操作符等.用于比较的比较操作符,还包括逻辑操作符.按位操作符.移位操作符.三元操作符等等 ...

  7. 快排的python实现

    快排的python实现 #python 2.7 def quick_sort(L): if len(L) <= 1: return L else: return quick_sort([lt f ...

  8. [转载] FFmpeg源代码简单分析:常见结构体的初始化和销毁(AVFormatContext,AVFrame等)

    ===================================================== FFmpeg的库函数源代码分析文章列表: [架构图] FFmpeg源代码结构图 - 解码 F ...

  9. CSS3的圆角border-radius属性

    一,语法解释 border-radius : none | <length>{1,4} [/ <length>{1,4} ] <length>: 由浮点数字和单位标 ...

  10. 使用appassembler-maven-plugin插件生成启动脚本

    appassembler-maven-plugin可以自动生成跨平台的启动脚本,省去了手工写脚本的麻烦,而且还可以生成jsw的后台运行程序. 首先pom引入相关依赖 <build> < ...