Springboot中数据库连接

Springboot中数据库连接

一.jdbc的方式连接

1.配置jdbc连接文件

spring:
  datasource:
    username: root
    password: 123123
    url: jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.jdbc.Driver

2.直接controller操作crud

package com.springboot.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

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

/**
 * @author panglili
 * @create 2022-07-10-10:27
 */
@Controller
public class JdbcController {

    @Autowired(required = false)
    JdbcTemplate jdbcTemplate;

@GetMapping("/sql")
@ResponseBody
    public List<Map<String,Object>> mapList(){
        String sql="select * from user";
        List<Map<String, Object>> queryForList = jdbcTemplate.queryForList(sql);

            return queryForList;
    }
}

二.mybatis连接

1.导入依赖

<dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.2.2</version>
</dependency>

2.数据库连接文件

与jdbc中的配置文件相同,使用jdbc方式中的即可!

3.pojo实体类

package com.springboot.pojo;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * @author panglili
 * @create 2022-07-10-11:23
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class user {

    private int  id;
    private String name;
    private String pwd;
}

4.controller操作修改

package com.springboot.controller;

import com.springboot.mapper.UserMapper;
import com.springboot.pojo.user;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @author panglili
 * @create 2022-07-10-11:46
 */
@RestController
public class MybatisController {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/queryAll")
    public List<user> queryAll(){
        List<user> users = userMapper.queryAll();
        return users;
    }

    @RequestMapping("/queryById/{id}")
    public user queryById(@PathVariable("id") int id){
        user user = userMapper.queryById(id);
        return user;
    }

}

5.在配置文件中配置

在这里插入图片描述

  • 7
    点赞
  • 42
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值