java中的接口是类吗
216
2022-10-29
Springboot整合mybatis的步骤
前期工作
1.导入mybatis整合依赖
2.连接数据库
3.连接完数据库就去applicaton.yml配置一下数据库
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://localhost:3306/mybatis?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
driver-class-name: com.mysql.cj.jdbc.Driver
开始整合
1.编写与数据库对应的实体类
package com.example.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private Integer id;
private String name;
private String pwd;
}
为了偷懒,导入了lombok
2.编写mapper
package com.example.mapper;
import com.example.pojo.User;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
@Mapper
@Repository
public interface UserMapper {
//查询用户的全部信息
List
//select 找出id=1的用户
User getUserById(int id);
//insert 增加一个用户
int insertUser(User user);
//delete 删除id=4的用户
int deleteUser(int id);
//update 将id=2的用户名字改为小龙
int updateUser(User user);
}
3.编写mapper.xml文件
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
select *
from mybatis.user
select *
from mybatis.user
where id = #{id};
insert into mybatis.user (id, name, pwd)
values (#{id}, #{name}, #{pwd});
delete
from mybatis.user
where id = #{id};
update mybatis.user
set name = #{name},
pwd = #{pwd}
where id = #{id};
这里我们用了别名而且我们把这个mapper.xml文件放在了resources目录下,所以我们要去application.yml配置一下
mybatis:
type-aliases-package: com.example.pojo
mapper-locations: classpath:mybatis/mapper/*.xml
mapper.xml文件编写的位置:
4.编写controller
package com.example.controller;
import cohttp://m.example.mapper.UserMapper;
import com.example.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
@Autowired
private UserMapper userMapper;
@GetMapping("/getUserList")
public List
return userMapper.getUserList();
}
@GetMapping("/getUserById/{id}")
public User getUserById(@PathVariable("id") int id){
return userMapper.getUserById(id);
}
@GetMapping("/insertUser")
public String insertUser(){
userMapper.insertUser(new User(5,"xiaoming","111"));
return "ok";
}
@GetMapping("/deleteUser")
public String deleteUser(){
userMapper.deleteUser(5);
return "ok";
}
http:// @GetMapping("/updateUser")
public String updateUser(){
userMapper.updateUser(new User(5,"xx","111"));
return "ok";
}
}
5.进行测试
以上就是Springboot整合mybatis的步骤的详细内容,更多关于Springboot整合mybatis的资料请关注我们其它相关文章!
版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。
发表评论
暂时没有评论,来抢沙发吧~