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.在配置文件中配置