Springboot整合Mybaits
Posted 学习笔记
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Springboot整合Mybaits相关的知识,希望对你有一定的参考价值。
1.导入mybatis-spring-boot-starter依赖
<!-- https://mvnrepository.com/artifact/org.mybatis.spring.boot/mybatis-spring-boot-starter -->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.2</version>
</dependency>
2.创建实体类User
package com.example.pojo;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@NoArgsConstructor
@AllArgsConstructor
public class User {
private int id;
private String name;
private String pwd;
}
3.创建dao层UserMapper
package com.example.dao;
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<User> getUserList();
//根据id查询用户
User selectUserById(int id);
//添加一个用户
int addUser(User user);
//修改一个用户
int updateUser(User user);
//根据id删除用户
int deleteUserById(int id);
}
4.创建UserMapper.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">
<!--namespace=绑定一个对应的Dao/Mapper接口-->
<mapper namespace="com.example.dao.UserMapper">
<!--select查询语句-->
<select id="getUserList" resultType="user">
select * from user
</select>
<select id="selectUserById" resultType="user" parameterType="int">
select * from user where id=#{id}
</select>
<insert id="addUser" parameterType="user">
insert into user (id,name,pwd) values (#{id},#{name},#{pwd})
</insert>
<update id="updateUser" parameterType="user">
update user set name=#{name},pwd=#{pwd} where id = #{id}
</update>
<delete id="deleteUserById" parameterType="int">
delete from user where id = #{id}
</delete>
</mapper>
5.编辑配置文件
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://192.168.137.100:3306/mybatis?useSSL=false&useUnicode=true&characterEncoding=UTF-8&allowPublicKeyRetrieval=true
spring.datasource.username=root
spring.datasource.password=root
#mybatis配置
mybatis.mapper-locations=classpath:mapper/*.xml
mybatis.type-aliases-package=com.example.pojo
6.创建控制器
package com.example.controller;
import com.example.dao.UserMapper;
import com.example.pojo.User;
import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class HomeController {
@Autowired
private UserMapper userMapper;
@GetMapping("/test")
public List<User> test(){
val userList = userMapper.getUserList();
return userList;
}
}
以上是关于Springboot整合Mybaits的主要内容,如果未能解决你的问题,请参考以下文章