文档

Jdbc的使用

基础的代码结构:

一个Application作为入口。IUserRepositoryUserRepository作为具体的实现。applicationContext.xml定义spring的配置。db.properties保存数据库相关的信息。

环境搭建步骤

新建项目

新建一个maven项目,编辑pom.xml文件,如下。除了mysql的驱动,其他是必须的。

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion> <groupId>com.lou.spring.demo5.tx</groupId>
<artifactId>lou-spring-demo5-tx</artifactId>
<version>1.0-SNAPSHOT</version> <dependencies>
<!--spring的核心-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>4.3.25.RELEASE</version>
</dependency>
<!--orm相关,比如jdbctemplate-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>4.3.25.RELEASE</version>
</dependency>
<!--mysql数据库驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.6</version>
</dependency>
<!-- datasource 数据源 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.7.0</version>
</dependency>
</dependencies>
</project>

applicationContext.xml

在resources下面添加spring的配置文件applicationContext.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 https://www.springframework.org/schema/context/spring-context.xsd"> <!-- 1.无需定义repository注解,通过属性设置的方式进行-->
<bean id="userRepository1" class="com.lou.spring.demo5.tx.UserRepository">
<property name="jdbcTemplate" ref="dataSource"></property>
</bean> <!-- 2.使用Component-scan的方式配合@repository注解-->
<!-- <context:component-scan base-package="com.lou.spring.demo5.tx"></context:component-scan>--> <bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource">
<property name="driverClassName" value="${jdbc.dirverClassName}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 上面datasource用到的属性值来自这个-->
<context:property-placeholder location="db.properties"></context:property-placeholder>
</beans>

db.properties

在resources下面添加db.properties文件

jdbc.dirverClassName=com.mysql.cj.jdbc.Driver
jdbc.username=root
jdbc.password=123456
jdbc.url=jdbc:mysql://localhost:3306/test1?useSSL=false

Repository

添加IUserRepository和UserRepository用于数据库的访问。

IUserRepository.java

package com.lou.spring.demo5.tx;

public interface IUserRepository {
//显示总数
void showCount();
}

UserRepository.java

package com.lou.spring.demo5.tx;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository; import javax.sql.DataSource; @Repository
public class UserRepository implements IUserRepository {
private JdbcTemplate jdbcTemplate; @Autowired
public void setJdbcTemplate(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
} @Override
public void showCount() {
Integer count = jdbcTemplate.queryForObject("select count(*) from account", Integer.class);
System.out.println(count);
}
}
  • 不使用Repository和Autowired注解方式

    没有开启Repository和Autowired注解,所以,需要在xml中手动配置。确保set方法的后面部分和applicationContext.xml#userRepository1#property的name字段名字是一样的。然后传入一个DataSource参数,也就是property的ref引用

  • 开启Repository和Autowired注解方式

    开启了注解之后就需要定义在applicationContext.xml中定义component-scan,然后spring自己去扫描查找需要的依赖。

程序入口

新建Application.java 作为程序入口。

package com.lou.spring.demo5.tx;

import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.support.ClassPathXmlApplicationContext; public class Application {
public static void main(String[] args) {
ClassPathXmlApplicationContext classPathXmlApplicationContext = new ClassPathXmlApplicationContext("applicationContext.xml");
BasicDataSource dataSource = (BasicDataSource) classPathXmlApplicationContext.getBean("dataSource");
//用来测试数据源是否通
System.out.println(dataSource);
//通过id的方式获取
UserRepository userRepository = (UserRepository) classPathXmlApplicationContext.getBean("userRepository1");
userRepository.showCount();
//通过class的方式获取
UserRepository userRepository1 = classPathXmlApplicationContext.getBean(UserRepository.class);
userRepository1.showCount();
}
}

使用demo

先定义一个User对象

User.java

package com.lou.spring.demo5.tx;

public class User {
private Integer id;
private String name;
private Integer age; public Integer getId() {
return id;
} public void setId(Integer id) {
this.id = id;
} public String getName() {
return name;
} public void setName(String name) {
this.name = name;
} public Integer getAge() {
return age;
} public void setAge(Integer age) {
this.age = age;
} @Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}

查询相关(select)

修改一下IUserRepository,增加如下内容。

public interface IUserRepository {
//总行数查询
Integer getTotalCount();
//带条件的总行数查询
Integer getTotalCount(String name);
//查询一个String
String getName();
//查询一个对象
User getUser();
//查询对象集合
List<User> getUsers();
}

具体实现:

@Repository
public class UserRepository implements IUserRepository {
private JdbcTemplate jdbcTemplate; @Autowired
public void setJdbcTemplate111(DataSource dataSource) {
this.jdbcTemplate = new JdbcTemplate(dataSource);
} @Override
public Integer getTotalCount() {
Integer userCount = jdbcTemplate.queryForObject("select count(*) from user", Integer.class);
return userCount;
} @Override
public Integer getTotalCount(String name) {
Integer louCount = jdbcTemplate.queryForObject("select count(*) from user where name like ?", Integer.class, name);
return louCount;
} @Override
public String getName() {
String name = jdbcTemplate.queryForObject("select name from user where id=?", new Object[]{1}, String.class);
return name;
} @Override
public User getUser() {
User user = jdbcTemplate.queryForObject("select * from user where id = ?", new Object[]{1}, new UserMapper());
return user;
} @Override
public List<User> getUsers() {
List<User> users = jdbcTemplate.query("select * from user", new UserMapper());
return users;
} //抽取公共的RowMapper<User>,内部私有的class,放外面的话是要public,非static
private static final class UserMapper implements RowMapper<User> {
@Override
public User mapRow(ResultSet resultSet, int i) throws SQLException {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setAge(resultSet.getInt("age"));
return user;
}
}
}

使用RowMapper对结果集做映射。UserMapper是一个私有的静态类。使用的时候需要new。

update相关(包括insert,update,delete)

@Override
public Integer insertUser(User u) {
return jdbcTemplate.update("insert into user (name,age) values(?,?)", u.getName(), u.getAge());
} @Override
public Integer updateUser(Integer userId, String name) {
return jdbcTemplate.update("update user set name=? where id=?", name, userId);
} @Override
public Integer deleteUser(Integer userId) {
return jdbcTemplate.update("delete from user where id = ?", userId);
}

execute 方法

用来执行create table 或者调用存储过程之类的sql语句。

this.jdbcTemplate.execute("create table mytable (id integer, name varchar(100))");
this.jdbcTemplate.update(
"call SUPPORT.REFRESH_ACTORS_SUMMARY(?)",
Long.valueOf(unionId));

JdbcTemplate的最佳实践

JdbcTemplate一旦被配置之后,他的实例就是线程安全的。这一点比较重要,因为这样你就可以把他注入到多个DAO或者Repository中。按照前文先配置DataSource,然后在构造函数里面实例化JdbcTemplate

总结

新建项目,添加依赖,添加spring的xml配置文件,写repo,写application,获取bean,运行。

【翻译】spring-data 之JdbcTemplate 使用的更多相关文章

  1. spring data之JDBCTemplate学习笔记

    一.spring 数据访问哲学 1.为避免持久化的逻辑分散在程序的各个组件中,数据访问的功能应到放到一个或多个专注于此的组件中,一般称之为数据访问对象(data access object,DAO). ...

  2. spring boot(五):spring data jpa的使用

    在上篇文章springboot(二):web综合开发中简单介绍了一下spring data jpa的基础性使用,这篇文章将更加全面的介绍spring data jpa 常见用法以及注意事项 使用spr ...

  3. springboot:spring data jpa介绍

    转载自:https://www.cnblogs.com/ityouknow/p/5891443.html 在上篇文章springboot(二):web综合开发中简单介绍了一下spring data j ...

  4. spring boot(五)Spring data jpa介绍

    在上篇文章springboot(二):web综合开发中简单介绍了一下spring data jpa的基础性使用,这篇文章将更加全面的介绍spring data jpa 常见用法以及注意事项 使用spr ...

  5. springboot(五):spring data jpa的使用

    在上篇文章springboot(二):web综合开发中简单介绍了一下spring data jpa的基础性使用,这篇文章将更加全面的介绍spring data jpa 常见用法以及注意事项 使用spr ...

  6. SpringBoot(五) :spring data jpa 的使用

    原文出处: 纯洁的微笑 在上篇文章springboot(二):web综合开发中简单介绍了一下spring data jpa的基础性使用,这篇文章将更加全面的介绍spring data jpa 常见用法 ...

  7. Spring Data JPA教程, 第三部分: Custom Queries with Query Methods(翻译)

    在本人的Spring Data JPA教程的第二部分描述了如何用Spring Data JPA创建一个简单的CRUD应用,本博文将描述如何在Spring Data JPA中使用query方法创建自定义 ...

  8. Spring Data JPA教程, 第二部分: CRUD(翻译)

    我的Spring Data Jpa教程的第一部分描述了,如何配置Spring Data JPA,本博文进一步描述怎样使用Spring Data JPA创建一个简单的CRUD应用.该应用要求如下: pe ...

  9. Spring Data JPA教程,第一部分: Configuration(翻译)

    Spring Data JPA项目旨在简化基于仓库的JPA的创建并减少与数据库交互的所需的代码量.本人在自己的工作和个人爱好项目中已经使用一段时间,它却是是事情如此简单和清洗,现在是时候与你分享我的知 ...

  10. Spring Data JPA 教程(翻译)

    写那些数据挖掘之类的博文 写的比较累了,现在翻译一下关于spring data jpa的文章,觉得轻松多了. 翻译正文: 你有木有注意到,使用Java持久化的API的数据访问代码包含了很多不必要的模式 ...

随机推荐

  1. [转]VB.NET DataTable Select Function

    本文转自:https://www.dotnetperls.com/datatable-select-vbnet VB.NET DataTable Select Function This VB.NET ...

  2. [转]自定义UiPath Activity实践

    本文转自:https://segmentfault.com/a/1190000017440647 为了对UiPath Activity的实现方式一探究竟,自己尝试实践编写了一个简单的Activity, ...

  3. PWA学习笔记(二)

    设计与体验 APP Shell: 1.应用从显示内容上可粗略划分为内容部分和外壳部分,App Shell 就是外壳部分,即页面的基本结构 2.它不仅包括用户能看到的页面框架部分,还包括用户看不到的代码 ...

  4. web项目踩坑过程

    sql函数设计: 一开始本来是直接用Java的jdbc直接传输操作语句的.但后来学了存储过程发现存储过程可以提高不少的效率.就重构了自己对数据库的操作代码.包括:开启,查找,修改,关闭. 开启:直接使 ...

  5. August 11th, 2019. Week 33rd, Sunday

    Worry does not empty tomorrow of its sorrow. It empties today of its strength. 忧虑不会消除明天的痛苦,它只会削弱今天的力 ...

  6. python爬取网页数据

    一.利用webbrowser.open()打开一个网站: ? 1 2 3 >>> import webbrowser >>> webbrowser.open('ht ...

  7. python访问kafka

    操作系统 : CentOS7.3.1611_x64 Python 版本 : 3.6.8 kafka 版本 : 2.3.1 本文记录python访问kafka的简单使用,是入门教程,高阶读者请直接忽略. ...

  8. 利用百度文字识别API识别图像中的文字

      本文将会介绍如何使用百度AI开放平台中的文字识别服务来识别图片中的文字.百度AI开放平台的访问网址为:http://ai.baidu.com/ ,为了能够使用该平台提供的AI服务,你需要事先注册一 ...

  9. 创建多进程之multiprocess包中的process模块

    创建多进程之multiprocess包中的process模块 1.process模块是一个创建进程的模块 Process([group [, target [, name [, args [, kwa ...

  10. three.js实现世界地图城市迁徙图

    概况如下: 1.THREE.CylinderGeometry,THREE.SphereGeometry绘制地图上的标记: 2.THREE.CanvasTexture用于加载canvas绘制的字体: 3 ...