Spring JDBC操作数据库示例
1、所需jar包
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
<maven.compiler.target>1.8</maven.compiler.target>
<maven.compiler.source>1.8</maven.compiler.source>
<servletApiVersion>3.1.0</servletApiVersion>
<springSecurityVersion>3.2.0.RELEASE</springSecurityVersion>
<springVersion>4.0.7.RELEASE</springVersion>
<thymeleafVersion>2.1.3.RELEASE</thymeleafVersion>
</properties> <dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${springVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-config</artifactId>
<version>${springSecurityVersion}</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-web</artifactId>
<version>${springSecurityVersion}</version>
</dependency> <dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-dbcp2</artifactId>
<version>2.5.0</version>
</dependency> <dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.12</version>
</dependency> <dependency>
<groupId>org.thymeleaf</groupId>
<artifactId>thymeleaf-spring4</artifactId>
<version>${thymeleafVersion}</version>
</dependency>
<dependency>
<groupId>org.thymeleaf.extras</groupId>
<artifactId>thymeleaf-extras-springsecurity3</artifactId>
<version>2.1.1.RELEASE</version>
</dependency> <dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>${servletApiVersion}</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
</dependencies>
2、WEB应用配置类
package test; import org.springframework.web.servlet.support.AbstractAnnotationConfigDispatcherServletInitializer;
import test.config.RootConfig;
import test.config.WebConfig; public class WebInitializer extends AbstractAnnotationConfigDispatcherServletInitializer { @Override
protected Class<?>[] getRootConfigClasses() {
return new Class<?>[]{RootConfig.class};
} @Override
protected Class<?>[] getServletConfigClasses() {
return new Class<?>[]{WebConfig.class};
} @Override
protected String[] getServletMappings() {
return new String[]{"/"};
}
}
其中
RootConfig类
package test.config; import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.ComponentScan.Filter;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.web.servlet.config.annotation.EnableWebMvc; @Configuration
@ComponentScan(basePackages = {"test"},
excludeFilters = {
@Filter(type = FilterType.ANNOTATION, value = EnableWebMvc.class)
})
public class RootConfig { }
WebConfig类
package test.config; import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.DefaultServletHandlerConfigurer;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.thymeleaf.extras.springsecurity3.dialect.SpringSecurityDialect;
import org.thymeleaf.spring4.SpringTemplateEngine;
import org.thymeleaf.spring4.view.ThymeleafViewResolver;
import org.thymeleaf.templateresolver.ServletContextTemplateResolver;
import org.thymeleaf.templateresolver.TemplateResolver; @Configuration
@EnableWebMvc
@ComponentScan("test")
public class WebConfig extends WebMvcConfigurerAdapter { @Bean
public ViewResolver viewResolver(SpringTemplateEngine templateEngine) {
ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
viewResolver.setTemplateEngine(templateEngine);
return viewResolver;
} @Bean
public SpringTemplateEngine templateEngine(TemplateResolver templateResolver) {
SpringTemplateEngine templateEngine = new SpringTemplateEngine();
templateEngine.setTemplateResolver(templateResolver);
templateEngine.addDialect(new SpringSecurityDialect());
return templateEngine;
} @Bean
public TemplateResolver templateResolver() {
TemplateResolver templateResolver = new ServletContextTemplateResolver();
templateResolver.setPrefix("/WEB-INF/templates/");
templateResolver.setSuffix(".html");
templateResolver.setTemplateMode("HTML5");
return templateResolver;
} @Override
public void addViewControllers(ViewControllerRegistry registry) {
registry.addViewController("/login").setViewName("login");
}
}
3、定义实体类
Category.java
package test;
public class Category {
private int id;
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Override
public String toString() {
return "Category{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}
创建数据库
create database test;
use test;
CREATE TABLE category_ (
id int(11) NOT NULL AUTO_INCREMENT,
name varchar(30),
PRIMARY KEY (id)
) DEFAULT CHARSET=UTF8;
定义增、删、改、查方法
package test; import org.springframework.stereotype.Component; @Component
public interface CategoryService { void insert(Category category); void delete(int id); void update(Category category); Category get(int id);
}
4、数据库设置,配置数据库连接url、用户名、密码等
package test.config; import com.mysql.cj.jdbc.Driver;
import org.apache.commons.dbcp2.BasicDataSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.core.JdbcTemplate; import javax.sql.DataSource; @Configuration
public class DataConfig { @Bean
public JdbcTemplate jdbcTemplate(DataSource dataSource) {
return new JdbcTemplate(dataSource);
} @Bean
public DataSource dateSource() throws Exception {
BasicDataSource dataSource = new BasicDataSource();
dataSource.setDriver(new Driver());
dataSource.setUrl("jdbc:mysql://127.0.0.1:3306/test?userUnicode=true&characterEncoding=utf-8&serverTimezone=GMT%2B8");
dataSource.setUsername("root");
dataSource.setPassword("admin");
dataSource.setInitialSize(5);
dataSource.setMaxTotal(10);
return dataSource;
}
}
5、实现CaategoryService类中定义的增、删、改、查方法
package test; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcOperations;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Component; import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; @Component
public class CategoryServiceImpl implements CategoryService { @Override
public void insert(Category category) {
jdbcOperations.update("insert into category_ (name) values (?)", category.getName());
} @Override
public void delete(int id) {
jdbcOperations.execute(String.format("delete from category_ where id = %1$s", id));
} @Override
public void update(Category category) {
jdbcOperations.update("update category_ set name = ? where id = ?", category.getName(), category.getId());
} @Override
public Category get(int id) {
return jdbcOperations.queryForObject("select id, name from category_ where id = ?", new CategoryRowMapper(), id);
} @Autowired
private JdbcOperations jdbcOperations; private static final class CategoryRowMapper implements RowMapper<Category> {
@Override
public Category mapRow(ResultSet resultSet, int i) throws SQLException {
String name = resultSet.getString("name");
int id = resultSet.getInt("id");
Category category = new Category();
category.setId(id);
category.setName(name);
return category;
}
}
}
6、定义web接口并测试
package test.controller; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import test.Category;
import test.CategoryService; import static org.springframework.web.bind.annotation.RequestMethod.GET; @Controller
@RequestMapping("/")
public class HomeController { @Autowired
private CategoryService categoryService; @RequestMapping(method = {GET}, value = "/insert")
@ResponseBody
public String add(String name) {
if (name == null || name.length() == 0) {
return "fail";
}
try {
Category student = new Category();
student.setName(name);
categoryService.insert(student);
return "success";
} catch (Exception e) {
return "fail";
}
} @ResponseBody
@RequestMapping(method = GET, value = "/delete/{id}")
public String delete(@PathVariable int id) {
try {
categoryService.delete(id);
} catch (Exception e) {
return "fail";
}
return "success";
} @ResponseBody
@RequestMapping(method = GET, value = "/update/{id}")
public String update(@PathVariable int id, String name) {
try {
Category category = new Category();
category.setId(id);
category.setName(name);
categoryService.update(category);
} catch (Exception e) {
return "fail";
}
return "success";
} @ResponseBody
@RequestMapping(method = GET, value = "/query/{id}")
public String get(@PathVariable int id) {
try {
return String.valueOf(categoryService.get(id));
} catch (Exception e) {
return "fail";
}
} }
http://localhost:8080/insert?name=A 插入数据
假设插入的数据id为10
http://localhost:8080/update/10?name=Bb 更新数据
http://localhost:8080/query/10 查询数据
http://localhost:8080/delete/10 删除数据
Spring JDBC操作数据库示例的更多相关文章
- Spring入门(十五):使用Spring JDBC操作数据库
在本系列的之前博客中,我们从没有讲解过操作数据库的方法,但是在实际的工作中,几乎所有的系统都离不开数据的持久化,所以掌握操作数据库的使用方法就非常重要. 在Spring中,操作数据库有很多种方法,我们 ...
- JDBC操作数据库的学习(1)
单单对数据库的操作,比如说MySQL,我们可以在命令行窗口中执行,但是一般是应用程序要操作数据库,因此我们应该在程序中的代码上体现对数据库的操作,那么使用程序应用如何操作数据库呢?那就要使用到数据库的 ...
- JDBC操作数据库的三种方式比较
JDBC(java Database Connectivity)java数据库连接,是一种用于执行上sql语句的javaAPI,可以为多种关系型数据库提供统一访问接口.我们项目中经常用到的MySQL. ...
- 用于JDBC操作数据库的公共类
/* * @(#)CommonSql.java 2011-9-5 * * Copyright 2011 Bianjing,All rights reserved. */ import java.sql ...
- JDBC操作数据库的学习(2)
在上一篇博客<JDBC操作数据库的学习(1)>中通过对例1,我们已经学习了一个Java应用如何在程序中通过JDBC操作数据库的步骤流程,当然我们也说过这样的例子是无法在实际开发中使用的,本 ...
- Spark Streaming通过JDBC操作数据库
本文记录了学习使用Spark Streaming通过JDBC操作数据库的过程,源数据从Kafka中读取. Kafka从0.10版本提供了一种新的消费者API,和0.8不同,因此Spark Stream ...
- JDBC操作数据库的基本步骤:
JDBC操作数据库的基本步骤: 1)加载(注册)数据库驱动(到JVM). 2)建立(获取)数据库连接. 3)创建(获取)数据库操作对象. 4)定义操作的SQL语句. 5)执行数据库操作. 6)获取并操 ...
- springboot学习-jdbc操作数据库--yml注意事项--controller接受参数以及参数校验--异常统一管理以及aop的使用---整合mybatis---swagger2构建api文档---jpa访问数据库及page进行分页---整合redis---定时任务
springboot学习-jdbc操作数据库--yml注意事项--controller接受参数以及参数校验-- 异常统一管理以及aop的使用---整合mybatis---swagger2构建api文档 ...
- Java笔记(第七篇 JDBC操作数据库)
JDBC是连接数据库和java程序的桥梁,通过JDBC API可以方便地实现对各种主流数据库的操作.学习java语言,必须学习JDBC技术,因为JDBC技术实在java语言中被广泛使用的一种操作数据库 ...
随机推荐
- 修改eclipse默认注释
windows-->preference-->Java-->Code Style-->Code Templates -->Comments :注释--> ... 关 ...
- ROS开发过程中遇到:Could not find a package configuration file provided by "qt_build" with any of the following names: qt_buildConfig.cmake qt_build-config.cmake........
最近在搭建QT开发ROS 界面的环境,遇到了很多问题,参考了很多资料,最后发现有些问题其实没有那么复杂,只是我们对整体环境还不了解,熟悉了以后你会发现有些问题就迎刃而解了. 在这个过程中,我首先新建了 ...
- Libev源码分析01:Libev中的监视器结构(C结构体实现继承)
在Libev的源码中,用到了一种用C实现类似C++中继承的技巧,主要是用宏和结构体实现. 在Libev中,最关键的数据结构就是各种监视器,比如IO监视器,信号监视器等等.这些监视器的多数成员都是一样的 ...
- codeforces2B.The least round way 题解 动态规划/模拟
题目出处:http://codeforces.com/problemset/problem/2/B 题目描述 给你一个 \(n \times n\) 的二维数组,它包含的元素都是非负整数.你需要寻找一 ...
- hdu 4063 Aircraft (Geometry + SP)
Problem - 4063 几何加简单最短路. 题意是给出若干圆的圆心以及半径,求出从给出的起点到终点的最短路径的长度,可以移动的区域是圆覆盖到的任意一个位置. 做法是这样的,对圆两两求交点,用这些 ...
- 不需内测账号,带你体验微信小程序完整开发过程
不需内测账号,带你体验微信小程序完整开发过程 2016年09月24日 - 作者: SwiftCafe 微信小程序还没正式发布就已经迅速成为大家讨论的焦点,那么大家可能觉得只有收到内测邀请才能体验小程序 ...
- C#循环语句练习(三)
for循环拥有两类:一.穷举:把所有可能的情况都走一遍,使用if条件筛选出来满足条件的情况. (1).羽毛球拍15元,球3元,水2元.200元每种至少一个,有多少可能. (2).百鸡百钱:公鸡2文钱一 ...
- HDU 1698 Just a Hook 线段树区间更新、
来谈谈自己对延迟标记(lazy标记)的理解吧. lazy标记的主要作用是尽可能的降低时间复杂度. 这样说吧. 如果你不用lazy标记,那么你对于一个区间更新的话是要对其所有的子区间都更新一次,但如果用 ...
- [全+转载] solaris 网络配置
===================== 较为重要的几个文件: /etc/nodename 主机名(即 hostname命令的输出) /etc/defaul ...
- CodeForces 620E"New Year Tree"(DFS序+线段树+状态压缩)
传送门 •题意 给你一颗 n 个节点的树,每个节点被染上了颜色: 有 m 次操作,每次操作的类型有两种 1 v c : 将以 v 为根的子树的结点全部涂成 c 2 v : 询问以 v 为根的子树的结点 ...