springboot整合mybatis

tech2024-10-30  8

1. pom.xml文件

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-jdbc</artifactId> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.3</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <scope>runtime</scope> </dependency>

2. 配置数据源和mybatis配置

spring: datasource: url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&userUnicode=true&characterEncoding=utf-8 username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver mybatis: type-aliases-package: com.example.pojo mapper-locations: classpath:mybatis/mapper/*.xml

3. 创建实体类

public class User { private int id; private String name; private String password; ...... }

4. 创建mapper接口

@Mapper @Repository public interface UserMapper { List<User> getAllUser(); int addUser(User user); int updateUser(User user); int deleteUser(int id); }

5. 创建mapper.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.example.mapper.UserMapper"> <select id="getAllUser" resultType="com.example.pojo.User"> select * from user </select> <insert id="addUser" parameterType="com.example.pojo.User"> insert into user values(#{id},#{name},#{password}) </insert> <update id="updateUser" parameterType="com.example.pojo.User"> update user set name=#{name},password=#{password} where id=#{id} </update> <delete id="deleteUser" parameterType="int"> delete from user where id=#{id} </delete> </mapper>

6. 创建controller

@RestController public class UserController { @Autowired private UserMapper userMapper; @GetMapping("/getAllUser") public List<User> getAllUser(){ List<User> userList = userMapper.getAllUser(); return userList; } ...... }
最新回复(0)