JavaWeb后端-JDBC、MyBatis

JDBC

Java DataBase Connectivity,java语言操作关系型数据库的一套API

入门程序

依赖项

xml 复制代码
<dependency>
   <groupId>com.mysql</groupId>
   <artifactId>mysql-connector-j</artifactId>
   <version>8.0.33</version>
</dependency>

JDBC程序

java 复制代码
public class JdbcTest {
    /**
     * JDBC入门程序
     */
    @Test
    public void testUpdate() throws Exception {
        //1.注册驱动
        Class.forName("com.mysql.cj.jdbc.Driver");
        //2.获取数据库连接
        String url = "jdbc:mysql://localhost:3306/web01";
        String username = "root";
        String password = "1234";
        Connection connection = DriverManager.getConnection(url, username, password);

        //3.获取sql语句的执行对象
        Statement statement = connection.createStatement();

        //4.执行sql(仅限DML语句)
        int i = statement.executeUpdate("update user set age=25 where id=1");//DML
        System.out.println("SQL语句执行完毕的影响的记录数:"+i);

        //5.释放资源
        statement.close();
        connection.close();
    }
}

查询数据

基于JDBC执行select语句,将查询结果封装到User对象中

ResultSet(结果集对象):ResultSet rs = statement.executeQuery()

  • next():将光标从当前位置向前移动一行,并判断当前行是否为有效行,返回值boolean
    true:有效行,当前行有数据
    false:无效行,当前行没有数据
  • getxxx(...):获取数据,可根据列的编号获取,也可根据列名获取(推荐)
java 复制代码
    @Test
    public void testSelect(){
        String url = "jdbc:mysql://localhost:3306/web01";
        String username = "root";
        String password = "1234";
        Connection connection = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;//封装查询结果
        try {
            //1.注册驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2.获取数据库连接
            connection = DriverManager.getConnection(url, username, password);

            //3.执行sql
            String sql = "select * from user where username=? && password=?";//预编译SQL
            stmt = connection.prepareStatement(sql);

            stmt.setString(1, "fangyuan");
            stmt.setString(2, "123456");

            rs = stmt.executeQuery();

            //4.处理结果
            while (rs.next()) {
                User user = new User(
                        rs.getInt("id"),
                        rs.getString("username"),
                        rs.getString("password"),
                        rs.getString("name"),
                        rs.getInt("age")
                );
                System.out.println(user);
            }

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //5.释放资源
            try {
                if (rs != null) {
                    rs.close();
                }
                if (stmt != null) {
                    stmt.close();
                }
                if (connection != null) {
                    connection.close();
                }
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}

预编译SQL

java 复制代码
String sql = "select * from user where username=? && password=?";//预编译SQL

优势一:防止SQL注入,更安全

优势二:性能更高

MyBatis

MyBatis是一款持久层框架,用于简化JDBC的开发

查询所有用户数据

  • 准备工作:
    1、创建SpringBoot工程,引入Mybatis相关依赖
    2、准备数据库表user,实体类User
    3、配置Mybatis(在application.properties中)

  • 编写Mybatis程序:编写Mybatis持久层接口,定义SQL(注解)

    配置数据库的连接信息

    spring.datasource.url=jdbc:mysql://localhost:3306/web01
    spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
    spring.datasource.username=root
    spring.datasource.password=1234

java 复制代码
@Mapper//应用程序在运行时会自动为该接口创建一个实现类对象(代理对象),该对象会作为Spring Bean对象加入到Spring容器中
public interface UserMapper {
    /**
     * 查询所有用户
     */
    @Select("select * from user")
    public List<User> findAll();

}
java 复制代码
@SpringBootTest //SpringBoot单元测试的注解 - 当前测试类中的测试方法运行时,会启动SpringBoot项目 - IOC容器
class SpringbootMybatisQuickstartApplicationTests {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testFindAll() {
        List<User> users = userMapper.findAll();
        users.forEach(System.out::println);
    }
}

数据库连接池

  • 一个容器,负责分配、管理数据库连接(资源重用)
  • 允许应用程序重复使用一个现有的数据库连接,而不是重新建立一个(提升系统响应速度)
  • 释放空闲时间超过最大空闲时间的连接,避免因为没有释放连接而引起的数据库连接遗漏(避免数据库连接遗漏)

切换数据库连接池:

增删改查

删除用户-delete

Mapper接口

java 复制代码
@Mapper//应用程序在运行时会自动为该接口创建一个实现类对象(代理对象),该对象会作为Spring Bean对象加入到Spring容器中
public interface UserMapper {
    /**
     * 根据id删除用户
     */
    @Delete("delete from user where id = #{id}")
    //public void deleteById(Integer id);
    public Integer deleteById(Integer id);
}
java 复制代码
@SpringBootTest //SpringBoot单元测试的注解 - 当前测试类中的测试方法运行时,会启动SpringBoot项目 - IOC容器
class SpringbootMybatisQuickstartApplicationTests {
    @Autowired
    private UserMapper userMapper;

    /**
     * 测试删除
     */
    @Test
    public void testdeleteById() {
        Integer i = userMapper.deleteById(5);
        System.out.println("执行完毕后,影响的记录数:"+i);
    }
}

新增用户-insert

java 复制代码
@Mapper//应用程序在运行时会自动为该接口创建一个实现类对象(代理对象),该对象会作为Spring Bean对象加入到Spring容器中
public interface UserMapper {
    /**
     * 添加用户
     */
    @Insert("insert into user(username, password, name, age) values (#{username},#{password},#{name},#{age})")//大括号中写User对象的属性名
    public void insert(User user);
}
java 复制代码
@SpringBootTest //SpringBoot单元测试的注解 - 当前测试类中的测试方法运行时,会启动SpringBoot项目 - IOC容器
class SpringbootMybatisQuickstartApplicationTests {

    @Autowired
    private UserMapper userMapper;

    /**
     * 测试新增用户
     */
    @Test
    public void testInsert() {
        User user = new User(null,"yuanlian","666888","元莲",24);
        userMapper.insert(user);
    }
}

修改用户-update

java 复制代码
@Mapper//应用程序在运行时会自动为该接口创建一个实现类对象(代理对象),该对象会作为Spring Bean对象加入到Spring容器中
public interface UserMapper {
    /**
     * 更新用户
     */
    @Update("update user set username=#{username},password=#{password},name=#{name},age=#{age} where id=#{id}")
    public void update(User user);
}
java 复制代码
@SpringBootTest //SpringBoot单元测试的注解 - 当前测试类中的测试方法运行时,会启动SpringBoot项目 - IOC容器
class SpringbootMybatisQuickstartApplicationTests {

    @Autowired
    private UserMapper userMapper;

    /**
     * 测试修改用户
     */
    @Test
    public void testUpdateById() {
        User user = new User(6,"kuangman","666888","狂蛮",34);
        userMapper.update(user);
    }
}

查询用户-select

java 复制代码
@Mapper//应用程序在运行时会自动为该接口创建一个实现类对象(代理对象),该对象会作为Spring Bean对象加入到Spring容器中
public interface UserMapper {
    /**
     * 查询用户
     */
    @Select("select * from user where username=#{username} and password=#{password}")
    //public User findByUsernameAndPassword(@Param("username") String username, @Param("password") String password);
    public User findByUsernameAndPassword(String username, String password);

@Param注解的作用是为接口的方法形参起名字

java 复制代码
@SpringBootTest //SpringBoot单元测试的注解 - 当前测试类中的测试方法运行时,会启动SpringBoot项目 - IOC容器
class SpringbootMybatisQuickstartApplicationTests {

    @Autowired
    private UserMapper userMapper;

    /**
     * 测试查询用户
     */
    @Test
    public void testFindByUsernameAndPassword() {
        User user = userMapper.findByUsernameAndPassword("kuangman","666888");
        System.out.println(user);
    }
}

基于官方骨架创建的springboot项目中,接口编译时会保留方法形参名,@Param注解可以省略(#{形参名})

XML映射配置

基本框架

xml 复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="">
  
</mapper>
xml 复制代码
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.it.mapper.UserMapper">

<!--    resultType:查询返回的单条记录所封装的类型-->
    <select id="findAll" resultType="com.it.pojo.User">
        select id, username, password, name, age from user
    </select>

</mapper>

原接口中的注解要注释掉

java 复制代码
@Mapper//应用程序在运行时会自动为该接口创建一个实现类对象(代理对象),该对象会作为Spring Bean对象加入到Spring容器中
public interface UserMapper {
    /**
     * 查询所有用户
     */
    //@Select("select id, username, password, name, age from user")
    public List<User> findAll();
}

官方建议:使用注解来映射简单语句会使代码显得更加简洁,但对于稍微复杂一点的语句,Java 注解不仅力不从心,还会让你本就复杂的 SQL 语句更加混乱不堪。 因此,如果你需要做一些很复杂的操作,最好用 XML 来映射语句。

  • 配置XML映射文件的位置
  • MybatisX插件

SpringBoot配置文件格式

SpringBoot提供了多种属性配置方式(properties、yaml、yml)

yml配置文件

格式:

  • 数值前面必须有空格,作为分隔符
  • 使用缩进表示层级关系,缩进时不能使用Tab键,只能用空格(idea自动将Tab转为空格)
  • 缩进空格数无要求,只要相同层级元素左侧对齐即可
  • "#" 表示注释

定义对象/Map集合

定义数组/List/Set集合

注意

在yml格式的配置文件中,若配置项的值是以0开头,值要用''引起来。因为0开头的值在yml中表示八进制数值

yaml 复制代码
spring:
  application:
    name: springboot-mybatis-quickstart
  #数据库的连接信息
  datasource:
    url: jdbc:mysql://localhost:3306/web01
    username: root
    password: 1234

#mybatis的配置信息
mybatis:
  configuration:
    log-impl: org.apache.ibatis.logging.stdout.StdOutImpl
  mapper-locations: classpath:mapper/*.xml
相关推荐
低音钢琴5 小时前
【SpringBoot从初学者到专家的成长25】认识SpringBoot中的Spring Expression Language (SpEL)
spring boot·后端·spring·spel
BeingACoder6 小时前
【项目实践】公寓租赁项目(九):SpringBoot与Redis整合的快速入门使用
java·spring boot·redis
刘一说14 小时前
深入理解 Spring Boot 嵌入式 Web 容器:从原理到性能调优
前端·spring boot·firefox
程序员小凯14 小时前
Spring Boot文件处理与存储详解
java·spring boot·后端
2501_9387742915 小时前
Leaflet 弹出窗实现:Spring Boot 传递省级旅游口号信息的前端展示逻辑
前端·spring boot·旅游
ruleslol17 小时前
SpringBoot13-文件上传02-阿里云OSS
spring boot
蹦跑的蜗牛17 小时前
Spring Boot 使用 Redis 实现消息队列
spring boot·1024程序员节
兜兜风d'18 小时前
RabbitMQ事务机制详解
数据库·spring boot·分布式·rabbitmq·ruby·java-rabbitmq
勇往直前plus18 小时前
学习和掌握RabbitMQ及其与springboot的整合实践(篇二)
spring boot·学习·rabbitmq·java-rabbitmq