Spring Boot入门——JDBCTemplate使用及其相关问题解决
Posted Miss_wang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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使用及其相关问题解决的主要内容,如果未能解决你的问题,请参考以下文章