本文介绍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. zend studio 添加xdebug调试php代码

    1.Eclipse下对于大部分语言都提供了调试器接口,自然的对于PHP,Zend已经集成了XDebug调试器,找到Zend中的Preferences->PHP->Debug, 将调试器设置 ...

  2. python面向对象编程 继承 组合 接口和抽象类

    1.类是用来描述某一类的事物,类的对象就是这一类事物中的一个个体.是事物就要有属性,属性分为 1:数据属性:就是变量 2:函数属性:就是函数,在面向对象里通常称为方法 注意:类和对象均用点来访问自己的 ...

  3. 蓝牙(cc2540) 协议栈 学习一

    ---------------------------------------------------------- app ------------------------------------- ...

  4. 下载并安装Prism5.0库(纯汉语版)

    Prism5.0中包含了文档,WPF代码示例,程序集.本篇告诉你从哪里获取程序集和代码示例,还有NuGet包的内容. 对于新功能,资产,和API的更改信息,请看Prism5.0新内容. 文档 Pris ...

  5. struts转换器

    struts转换器:在B/S应用中,将字符串请求参数转换为相应的数据类型,是MVC框架提供的功能,而Struts2是很好的MVC框架实现者,理所当然,提供了类型转换机制. 一.类型转换的意义 对于一个 ...

  6. hibernate validate验证框架中@NotEmpty、@NotbBank、@NotNull的区别

    Hibernate Validator验证框架中@NotEmpty.@NotBlank.@NotNull 的区别 Hibernate Validator验证框架中@NotEmpty.@NotBlank ...

  7. 【tensorflow:Google】三、tensorflow入门

    [一]计算图模型 节点是计算,边是数据流, a = tf.constant( [1., 2.] )定义的是节点,节点有属性 a.graph 取得默认计算图 g1 = tf.get_default_gr ...

  8. JS 页面加载触发事件 document.ready和onload的区别

    document.ready和onload的区别——JavaScript文档加载完成事件页面加载完成有两种事件: 一是ready,表示文档结构已经加载完成(不包含图片等非文字媒体文件): 二是onlo ...

  9. win7 秘钥

    链接 安装好Windows7后右击计算机--属性--更改产品密匙 输入以下密匙; RHTBY-VWY6D-QJRJ9-JGQ3X-Q2289 HT6VR-XMPDJ-2VBFV-R9PFY-3VP7R ...

  10. int 21h 汇编

    INT 21H 指令说明及使用方法 转自http://www.cnblogs.com/ynwlgh/archive/2011/12/12/2285017.html 很多初学汇编语言的同学可能会对INT ...