zoukankan      html  css  js  c++  java
  • Spring Boot 系列教程4-JDBC

    JDBC

    Java Data Base Connectivity,是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。不管是Hibernate,还是JPA或者MyBatis都是对JDBC做了一次封装。

    Spring简化了JDBC那些内容

    Spring JDBC抽象框架所带来的价值将在以下几个方面得以体现:(注:使用了Spring JDBC抽象框架之后,应用开发人员只需要完成斜体字部分的编码工作。)
    - 定义数据库连接参数
    - 打开数据库连接
    - 声明SQL语句
    - 预编译并执行SQL语句
    - 遍历查询结果(如果需要的话)
    - 处理每一次遍历操作
    - 处理抛出的任何异常
    - 处理事务
    - 关闭数据库连接

    项目图片

    这里写图片描述

    pom.xml

    -只需要在pom.xml引入需要的数据库配置,就会自动访问此数据库,如果需要配置其他数据库,可以在application.properties进行添加
    -默认使用org.apache.tomcat.jdbc.pool.DataSource创建连接池

    <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">
        <modelVersion>4.0.0</modelVersion>
    
        <groupId>com.jege.spring.boot</groupId>
        <artifactId>spring-boot-jdbc</artifactId>
        <version>0.0.1-SNAPSHOT</version>
        <packaging>jar</packaging>
    
        <name>spring-boot-jdbc</name>
        <url>http://maven.apache.org</url>
    
        <!-- 公共spring-boot配置,下面依赖jar文件不用在写版本号 -->
        <parent>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-parent</artifactId>
            <version>1.4.1.RELEASE</version>
            <relativePath />
        </parent>
    
        <properties>
            <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
            <java.version>1.8</java.version>
        </properties>
    
        <dependencies>
    
            <!-- 持久层 -->
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-jdbc</artifactId>
            </dependency>
    
            <!-- h2内存数据库 -->
            <dependency>
                <groupId>com.h2database</groupId>
                <artifactId>h2</artifactId>
                <scope>runtime</scope>
            </dependency>
    
            <dependency>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-test</artifactId>
                <scope>test</scope>
            </dependency>
    
        </dependencies>
    
        <build>
            <finalName>spring-boot-jdbc</finalName>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-compiler-plugin</artifactId>
                    <configuration>
                        <source>${java.version}</source>
                        <target>${java.version}</target>
                    </configuration>
                </plugin>
            </plugins>
        </build>
    </project>
    

    User.java

    package com.jege.spring.boot.jdbc.entity;
    
    /**
     * @author JE哥
     * @email 1272434821@qq.com
     * @description:模型对象
     */
    public class User {
      private Long id;
      private String name;
      private Integer age;
    
      public User() {
    
      }
    
      public User(String name, Integer age) {
        this.name = name;
        this.age = age;
      }
    
      public Long getId() {
        return id;
      }
    
      public void setId(Long id) {
        this.id = id;
      }
    
      public String getName() {
        return name;
      }
    
      public void setName(String name) {
        this.name = name;
      }
    
      public Integer getAge() {
        return age;
      }
    
      public void setAge(Integer age) {
        this.age = age;
      }
    }
    

    UserDaoImpl.java

    package com.jege.spring.boot.jdbc.dao.impl;
    
    import java.util.List;
    
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.jdbc.core.BeanPropertyRowMapper;
    import org.springframework.jdbc.core.JdbcTemplate;
    import org.springframework.stereotype.Repository;
    
    import com.jege.spring.boot.jdbc.dao.IUserDao;
    import com.jege.spring.boot.jdbc.entity.User;
    
    /**
     * @author JE哥
     * @email 1272434821@qq.com
     * @description:jdbc CRUD
     */
    @Repository
    public class UserDaoImpl implements IUserDao {
      @Autowired
      JdbcTemplate jdbcTemplate;
    
      @Override
      public void dropTable() {
        jdbcTemplate.update("drop table t_user if exists");
      }
    
      @Override
      public void createTable() {
        jdbcTemplate.update(
        "create table t_user (id bigint generated by default as identity, age integer, name varchar(255), primary key (id))");
      }
    
      @Override
      public void save(User user) {
        jdbcTemplate.update("insert into t_user(name,age) values(?,?)", user.getName(), user.getAge());
      }
    
      @Override
      public List<User> findAll() {
        return jdbcTemplate.query("select id,name,age from t_user", BeanPropertyRowMapper.newInstance(User.class));
      }
    
      @Override
      public void deleteAll() {
        jdbcTemplate.update("delete from t_user");
      }
    
      @Override
      public List<User> findByNameLike(String name) {
        return jdbcTemplate.query("select id,name,age from t_user where name like ?", new Object[] { name },
        BeanPropertyRowMapper.newInstance(User.class));
      }
    
    }
    
    
    

    Application.java

    package com.jege.spring.boot;
    
    import org.springframework.boot.SpringApplication;
    import org.springframework.boot.autoconfigure.SpringBootApplication;
    
    /**
     * @author JE哥
     * @email 1272434821@qq.com
     * @description:spring boot 启动类
     */
    
    @SpringBootApplication
    public class Application {
    
      public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
      }
    
    }
    

    不需要application.properties

    UserDaoTest.java

    package com.jege.spring.boot.data.jpa;
    
    import static org.assertj.core.api.Assertions.assertThat;
    
    import org.junit.After;
    import org.junit.Before;
    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.test.context.junit4.SpringJUnit4ClassRunner;
    
    import com.jege.spring.boot.jdbc.dao.IUserDao;
    import com.jege.spring.boot.jdbc.entity.User;
    
    /**
     * @author JE哥
     * @email 1272434821@qq.com
     * @description:
     */
    @RunWith(SpringJUnit4ClassRunner.class)
    @SpringBootTest()
    public class UserDaoTest {
      @Autowired
      IUserDao userDao;
    
      // 每次执行Test之前先删除表,创建表
      @Before
      public void before() throws Exception {
        userDao.dropTable();
        userDao.createTable();
      }
    
      @Test
      public void save() throws Exception {
        for (int i = 0; i < 10; i++) {
          User user = new User("jege" + i, 25 + i);
          userDao.save(user);
        }
      }
    
      @Test
      public void all() throws Exception {
        save();
        assertThat(userDao.findAll()).hasSize(10);
      }
    
      @Test
      public void findByName() throws Exception {
        save();
        assertThat(userDao.findByNameLike("jege%")).hasSize(10);
      }
    
      @After
      public void destroy() throws Exception {
        userDao.deleteAll();
      }
    
    }
    
    

    源码地址

    https://github.com/je-ge/spring-boot

    如果觉得我的文章对您有帮助,请予以打赏。您的支持将鼓励我继续创作!谢谢!
    微信打赏
    支付宝打赏

  • 相关阅读:
    链表的常用操作
    android简易论坛的制作
    Bmob后端云的使用
    马哥第九周
    马哥第八周
    马哥第七周
    马哥第六周
    马哥第五周
    马哥第四周
    马哥第三周
  • 原文地址:https://www.cnblogs.com/je-ge/p/6105493.html
Copyright © 2011-2022 走看看