spring整合JdbcTemplate进行数据库操作

前言

Spring Data JPA,Hibernate:
均把SQL彻底封装起来,让Java程序员看不到关系的概念,用纯的面向对象思想进行操作。
更加复杂,难以理解,性能降低,不好优化,查询灵活性变差,查询语句受限制,例如多表关联查询。
表之间的连接查询,被映射为实体类之间的关联关系,这样,如果两个实体类之间没有(实现)关联关系,你就不能把两个实体(或者表)join起来查询,这点很烦。
MyBatis:
优点: 高效、支持动态、复杂的SQL构建, 支持与Spring整合和AOP事务、结果集做了轻量级Mapper 封装、支持缓存
缺点:不支持数据库跨平台, 还是需要自己写SQL语句,难以避免写xml文件,xml文件编写困难,容易出错,还不容易查找错误
JdbcTemplate:
优点:使用简单,高效、内嵌Spring框架中、支持基于AOP的声明式事务
缺点:必须于Spring框架结合在一起使用、不支持数据库跨平台、默认没有缓存

总的相比较而言,JdbcTemplate在java开发场景中更优!!!

JdbcTemplate在纯spring下的使用

  1. 导入相关依赖包
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <parent>
        <artifactId>spring-study</artifactId>
        <groupId>com.com.lmy</groupId>
        <version>1.0-SNAPSHOT</version>
    </parent>
    <modelVersion>4.0.0</modelVersion>

    <artifactId>spring-05-jdbcTemplate</artifactId>

    <dependencies>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.10.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.22</version>
        </dependency>
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.29</version>
        </dependency>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>
    </dependencies>

</project>

数据源配置:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="
		http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd">

    <context:annotation-config/>

    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="jdbcDataSource"/>
    </bean>

    <bean id="jdbcDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://localhost:3306/db2?useSSL=false&amp;useUnicode=true&amp;characterEncoding=utf8"/>
        <property name="username" value="root"/>
        <property name="password" value="root"/>
    </bean>

    <bean id="userDao" class="com.lmy.dao.impl.UserDaoImpl">
        <property name="jdbcTemplate" ref="jdbcTemplate"/>
    </bean>
</beans>

dao类:

package com.lmy.dao.impl;

import com.lmy.dao.UserDao;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.List;
import java.util.Map;

/**
 * @author : liu ming yong
 * @date : 2022/8/7 下午 10:05
 * @description : dao类
 */
public class UserDaoImpl implements UserDao {

    private JdbcTemplate jdbcTemplate;

    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    @Override
    public List<Map<String, Object>> getUserToId(Integer id) {
        String sql = "select * from tb_user where id=?";
        List<Map<String, Object>> list = jdbcTemplate.queryForList(sql, new Object[]{id});
        return list;
    }
}

测试类:

package com.lmy;

import com.lmy.dao.UserDao;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.util.List;
import java.util.Map;

/**
 * @author : liu ming yong
 * @date : 2022/8/7 下午 10:41
 * @description : jdbcTemplate测试
 */
public class MyTest {

    public static void main(String[] args) {
        ApplicationContext context = new ClassPathXmlApplicationContext("spring/jdbc-resources.xml");
        UserDao userDao = context.getBean("userDao",UserDao.class);
        List<Map<String, Object>> user = userDao.getUserToId(16);
        System.out.println(user);
    }
}

输出结果:

[{id=16, username=huge, password=1f8fe7059d1a86060f3a82bfcf2ea06e, phone=13688666688, created=2018-04-29T16:31:35}]

JdbcTemplate在spring boot中使用

导入依赖:

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-jdbc</artifactId>
            <version>2.1.15.RELEASE</version>
        </dependency>

自定义数据源配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd">

       <!--自定义配置数据源-->
       <bean id="myJdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
           <property name="dataSource" ref="jdbcDataSource"/>
       </bean>
       <bean id="jdbcDataSource" class="com.zaxxer.hikari.HikariDataSource">
           <property name="driverClassName" value="${driverClassName}"/>
           <property name="jdbcUrl" value="${url}"/>
           <property name="username" value="${name}"/>
           <property name="password" value="${password}"/>
       </bean>

</beans>

spring boot支持自动配置数据源(自定义了数据源,则以自定义数据源为准):

spring:
  profiles:
    active: dev
  datasource:
      driver-class-name: com.mysql.cj.jdbc.Driver
      url: jdbc:mysql://localhost:3306/bufenli_utils?useSSL=false&characterEncoding=utf8&serverTimezone=UTC
      username: root
      password: root
# 如果自定义了数据源,则spring boot的自动配置将不生效
driverClassName: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/db2?useSSL=false&characterEncoding=utf8&serverTimezone=UTC
name: root
password: root

测试类:

package com.lmy;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ActiveProfiles;
import org.springframework.test.context.junit4.SpringRunner;

import java.util.List;
import java.util.Map;

/**
 * @author : liu ming yong
 * @date : 2022/8/8 上午 10:41
 * @description : 测试类
 */
@RunWith(SpringRunner.class)
@SpringBootTest(classes = UtilsDemoApplication.class)
@ActiveProfiles(value = {"dev"})
public class myTest {

    // springBoot自动配置数据源后直接注入(适用于只有一个数据源情况)
    @Autowired
    private JdbcTemplate jdbcTemplate;
    // 自定义配置数据源注入(适用于需要配置多个数据源情况)
    @Autowired
    private JdbcTemplate myJdbcTemplate;

    @Test
    public void getUser() {
        String sql = "select * from tb_user";
        List<Map<String, Object>> list = myJdbcTemplate.queryForList(sql, new Object[]{});
        System.out.println("自定义数据源:"+list);
    }
}

输出结果:

自定义数据源:[{id=16, username=huge, password=1f8fe7059d1a86060f3a82bfcf2ea06e, phone=13688666688, created=2018-04-30 00:31:35.0}, {id=17, username=leyou, password=9ff12f364c1e1d576a6c031af17c6a2c, phone=13800880088, created=2018-05-01 17:31:33.0}, {id=18, username=hehe, password=ec597888142eb7ae821a6bf3555ffc4f, phone=16888668866, created=2018-05-01 17:35:29.0}, {id=19, username=haha, password=b1e2d0f363b8937b72056d39b933eed9, phone=18999999999, created=2018-05-01 17:38:22.0}, {id=20, username=heihei, password=bffbff3726148ca20b8e1edbb96e7d02, phone=13888888888, created=2018-05-01 17:38:39.0}, {id=21, username=hugege, password=0760bf52d18804f9b1ba9ec2526f74db, phone=13600527634, created=2018-05-02 02:23:46.0}, {id=27, username=liuyan, password=ee15b6016cd78661056c5701d6f343e7, phone=17623672016, created=2018-05-02 02:25:30.0}]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值