0


Spring | Spring的“数据库开发“ (Srping JDBC)

目录:

在这里插入图片描述

作者简介 :一只大皮卡丘,计算机专业学生,正在努力学习、努力敲代码中! 让我们一起继续努力学习!

该文章参考学习教材为:
《Java EE企业级应用开发教程 (Spring + Spring MVC +MyBatis)》 黑马程序员 / 编著
文章以课本知识点 + 代码为主线,结合自己看书学习过程中的理解和感悟 ,最终成就了该文章

文章用于本人学习使用 , 同时希望能帮助大家。
欢迎大家点赞👍 收藏⭐ 关注💖哦!!!

(侵权教材方可联系我,进行删除,如果雷同,纯属巧合)


Spring JDBC

SpringJDBC模块 负责数据库资源管理错误处理,大大简化了开发人员对数据库的操作,使得开发人员可以从烦琐的数据库操作中解脱出来,从而将更多的精力投入到编写业务逻辑中

1.Spring JDBC的核心类 ( JdbcTemplate类 )

  • 针对数据库的操作,Spring 框架 (Spring JDBC )提供了 JdbcTemplate类,该类是Spring框架数据抽象层基础,其他更高层次的抽象类却是构建于JdbcTemplate类之上。
  • JdbcTemplate 类是Spring JDBC核心类
  • JdbcTemplate继承 / 实现 关系为 :在这里插入图片描述抽象类赋予JdbcTemplate属性接口赋予JdbcTemplate操作的方法,具体内容如下 : 一、JdbcTemplate****继承 抽象类 JdbcAccessorJdbcAccessor是 JdbcTemplate的直接父类,该 (JdbcAccessor) 为子类 (JdbcTemplate) 提供了一些访问数据库时使用公共属性。① DataSource : 其主要功能是获取数据库连接具体实现时还可以引入对数据库连接缓****冲池分布式事务的支持,它可以作为访问数据库资源的标准接口。② SQLExceptionTranslator : org.springframework.jdbc support.SQLExceptionTranslator接口负责对 SQLException 进行转译工作。通过必要的设置或者 获取SQLExceptionTranslator中的方法,可以使 JdbcTemplate 在需要处理SQLException时,委托SQLExceptionTranslator实现类完成相关的转译工作。二、JdbcTemplate实现了JdbcOperations 接口。JdbcOperations接口定义了在JdbcTemplate类中可以使用的操作集合,包括 添加修改查询删除 等操作。

2.Srping JDBC 的配置

  • Spring JDBC模块主要由 4个包组成,分别是**core (核心包)dataSource (数据源包)object (对象包)support (支持包)**。
  • 想实现 Spring JDBC功能,要进行Spring JDBC配置 : 配置 core (核心包) 中的 JdbcTemplate 类 配置 dataSource (数据源包) 中的 DriverManagerDataSource类 (在 applicationContext.xml 中进行配置)
  • 包名说明core包(要配置JdbcTemplate 类)① 包含了JDBC核心功能,包括 JdbcTemplate 类SimpleJdbcInsert类SimpleJdbcCall类 以及 NamedParameterJdbcTemplate类。② 定义JdbcTemplate时,要将已经配置好的dataSource注入到JdbcTemplate中。dataSource包(要配置dataSource数据源 : DriverManagerDataSource类 )① 访问数据源实用工具类,它有多种数据源实现,可以在Java EE容器外部测试JDBC代码。② 在配置文件中配置dataSource其的类为 :org.springframework.jdbc.datasource.DriverManagerDataSource③ 配置 dataSource4个属性分别为: 数据库驱动url用户名密码ps : 配置dataSource的例子在下面。object包面向对象的方式访问数据库,它允许执行查询并将返回结果作为业务对象,可以在数据表的列业务对象的属性之间映射查询结果support包包含了coreobject包支持类,例如,提供异常转换功能的SQLException类
  • dataSource4个属性 : ( 在以下的dataSource4个属性applicationContext.xml中完成配置 )属性名含义driverClassName使用驱动名词,对应驱动JAR包中工的Driver类。如 :<property *name**=“driverClassNamevalue=“com.mysql.jdbc.Driver”/>url数据源所在地址*。如 :<property **name**=“**url**” **value**=“jdbc:mysql://localhost:3306/spring”/>username访问数据库的用户名*。如: <property name=“username” value=“root”/>password*访问数据库的密码**。如 : <property name=“password” value=“root”/>
  • Srping JDBC配置的 “配置模板” / 例子Spring JDBC要添 JAR包 : (配置JAR包)Spring的核心JAR包②****Spring JDBC开发所需JARmysql数据库的驱动JAR包 (mysql-connector-java.jar) 、Srpring的JDBC的JAR包 (spring-jdbc.jar) 、Spring事务处理的JAR包(spring-tx.jar)。在这里插入图片描述获取spring框架基本核心jar包 获取Spring JDBC 开发需要的jar包 jar包 / maven( 依赖 ) 下载( 可自行按需下载JAR ) ps : 如有报错版本问题,可看情况判断是否需要更换JAR版本。---applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--
①该配置文件中可添加、配置管理Bean
②可配置Spring AOP (AspectJ等)的配置信息
③当然也可以配置Spring JDBC等的配置信息
--><!-- 1.配置数据源 (与Spring JDBC中的dataSource模块有关)   --><beanid="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><!-- 数据库驱动   --><propertyname="driverClassName"value="com.mysql.jdbc.Driver"/><!-- url   --><propertyname="url"value="jdbc:mysql://localhost:3306/spring"/><!-- 用户名   --><propertyname="username"value="root"/><!-- 密码   --><propertyname="password"value="root"/></bean><!--  2.配置JDBC模板 / 配置JdbcTemplate (与Spring JDBC中的core模块有关)  --><beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate"><!--  默认必须使用数据源 --><propertyname="dataSource"ref="dataSource"/></bean></beans>

在上述applicationContext.xml中,定义了 3个Bean,分别是 dataSourejdbcTemplate 和 需要注入类Bean
其中 dataSource 对应 的org.springframework.jdbc.datasource. DriverManagerDataSource 类用于对数据源进行配置
jdbcTemplate 对应的org.springframework.jdbc.core. JdbcTemplate 类用于定义了JdbcTemplate的相关配置。

dataSource4个属性,需要根据数据库类型或者机器配置的不同设置相应的属性值。例如果数据库类型不同需要更改驱动名称;如果数据库不在本地,则需要将地址中的 localhost 替换成相应的主机IP;如果修改过MySQL数据库的端口号(默认为3306),则需要加上修改后的端口号,如果没修改,则端口号可以省略。

3.JdbcTemplate类的“常用方法”

JdbcTemplate类中,提供了大量的更新查询数据库方法,我们就是使用这些方法操作数据库的。

execute( ):直接执行“sql语句”,没有返回值
  • execute (String****sql) 方法 : 执行指定的 SQL 语句。该方法是==没有返回值==的。例子如 :****第一步、建好项目、导入所需依赖、打开doc窗口,指定确定存在数据库 (如: use spring)在这里插入图片描述在这里插入图片描述​ 此时spring这个 “数据库” 中并没有 “数据表”。第二步、配置applicationContext.xml<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!-- 该配置文件中可以配置Spring JDBC等的配置信息 --><!-- 1.配置数据源 (与Spring JDBC中的dataSource模块有关) --><beanid="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><!-- 数据库驱动 --><propertyname="driverClassName"value="com.mysql.jdbc.Driver"/><!-- url --><propertyname="url"value="jdbc:mysql://localhost:3306/spring"/><!-- 用户名 --><propertyname="username"value="root"/><!-- 密码 --><propertyname="password"value="root"/></bean><!-- 2.配置JDBC模板 / 配置JdbcTemplate (与Spring JDBC中的core模块有关) --><beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate"><!-- 默认必须使用数据源 --><propertyname="dataSource"ref="dataSource"/></bean></beans>第三步、创建 JdbcTemplateTest测试类测试 JdbcTemplate类中的 execute( )方法的使用情况 :packagecom.myh.jdbc;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importorg.springframework.jdbc.core.JdbcTemplate;publicclassJdbcTemplateTest{//在该测试类中使用 execute()方法建数据库中的"表"publicstaticvoidmain(String[] args){//加载配置文件ApplicationContext applicationContext =newClassPathXmlApplicationContext("com/myh/jdbc/applicationContext.xml");//从IOC容器中获得 JdbcTemplate 实例JdbcTemplate jdbcTemplate =(JdbcTemplate) applicationContext.getBean("jdbcTemplate");String sql ="create table student("+"id int primary key auto_increment,"+"username varchar(50),"+"hobby varchar(50))";/* execute()方法作用 : 执行sql语句 */ jdbcTemplate.execute(sql);System.out.println("创建student表成功!");}}运行效果图doc窗口,输入 “show tables”命令,判断execute( )方法是否成功执行

在这里插入图片描述

控制台输入 如下 :

在这里插入图片描述

由两个效果图可知,程序 使用execute( String sql )方法执行的sql语句成功创建student表

update( ) :“增删改”,返回 “影响的行数”
  • update()方法 : 可以完成 插入更新删除数据 的操作,有返回值 : 返回影响的行数。 在JdbcTemplate类中,提供了一系列的update( )方法,其常用方法如下所示 :
    方法说明int update( String sql )该方法是最简单update 方法重载形式,它直接执行传入的SQL语句,并 返回受影响行数int update( PreparedStatementCreator psc )该方法执行PreparedStatementCreator返回的语句,然后返回受影响的行数int update( String sql,PreparedStatementSetter )该方法通过PreparedStatementSetter设置SQL语句中参数,并返回受影响的行数int update( String sql,Object…args )

★★★★★ ( 常用 )该方法 使用Object…设置SQL语句中参数要求参数不能为NULL,并 返回受影响的行数
将设置的参数填充到占位符?中
update( ) 方法例子 :进行“增删改”操作。
Student.java

packagecom.myh.jdbc;publicclassStudent{privateInteger id;//学生idprivateString username;//用户名privateString hobby;/*
      getter/setter方法
     */publicIntegergetId(){return id;}publicvoidsetId(Integer id){this.id = id;}publicStringgetUsername(){return username;}publicvoidsetUsername(String username){this.username = username;}publicStringgetHobby(){return hobby;}publicvoidsetHobby(String hobby){this.hobby = hobby;}//重写toString()方法@OverridepublicStringtoString(){return"Student{"+"id="+ id +", username='"+ username +'\''+", hobby='"+ hobby +'\''+'}';}}

StudentDao.java (接口) :

packagecom.myh.jdbc;publicinterfaceStudentDao{//在该接口中定义“添加”、“更新”、“删除”的Student的方法//添加publicintaddStudent(Student student);//更新publicintupdateStudent(Student student);//删除publicintdeleteStudent(int id);}

StudentDaoImpl.java实现类

packagecom.myh.jdbc;importorg.springframework.jdbc.core.JdbcTemplate;publicclassStudentDaoImplimplementsStudentDao{//该类为StudentDao接口的"实现类"//声明JdbcTemplate属性privateJdbcTemplate jdbcTemplate;//为JdbcTemplate属性 添加setter方法publicvoidsetJdbcTemplate(JdbcTemplate jdbcTemplate){this.jdbcTemplate = jdbcTemplate;}/**
      添加
     */@OverridepublicintaddStudent(Student student){/*
          sql语句,此处的占位符?通过下面的Object参数进行填充
         */String sql ="insert into student(username,hobby) values(?,?)";//定义数组来存储sql语句中的参数 (将Student类中存储的数组放进数组中)Object[] obj =newObject[]{student.getUsername(),student.getHobby()};//通过 update(String sql)执行操作,返回值为: sql语句影响的行数int num =this.jdbcTemplate.update(sql,obj);//返回sql语句影响的行数return num;}/**
     * 更新
     */@OverridepublicintupdateStudent(Student student){String sql ="update student set username = ?,hobby = ? where id = ?";//定义要用在update()方法中的参数Object[] params =newObject[]{student.getUsername(), student.getHobby(), student.getId()};int num =this.jdbcTemplate.update(sql, params);return num;}/**
     * 删除
     */@OverridepublicintdeleteStudent(int id){String sql ="delete from student where id = ?";//执行删除操作,返回影响的行数int num =this.jdbcTemplate.update(sql, id);return num;}}

applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--
      该配置文件中可以配置Spring JDBC等的配置信息
    --><!-- 1.配置数据源 (与Spring JDBC中的dataSource模块有关)   --><beanid="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><!-- 数据库驱动   --><propertyname="driverClassName"value="com.mysql.jdbc.Driver"/><!-- url   --><propertyname="url"value="jdbc:mysql://localhost:3306/spring"/><!-- 用户名   --><propertyname="username"value="root"/><!-- 密码   --><propertyname="password"value="root"/></bean><!--  2.配置JDBC模板 / 配置JdbcTemplate (与Spring JDBC中的core模块有关)  --><beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate"><!--  默认必须使用数据源 --><propertyname="dataSource"ref="dataSource"/></bean><!--
     定义一个id 为"studentDao" 的Bean,该Bean用于将"jdbcTemplate"类注入到"studentDao"这个实例中,因为实例中要用到该对象
     --><beanid="studentDao"class="com.myh.jdbc.StudentDaoImpl"><propertyname="jdbcTemplate"ref="jdbcTemplate"/></bean></beans>

JdbcTemplateTest.java (测试类)

packagecom.myh.jdbc;importorg.junit.Test;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importorg.springframework.jdbc.core.JdbcTemplate;publicclassJdbcTemplateTest{//在该测试类中使用 execute()方法建数据库中的"表"/**
     * 进行Junit测试
     */@TestpublicvoidJunitTest(){//加载配置文件ApplicationContext applicationContext =newClassPathXmlApplicationContext("com/myh/jdbc/applicationContext.xml");//从IOC容器中获得 JdbcTemplate 实例JdbcTemplate jdbcTemplate =(JdbcTemplate) applicationContext.getBean("jdbcTemplate");/*
          execute()方法作用 : 执行sql语句
         */
        jdbcTemplate.execute("select * from tb_user");System.out.println("数据查询成功!");}/**
     * 添加
     */@Test//junit4单元测试publicvoidaddStudentTest(){//加载配置文件ApplicationContext applicationContext =newClassPathXmlApplicationContext("com/myh/jdbc/applicationContext.xml");//获取StudentDao实例StudentDao studentDao =(StudentDao) applicationContext.getBean("studentDao");//创建Student对象,往其中添加数据Student student =newStudent();
       student.setUsername("张三");
       student.setHobby("打篮球");//添加int num = studentDao.addStudent(student);if(num >0){System.out.println("成功插入了"+ num +"条数据!");}else{System.out.println("插入操作执行失败!");}}/**
     * 更新(修改)
     */@TestpublicvoidupdateStudentTest(){//加载配置文件ApplicationContext applicationContext =newClassPathXmlApplicationContext("com/myh/jdbc/applicationContext.xml");//获取StudentDao实例StudentDao studentDao =(StudentDao) applicationContext.getBean("studentDao");//创建Student对象,往其中添加数据Student student =newStudent();
        student.setId(1);
        student.setUsername("小明");
        student.setHobby("踢足球");//更新(修改)int num = studentDao.updateStudent(student);if(num >0){System.out.println("成功修改了"+ num +"条数据!");}else{System.out.println("修改操作执行失败!");}}/**
     * 删除
     */@TestpublicvoiddeleteStudentTest(){//加载配置文件ApplicationContext applicationContext =newClassPathXmlApplicationContext("com/myh/jdbc/applicationContext.xml");//获取StudentDao实例StudentDao studentDao =(StudentDao) applicationContext.getBean("studentDao");//删除int num = studentDao.deleteStudent(1);if(num >0){System.out.println("成功删除了"+ num +"条数据!");}else{System.out.println("删除操作执行失败!");}}}
query( ) : “查询”,返回 “T类型 / List类型” 的结果
  • query( ) : 对数据库中的数据进行查询操作JdbcTemplate类中还提供了大量的query( )方法来处理各种对数据库表查询操作。方法说明List<T> query ( String sql , RowMapper rowMapper)★★★★★ ( 常用 )执行String类型参数提供SQL语句,并通过 RowMapper****返回一个List类型结果 : 可用于查询所有数据。(★★★)List<T> query ( String sql , PearesSatementSetter pss , RowMapper rowMapper)根据String 类型参数提供SQL语句创建 PreparedStatement对象,通过RowMapper结果 / 结果集返回到List中。List<T> query ( String sql , Objecr[ ] args , RowMapper rowMapper )使用Obiect[ ]的值来设置SQL语句中的参数值,采用 RowMapper回调方法可以直接返回List类型数值T queryForObject ( String sql , RowMapper rowMapper , Object… args)★★★★★ ( 常用 )args参数绑定SQL语句中,并通过 RowMapper返回一个Object类型单行记录 : 可用于“根据指定id查询数据。(★★★)List<T> queryForList ( String sql , Object[ ] args , class<T> )该方法可以 返回多行数据结果, 但必须是返回列表elementType参数返回的是 List元素类型
  • query( ) 方法例子 :返回 “T类型 / List类型” 的结果 :Student.javapackagecom.myh.jdbc;publicclassStudent{privateInteger id;//学生idprivateString username;//用户名privateString hobby;/* getter/setter方法 */publicIntegergetId(){return id;}publicvoidsetId(Integer id){this.id = id;}publicStringgetUsername(){return username;}publicvoidsetUsername(String username){this.username = username;}publicStringgetHobby(){return hobby;}publicvoidsetHobby(String hobby){this.hobby = hobby;}//重写toString()方法@OverridepublicStringtoString(){return"Student{"+"id="+ id +", username='"+ username +'\''+", hobby='"+ hobby +'\''+'}';}}StudentDao.java (接口)packagecom.myh.jdbc;importjava.util.List;publicinterfaceStudentDao{//根据id查询publicStudentfindStudentById(int id);//查询所有publicList<Student>findAllStudent();}StudentDaoImpl.java (实现类)packagecom.myh.jdbc;importorg.springframework.jdbc.core.BeanPropertyRowMapper;importorg.springframework.jdbc.core.JdbcTemplate;importorg.springframework.jdbc.core.RowMapper;importjava.util.List;publicclassStudentDaoImplimplementsStudentDao{//该类为StudentDao接口的"实现类"/** * 根据id查询 : * 用queryForObject ( String sql , RowMapper rowMapper , Object...args) 这个方法来进行“根据id”查询数据 * 该方法 : 将args参数绑定到sql语句中,且通过 RowMapper 返回一个Object类型的“单行记录”。 */@OverridepublicStudentfindStudentById(int id){//sql语句String sql ="select * from student where id = ?";//创建一个BeanPropertyRowMapper对象RowMapper<Student> rowMapper =newBeanPropertyRowMapper<Student>(Student.class);//调用query()方法查询数据库中的数据Student student =this.jdbcTemplate.queryForObject(sql, rowMapper, id);//返回值为一个return student;}/** * 查询所有 */@OverridepublicList<Student>findAllStudent(){//sql语句String sql ="select * from student";//创建 BeanPropertyRowMapper 对象RowMapper<Student> rowMapper =newBeanPropertyRowMapper<Student>(Student.class);List<Student> students =this.jdbcTemplate.query(sql, rowMapper);//返回值为list集合,该集合中存储一个或多个Student类数据return students;}}applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?><beansxmlns="http://www.springframework.org/schema/beans"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"><!--
      该配置文件中可以配置Spring JDBC等的配置信息
    --><!-- 1.配置数据源 (与Spring JDBC中的dataSource模块有关)   --><beanid="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource"><!-- 数据库驱动   --><propertyname="driverClassName"value="com.mysql.jdbc.Driver"/><!-- url   --><propertyname="url"value="jdbc:mysql://localhost:3306/spring"/><!-- 用户名   --><propertyname="username"value="root"/><!-- 密码   --><propertyname="password"value="root"/></bean><!--  2.配置JDBC模板 / 配置JdbcTemplate (与Spring JDBC中的core模块有关)  --><beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate"><!--  默认必须使用数据源 --><propertyname="dataSource"ref="dataSource"/></bean><!--
     定义一个id 为"studentDao" 的Bean,该Bean用于将"jdbcTemplate"类注入到"studentDao"这个实例中,因为实例中要用到该对象
     --><beanid="studentDao"class="com.myh.jdbc.StudentDaoImpl"><propertyname="jdbcTemplate"ref="jdbcTemplate"/></bean></beans>

JdbcTemplateTest.java (测试类)

packagecom.myh.jdbc;importorg.junit.Test;importorg.springframework.context.ApplicationContext;importorg.springframework.context.support.ClassPathXmlApplicationContext;importorg.springframework.jdbc.core.JdbcTemplate;importjava.util.Iterator;importjava.util.List;publicclassJdbcTemplateTest{/**
     * 根据id来查询数据
     */@TestpublicvoidfindStudentByIdTest(){//加载配置文件ApplicationContext applicationContext =newClassPathXmlApplicationContext("com/myh/jdbc/applicationContext.xml");//获取StudentDao实例StudentDao studentDao =(StudentDao) applicationContext.getBean("studentDao");//执行 findStudentById()方法Student student = studentDao.findStudentById(1);System.out.println(student);}/**
     * 查询所有数据
     */@TestpublicvoidfindAllStudentTest(){//加载配置文件ApplicationContext applicationContext =newClassPathXmlApplicationContext("com/myh/jdbc/applicationContext.xml");//获取StudentDao实例StudentDao studentDao =(StudentDao) applicationContext.getBean("studentDao");//执行 findAllStudent()方法List<Student> allStudent = studentDao.findAllStudent();//使用“集合”的“迭代器”遍历集合中数据Iterator<Student> iterator = allStudent.iterator();while(iterator.hasNext()){Student next = iterator.next();System.out.println(next);}}}

本文转载自: https://blog.csdn.net/m0_70720417/article/details/135943421
版权归原作者 一只大皮卡丘 所有, 如有侵权,请联系我们删除。

“Spring | Spring的“数据库开发“ (Srping JDBC)”的评论:

还没有评论