Java自学者论坛

 找回密码
 立即注册

手机号码,快捷登录

恭喜Java自学者论坛(https://www.javazxz.com)已经为数万Java学习者服务超过8年了!积累会员资料超过10000G+
成为本站VIP会员,下载本站10000G+会员资源,会员资料板块,购买链接:点击进入购买VIP会员

JAVA高级面试进阶训练营视频教程

Java架构师系统进阶VIP课程

分布式高可用全栈开发微服务教程Go语言视频零基础入门到精通Java架构师3期(课件+源码)
Java开发全终端实战租房项目视频教程SpringBoot2.X入门到高级使用教程大数据培训第六期全套视频教程深度学习(CNN RNN GAN)算法原理Java亿级流量电商系统视频教程
互联网架构师视频教程年薪50万Spark2.0从入门到精通年薪50万!人工智能学习路线教程年薪50万大数据入门到精通学习路线年薪50万机器学习入门到精通教程
仿小米商城类app和小程序视频教程深度学习数据分析基础到实战最新黑马javaEE2.1就业课程从 0到JVM实战高手教程MySQL入门到精通教程
查看: 512|回复: 0

Spring Boot入门——JDBCTemplate使用及其相关问题解决

[复制链接]
  • TA的每日心情
    奋斗
    2024-11-24 15:47
  • 签到天数: 804 天

    [LV.10]以坛为家III

    2053

    主题

    2111

    帖子

    72万

    积分

    管理员

    Rank: 9Rank: 9Rank: 9

    积分
    726782
    发表于 2021-8-29 09:15:25 | 显示全部楼层 |阅读模式

    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;
        }
    }
    View Code

    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方法返回插入的对象:

      

    哎...今天够累的,签到来了1...
    回复

    使用道具 举报

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    QQ|手机版|小黑屋|Java自学者论坛 ( 声明:本站文章及资料整理自互联网,用于Java自学者交流学习使用,对资料版权不负任何法律责任,若有侵权请及时联系客服屏蔽删除 )

    GMT+8, 2024-12-23 04:56 , Processed in 0.055962 second(s), 28 queries .

    Powered by Discuz! X3.4

    Copyright © 2001-2021, Tencent Cloud.

    快速回复 返回顶部 返回列表