Spring Boot 自动配置数据源及操作数据库

  • 数据库配置```application.properties```
  • springboot继承mybatis
  • 测试类检查是否连接成功

创建数据库

CREATE DATABASE /*!32312 IF NOT EXISTS*/`lou_springboot` /*!40100 DEFAULT CHARACTER SET utf8 */;

USE `lou_springboot`;

DROP TABLE IF EXISTS `tb_user`;

CREATE TABLE `tb_user` (
  `id` INT(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `name` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '登录名',
  `password` VARCHAR(100) NOT NULL DEFAULT '' COMMENT '密码',
  PRIMARY KEY (`id`)
) ENGINE=INNODB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8;

数据库配置 application.properties

# datasource config
spring.datasource.url=jdbc:mysql://localhost:3306/lou_springboot?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&serverTimezone=GMT
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=123456

测试类检查是否连接成功

@RunWith(SpringRunner.class)
@SpringBootTest
public class ApplicationTests {
 
    // 注入数据源对象
    @Autowired
    private DataSource dataSource;

    @Test
    public void datasourceTest() throws SQLException {
 
        // 获取数据源类型
        System.out.println("默认数据源为:" + dataSource.getClass());
        // 获取数据库连接对象
        Connection connection = dataSource.getConnection();
        // 判断连接对象是否为空
        System.out.println(connection != null);
        connection.close();
    }
}

可以看到默认数据源是 hikari

springboot操作数据库

@RestController
public class JdbcController {
 

    //自动配置,因此可以直接通过 @Autowired 注入进来
    @Autowired
    JdbcTemplate jdbcTemplate;

    // 查询所有记录
    @GetMapping("/users/queryAll")
    public List<Map<String, Object>> queryAll() {
 
        List<Map<String, Object>> list = jdbcTemplate.queryForList("select * from tb_user");
        return list;
    }

    // 新增一条记录
    @GetMapping("/users/insert")
    public Object insert(String name, String password) {
 
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) {
 
            return false;
        }
        jdbcTemplate.execute("insert into tb_user(`name`,`password`) value (\"" + name + "\",\"" + password + "\")");
        return true;
    }
}

插入成功

查询成功

springboot继承mybatis

示例代码

Spring Boot 整合 MyBatis 时几个比较需要注意的配置参数:

  • mybatis.config-location

    配置 mybatis-config.xml 路径,mybatis-config.xml 中配置 MyBatis 基础属性,如果项目中配置了 mybatis-config.xml 文件需要设置该参数

  • mybatis.mapper-locations

    配置 Mapper 文件对应的 XML 文件路径

  • mybatis.type-aliases-package

    配置项目中实体类包路径

mybatis.config-location=classpath:mybatis-config.xml
mybatis.mapper-locations=classpath:mapper/*Dao.xml
mybatis.type-aliases-package=com.lou.springboot.entity

在启动类中添加对 Mapper 包扫描 @MapperScan,Spring Boot 启动的时候会自动加载包路径下的 Mapper 接口:

@SpringBootApplication
@MapperScan("com.lou.springboot.dao") //添加 @Mapper 注解
public class Application {
 
    public static void main(String[] args) {
 
        System.out.println("启动 Spring Boot...");
        SpringApplication.run(Application.class, args);
    }
}

①.编写数据库实体类 User

注意类名和字段名要和数据库完全一致才能对应上去

package com.lou.springboot.entity;

public class User {
 

    private Integer id;
    private String name;
    private String password;

    public Integer getId() {
 
        return id;
    }

    public void setId(Integer id) {
 
        this.id = id;
    }

    public String getName() {
 
        return name;
    }

    public void setName(String name) {
 
        this.name = name;
    }

    public String getPassword() {
 
        return password;
    }

    public void setPassword(String password) {
 
        this.password = password;
    }
}

②.编写接口

dao 包中新建 UserDao 接口,并定义增删改查四个接口:

public interface UserDao {
 

    List<User> findAllUsers();//返回数据列表

    int insertUser(User User);//添加
    
    int updUser(User User);//修改
    
    int delUser(Integer id);//删除
}

③.编写 Mapper 实现接口

resources/mapper 目录下新建 Mapper 接口的映射文件 UserDao.xml ,之后进行映射文件的编写。

1.首先,定义映射文件与 Mapper 接口的对应关系,比如该示例中,需要将 UserDao.xml 的与对应的 UserDao 接口类之间的关系定义出来:

<mapper namespace="com.lou.springboot.dao.UserDao">

2.之后,配置表结构和实体类的对应关系:

<resultMap type="com.lou.springboot.entity.User" id="UserResult">
     <result property="id" column="id"/>
     <result property="name" column="name"/>
     <result property="password" column="password"/>
 </resultMap>

3.最后,针对对应的接口方法,编写具体的 SQL 语句, 最终 的 UserDao.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.lou.springboot.dao.UserDao">
    <resultMap type="com.lou.springboot.entity.User" id="UserResult">
        <result property="id" column="id"/>
        <result property="name" column="name"/>
        <result property="password" column="password"/>
    </resultMap>
    <select id="findAllUsers" resultMap="UserResult">
        select id,name,password from tb_user
        order by id desc
    </select>
    <insert id="insertUser" parameterType="com.lou.springboot.entity.User">
        insert into tb_user(name,password)
        values(#{name},#{password})
    </insert>
    <update id="updUser" parameterType="com.lou.springboot.entity.User">
        update tb_user
        set
        name=#{name},password=#{password}
        where id=#{id}
    </update>
    <delete id="delUser" parameterType="int">
        delete from tb_user where id=#{id}
    </delete>
</mapper>

最后编写测试的增删改查 Controller 层

package com.lou.springboot.controller;

import com.lou.springboot.dao.UserDao;
import com.lou.springboot.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.List;
import java.util.Map;

@RestController
public class MyBatisController {
 

    @Resource
    UserDao userDao;

    // 查询所有记录
    @GetMapping("/users/mybatis/queryAll")
    public List<User> queryAll() {
 
        return userDao.findAllUsers();
    }

    // 新增一条记录
    @GetMapping("/users/mybatis/insert")
    public Boolean insert(String name, String password) {
 
        if (StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) {
 
            return false;
        }
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        return userDao.insertUser(user) > 0;
    }

    // 修改一条记录
    @GetMapping("/users/mybatis/update")
    public Boolean insert(Integer id, String name, String password) {
 
        if (id == null || id < 1 || StringUtils.isEmpty(name) || StringUtils.isEmpty(password)) {
 
            return false;
        }
        User user = new User();
        user.setId(id);
        user.setName(name);
        user.setPassword(password);
        return userDao.updUser(user) > 0;
    }

    // 删除一条记录
    @GetMapping("/users/mybatis/delete")
    public Boolean insert(Integer id) {
 
        if (id == null || id < 1) {
 
            return false;
        }
        return userDao.delUser(id) > 0;
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值