JdbcTemplate的基本用法

本文涉及的产品
云数据库 RDS MySQL,集群系列 2核4GB
推荐场景:
搭建个人博客
RDS MySQL Serverless 基础系列,0.5-2RCU 50GB
云数据库 RDS MySQL,高可用系列 2核4GB
简介: JdbcTemplate的基本用法

JdbcTemplate的基本用法

JdbcTemplate原始代码

publicclassJdbcTemplateDemo1 {

   publicstaticvoidmain(String[] args) {

       //准备数据源:spring的内置数据源

       DriverManagerDataSourceds=newDriverManagerDataSource();

       //com.mysql.cj.jdbc.Driver

       ds.setDriverClassName("com.mysql.cj.jdbc.Driver");

       ds.setUrl("jdbc:mysql://localhost:3306/eesy?serverTimezone=GMT%2B8");

       ds.setUsername("ggbond");

       ds.setPassword("password");

       //1.创建JdbcTemplate对象

       JdbcTemplatejt=newJdbcTemplate();

       //2.给jt设置数据源

       jt.setDataSource(ds);

       //3.执行操作

       jt.execute("insert into account(name,money) values ('ddd',1000)");

   }

}

使用AOP对代码解耦

<?xmlversion="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">

<!--    配置JdbcTemplate-->

   <beanid="jdbcTemplate"class="org.springframework.jdbc.core.JdbcTemplate">

       <propertyname="dataSource"ref="dataSource"></property>

   </bean>

<!--    配置数据源-->

   <beanid="dataSource"class="org.springframework.jdbc.datasource.DriverManagerDataSource">

       <propertyname="driverClassName"value="com.mysql.cj.jdbc.Driver"></property>

       <propertyname="url"value="jdbc:mysql://localhost:3306/eesy?serverTimezone=GMT%2B8"></property>

       <propertyname="username"value="ggbond"></property>

       <propertyname="password"value="password"></property>

   </bean>

</beans>

publicclassJdbcTemplateDemo2 {

   publicstaticvoidmain(String[] args) {

       //1.获取容器

       ApplicationContextac=newClassPathXmlApplicationContext("bean.xml");

       //2.获取对象

       JdbcTemplatejt= (JdbcTemplate)ac.getBean("jdbcTemplate");

       //3.执行操作

       jt.execute("insert into account(name,money) values ('eee',1000)");

   }

}

JdbcTemplate的CRUD操作

publicclassJdbcTemplateDemo3 {

   publicstaticvoidmain(String[] args) {

       //1.获取容器

       ApplicationContextac=newClassPathXmlApplicationContext("bean.xml");

       //2.获取对象

       JdbcTemplatejt= (JdbcTemplate)ac.getBean("jdbcTemplate");

       //增加(保存)

       jt.update("insert into account(name,money) values (?,?)", "fff",1000);

       //删除

       jt.update("delete from account where id=?", 10);

       //更改(更新)

       jt.update("update account set name=?,money=? where id=?", "test",4567,11);

       //查询所有

       List<Account>list=jt.query("select * from account where money=?", newBeanPropertyRowMapper<>(Account.class), 1000);

       for (Accountaccount: list) {

           System.out.println(account);

       }

       //查询一个

       List<Account>accounts=jt.query("select * from account where id=?", newBeanPropertyRowMapper<>(Account.class), 11);

       System.out.println(accounts.isEmpty()?"没有内容":accounts.get(0));

       //查询返回一行一列(使用聚合函数,但不使用group by子句)

       Longcount=jt.queryForObject("select count(*) from account where money=?", Long.class, 1000);

       System.out.println(count);

   }

}

JdbcTemplate在DAO中的使用

/**

* 账户的持久层实现类

*/

publicclassAccountDaoImplimplementsIAccountDao {

   //通过set方法注入JdbcTemplate对象

   privateJdbcTemplatejt;

   publicvoidsetJt(JdbcTemplatejt) {

       this.jt=jt;

   }

   /**

    * 根据id查找,可能为0或1

    * @param accountId

    * @return

    */

   @Override

   publicAccountfindAccountById(IntegeraccountId) {

       List<Account>list=jt.query("select * from account where id=?", newBeanPropertyRowMapper<>(Account.class), accountId);

       returnlist.isEmpty()?null:list.get(0);

   }

   /**

    * 根据name查找,可能为0或1或多个

    * @param accountName

    * @return

    */

   @Override

   publicAccountfindAccountByName(IntegeraccountName) {

       List<Account>list=jt.query("select * from account where name=?", newBeanPropertyRowMapper<>(Account.class), accountName);

       if (list.isEmpty()){//0

           returnnull;

       }elseif (list.size()>1){//多个

           thrownewRuntimeException("结果集不唯一");

       }

       returnlist.get(0);//1

   }

   /**

    * 更新账户

    * @param account

    */

   @Override

   publicvoidupdateAccount(Accountaccount) {

       jt.update("update account set name=?,money=? where id=?", account.getName(),account.getMoney(),account.getId());

   }

}

dao中通过set方法注入JdbcTemplate对象的重复代码,spring封装在JdbcDaoSupport类中,只要继承即可


相关实践学习
如何在云端创建MySQL数据库
开始实验后,系统会自动创建一台自建MySQL的 源数据库 ECS 实例和一台 目标数据库 RDS。
全面了解阿里云能为你做什么
阿里云在全球各地部署高效节能的绿色数据中心,利用清洁计算为万物互联的新世界提供源源不断的能源动力,目前开服的区域包括中国(华北、华东、华南、香港)、新加坡、美国(美东、美西)、欧洲、中东、澳大利亚、日本。目前阿里云的产品涵盖弹性计算、数据库、存储与CDN、分析与搜索、云通信、网络、管理与监控、应用服务、互联网中间件、移动服务、视频服务等。通过本课程,来了解阿里云能够为你的业务带来哪些帮助 &nbsp; &nbsp; 相关的阿里云产品:云服务器ECS 云服务器 ECS(Elastic Compute Service)是一种弹性可伸缩的计算服务,助您降低 IT 成本,提升运维效率,使您更专注于核心业务创新。产品详情: https://www.aliyun.com/product/ecs
目录
相关文章
|
3月前
|
SQL Java 数据库连接
JDBCTEMPLATE 的基本使用----查询操作26
JDBCTEMPLATE 的基本使用----查询操作26
JDBCTEMPLATE 的基本使用----查询操作26
|
SQL 数据库
四、JdbcTemplate2
四、JdbcTemplate2
37 1
|
4月前
|
Java 程序员 API
JdbcTemplate常用语句代码示例
JdbcTemplate常用语句代码示例
60 0
|
SQL XML Java
四、JdbcTemplate1
四、JdbcTemplate1
52 1
|
Java 数据库连接 数据库
|
Java 数据库 Spring
JdbcTemplate的基本使用
JdbcTemplate的基本使用
JdbcTemplate的基本使用
|
SQL 监控 Java
如何使用多数据源,同时使用jpa和jdbctemplate
spring: datasource: first: type: com.alibaba.druid.pool.DruidDataSource url: jdbc:mysql://xx.
1375 0
|
SQL 数据格式 关系型数据库