Spring Boot入门——JDBCTemplate使用及其相关问题解决
1、在pom.xml文件中引入相应依赖
<!-- mysql依赖 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.42</version>
</dependency> <!-- jdbc依赖 -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
2、创建Grade类
public class Grade { private int id;
private String gradeNm;
private int teacherId; public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getGradeNm() {
return gradeNm;
}
public void setGradeNm(String gradeNm) {
this.gradeNm = gradeNm;
}
public int getTeacherId() {
return teacherId;
}
public void setTeacherId(int teacherId) {
this.teacherId = teacherId;
}
}
3、创建GradeDAO
在insert方法中获取自增长id,在findByGradeNm和findAll方法中封装返回对象
import java.sql.ResultSet;
import java.sql.SQLException; import javax.annotation.Resource; import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository; import com.wyl.bean.Grade; @Repository
public class GradeDAO{ @Resource
private JdbcTemplate jdbcTemplate; public Grade findByGradeNm(String gradeNm) {
String sql = "select * from Grade where grade_Nm='" + gradeNm + "'";
RowMapper<Grade> rm = new GradeRowMapper();
return jdbcTemplate.queryForObject(sql,rm);
} public List<Grade> findAll() {
String sql = "select * from Grade";
RowMapper<Grade> rm = new GradeRowMapper();
return jdbcTemplate.query(sql, rm);
}
/*
* jdbc默认插入数据库中没有返回集 ,可以对数据进行封装,使其返回插入的对象
*/
public Grade insertGrade(final Grade grade){
final String sql = "insert into grade(grade_nm, teacher_id) values(?,?)";
KeyHolder holder = new GeneratedKeyHolder();
jdbc.update(new PreparedStatementCreator() {
@Override
public PreparedStatement createPreparedStatement(Connection connection) throws SQLException {
// TODO Auto-generated method stub
PreparedStatement ps = connection.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
ps.setString(1, grade.getGradeNm());
ps.setInt(2, grade.getTeacherId());
return ps;
}
}, holder);
int newGradeId = holder.getKey().intValue();//获得自增长的id
grade.setId(newGradeId);
return grade;
}
/*
* 必须自己手动封装Grade类,因为Springboot默认将数据库中的一列封装为一个对象
*/
class GradeRowMapper implements RowMapper<Grade>{ @Override
public Grade mapRow(ResultSet rs, int rowNum) throws SQLException {
// TODO Auto-generated method stub
Grade grade = new Grade();
grade.setGradeNm(rs.getString("grade_nm"));
grade.setId(rs.getInt("id"));
grade.setTeacherId(rs.getInt("teacher_id"));
return grade;
}
}
}
4、创建GradeService
import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.wyl.bean.Grade;
import com.wyl.dao.GradeDAO; /**
* GradeService类,调用gradeDAO中的方法
* */
@Service
public class GradeService { @Resource
private GradeDAO gradeDAO; public Grade fingByGradeNm(String gradeNm){
return gradeDAO.findByGradeNm(gradeNm);
}
public List<Grade> fingAll(){
return gradeDAO.findAll();
}
public Grade insertGrade(Grade grade){
return gradeDAO.insertGrade(grade);
}
}
5、创建GradeController
import javax.annotation.Resource; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController; import com.wyl.bean.Grade;
import com.wyl.service.GradeService; @RestController
public class JPAController { @Resource
private GradeService gradeService; @RequestMapping("/finfByGradeNm")
public Grade finfByGradeNm(String gradeNm){
System.out.println("finfByGradeNm");
return gradeService.fingByGradeNm(gradeNm);
} @RequestMapping("/findAll")
public List<Grade> findAll(String gradeNm){
System.out.println("findAll");
return gradeService.fingAll();
} @RequestMapping("/insertGrade")
public Grade insertGrade(Grade grade){
System.out.println("insertGrade");
return gradeService.insertGrade(grade);
}
}
6、测试
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration$LiquibaseConfiguration': Invocation of init method failed; nested exception is java.lang.IllegalStateException: Cannot find changelog location: class path resource [db/changelog/db.changelog-master.yaml] (please add changelog or check your Liquibase configuration)
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:137) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:409) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1620) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:555) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:483) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:306) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:230) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:302) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:197) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:761) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:866) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:542) ~[spring-context-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.boot.context.embedded.EmbeddedWebApplicationContext.refresh(EmbeddedWebApplicationContext.java:122) ~[spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:737) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:370) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:314) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1162) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1151) [spring-boot-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at com.wyl.App.main(App.java:16) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_60]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_60]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_60]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_60]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-1.5.3.RELEASE.jar:1.5.3.RELEASE]
Caused by: java.lang.IllegalStateException: Cannot find changelog location: class path resource [db/changelog/db.changelog-master.yaml] (please add changelog or check your Liquibase configuration)
at org.springframework.util.Assert.state(Assert.java:70) ~[spring-core-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.boot.autoconfigure.liquibase.LiquibaseAutoConfiguration$LiquibaseConfiguration.checkChangelogExists(LiquibaseAutoConfiguration.java:92) ~[spring-boot-autoconfigure-1.5.3.RELEASE.jar:1.5.3.RELEASE]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_60]
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) ~[na:1.8.0_60]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:1.8.0_60]
at java.lang.reflect.Method.invoke(Method.java:497) ~[na:1.8.0_60]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:366) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:311) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:134) ~[spring-beans-4.3.8.RELEASE.jar:4.3.8.RELEASE]
... 23 common frames omitted
测试出现以上问题是因为liquibase中需要db.changelog-master.yaml文件
解决方法:
1、在application.properties中添加如下代码:
liquibase.change-log=classpath:/liquibase/db.changelog.xml
2、在src/main/resource包下创建/liquibase/db.changelog.xml目录,并且db.changelog.xml中的内容如下:
<?xml version="1.0" encoding="UTF-8"?>
<databaseChangeLog xmlns="http://www.liquibase.org/xml/ns/dbchangelog/1.9"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.liquibase.org/xml/ns/dbchangelog/1.9
http://www.liquibase.org/xml/ns/dbchangelog/dbchangelog-1.9.xsd">
<changeSet id="1" author="jim"> <createTable tableName="useraccount">
<column name="userid" type="bigint(20)">
<constraints primaryKey="true" />
</column>
<column name="accountstate" type="varchar(255)" />
<column name="expiredDate" type="datetime" />
<column name="username" type="varchar(255)" />
</createTable> <addUniqueConstraint tableName="useraccount"
columnNames="username" constraintName="username" /> </changeSet> <changeSet id="2" author="jim"> <addColumn tableName="useraccount">
<column name="gender" type="varchar(1)" value="M">
<constraints nullable="false" />
</column>
</addColumn> </changeSet> </databaseChangeLog>
解决之后的测试结果:
insert方法返回插入的对象:
Spring Boot入门——JDBCTemplate使用及其相关问题解决的更多相关文章
- Spring Boot入门系列(十四)使用JdbcTemplate操作数据库,配置多数据源!
前面介绍了Spring Boot 中的整合Mybatis并实现增删改查.如何实现事物控制.不清楚的朋友可以看看之前的文章:https://www.cnblogs.com/zhangweizhong/c ...
- spring boot与jdbcTemplate的整合案例2
简单入门了spring boot后,接下来写写跟数据库打交道的案例.博文采用spring的jdbcTemplate工具类与数据库打交道. 下面是搭建的springbootJDBC的项目的总体架构图: ...
- spring boot 系列之三:spring boot 整合JdbcTemplate
前面两篇文章我们讲了两件事情: 通过一个简单实例进行spring boot 入门 修改spring boot 默认的服务端口号和默认context path 这篇文章我们来看下怎么通过JdbcTemp ...
- Spring Boot 入门之持久层篇(三)
原文地址:Spring Boot 入门之持久层篇(三) 博客地址:http://www.extlight.com 一.前言 上一篇<Spring Boot 入门之 Web 篇(二)>介绍了 ...
- Spring Boot入门系列(二十)快速打造Restful API 接口
spring boot入门系列文章已经写到第二十篇,前面我们讲了spring boot的基础入门的内容,也介绍了spring boot 整合mybatis,整合redis.整合Thymeleaf 模板 ...
- Spring Boot入门教程1、使用Spring Boot构建第一个Web应用程序
一.前言 什么是Spring Boot?Spring Boot就是一个让你使用Spring构建应用时减少配置的一个框架.约定优于配置,一定程度上提高了开发效率.https://zhuanlan.zhi ...
- Spring Boot入门(五):使用JDBC访问MySql数据库
本系列博客记录自己学习Spring Boot的历程,如帮助到你,不胜荣幸,如有错误,欢迎指正! 在程序开发的过程中,操作数据库是必不可少的部分,前面几篇博客中,也一直未涉及到数据库的操作,本篇博客 就 ...
- Spring boot 入门(四):集成 Shiro 实现登陆认证和权限管理
本文是接着上篇博客写的:Spring boot 入门(三):SpringBoot 集成结合 AdminLTE(Freemarker),利用 generate 自动生成代码,利用 DataTable 和 ...
- Spring boot入门(三):SpringBoot集成结合AdminLTE(Freemarker),利用generate自动生成代码,利用DataTable和PageHelper进行分页显示
关于SpringBoot和PageHelper,前篇博客已经介绍过Spring boot入门(二):Spring boot集成MySql,Mybatis和PageHelper插件,前篇博客大致讲述了S ...
随机推荐
- oracle 查看表是否被锁
--以下几个为相关表SELECT * FROM v$lock;SELECT * FROM v$sqlarea;SELECT * FROM v$session;SELECT * FROM v$proce ...
- <2013 07 06> "极路由" 与 “家庭服务器” 报道两则
跟我做!打造家庭服务器 很久没有更新了,因为之前托朋友帮我弄的mini PC终于到手了.阴差阳错地,原来只打算弄一台将就可用的低功耗下载机,结果到手的却是一台支持1080p(宣称,还没烧过),还带遥控 ...
- Java你不知道的那些事儿—Java隐藏特性
转载自:http://www.cnblogs.com/lanxuezaipiao/p/3460373.html 每 种语言都很强大,不管你是像我一样的初学者还是有过N年项目经验的大神,总会有你不知道的 ...
- Grunt自动化工具相关
Grunt 项目中安装grunt模块npm install grunt --save,删除模块 npm uninstall grunt ,缺失某个插件:npm install grunt-contri ...
- python多进程编程(一)
multiprocessing模块介绍 python中的多线程无法利用多核优势,如果想要充分地使用多核CPU的资源(os.cpu_count()查看),在python中大部分情况需要使用多进程.Pyt ...
- MySQL 第六天
回顾 外键: 关联关系(表与表之间: 表中字段指向另外一张表的主键) 外键条件: 字段类型必须一致, 存储引擎必须为innodb 外键约束: 子表约束: 不能插入父表不存在的记录 父表约束: 三种 ...
- 曾经跳过的坑------replace、替换斜杠反斜杠、时间格式化处理
JAVA 中: 坑一: replace没有用对象进行接收.直接使用 dateStr.replaceAll("\\/", "-"); 是不行的,至少得加上 &qu ...
- 根据GUID获取设备信息
#include <windows.h> #include <setupapi.h> #include <objbase.h> #include <initg ...
- Java访问网络url,获取网页的html代码
在Java中,Java.net包里面的类是进行网络编程的,其中,java.net.URL类和java.net.URLConection类是编程者方便地利用URL在Internet上进行网络通信.有两种 ...
- Linux CentOS7安装Mysql5.7
一.下载mysql mkdir /home/install #创建install目录 在/home/install目录下下载mysql5.7 wget https://cdn.mysql.com//D ...