SpringBoot整合Mybatis
1、添加mybatis起步依赖(注意与springboot的版本冲突问题)
<!--mybatis起步依赖--> <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>3.0.0</version> </dependency>
2、添加mysql起步依赖
<!--mysql驱动依赖--> <dependency> <groupId>com.mysql</groupId> <artifactId>mysql-connector-j</artifactId> </dependency>
3、添加数据库连接信息 (yml 或 properties)
#数据库信息配置 spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://localhost:3306/dev username: root password: 123456
3.5、数据库建库建表
4、创建实体
package com.demo.springbootdemo.model; public class User { private int id; private String name; private int age; private int gender; private String phone; public User(int id, String name, int age, int gender, String phone) { this.id = id; this.name = name; this.age = age; this.gender = gender; this.phone = phone; } public User() { } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public int getGender() { return gender; } public void setGender(int gender) { this.gender = gender; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } }
5、创建mapper
package com.demo.springbootdemo.mapper; import com.demo.springbootdemo.model.User; import org.apache.ibatis.annotations.Mapper; import org.apache.ibatis.annotations.Select; @Mapper public interface UserMapper { @Select("select * from user where id = #{id}") public User getUserById(int id); }
6、创建service类
package com.demo.springbootdemo.service; import com.demo.springbootdemo.model.User; public interface UserService { public User getUserById(int id); }
7、创建 service 实现类 impl
package com.demo.springbootdemo.service.impl; import com.demo.springbootdemo.mapper.UserMapper; import com.demo.springbootdemo.model.User; import com.demo.springbootdemo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; @Override public User getUserById(int id) { return userMapper.getUserById(id); } }
8、创建相关控制器 controller
package com.demo.springbootdemo.controller; import com.demo.springbootdemo.model.User; import com.demo.springbootdemo.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; @RestController public class UserController { @Autowired private UserService userService; @RequestMapping("/getUserById") public User getUserById(int id) { return userService.getUserById(id); } }
9、运行
项目整体结构