一、数据库新建用户(user)表
二、利用mybatis-generator生成代码
可参考【记录·后端篇-2】springboot集成mybatis-generator_郝南过的博客-CSDN博客
(1)在生成的UserMapper接口上添加注解@Repository
(2)创建UserController、UserServer以及UserviceIpml(实现自带的selectByPrimaryKey为例)
UserController.java(注意添加注解)
package com.hng.example.controller;
import com.hng.example.entity.User; import com.hng.example.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; /** * @Author 郝南过 * @Date 2022/11/6 19:04 * @Version 1.0 */ @RestController public class UserController { @Autowired private UserService userService; @RequestMapping("/hello") public User hello(){ return userService.selectByPrimaryKey(1); } }
UserServer.java
package com.hng.example.service; import com.hng.example.entity.User; /** * @Author 郝南过 * @Date 2022/11/4 11:14 * @Version 1.0 */ public interface UserService { User selectByPrimaryKey(Integer id); }
UserServiceImpl.java (注意添加注解@Service)
package com.hng.example.service.impl; import com.hng.example.entity.User; import com.hng.example.repository.UserMapper; import com.hng.example.service.UserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * @Author 郝南过 * @Date 2022/11/6 19:07 * @Version 1.0 */ @Service public class UserServiceImpl implements UserService { @Autowired private UserMapper userMapper; public User selectByPrimaryKey(Integer id) { return userMapper.selectByPrimaryKey(id); } }
三、启动类上方添加mapper扫描 @MapperScan("com.hng.example.repository")
package com.hng.example; import org.mybatis.spring.annotation.MapperScan; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; @SpringBootApplication @MapperScan("com.hng.example.repository") public class ExampleApplication { public static void main(String[] args) { SpringApplication.run(ExampleApplication.class, args); } }
四、application.properties中添加**mapper.xml扫描位置
# db spring.datasource.url=jdbc:mysql://xxx.xxx.xxx.xxx:3306/hng spring.datasource.username=root spring.datasource.password=password spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver # mybatis-generator tableName = user entityName = User mybatis.mapper-locations = classpath:mapper/*Mapper.xml
五、运行测试
在数据库中在的表user中,根据测试代码添加ID为1数据信息,然后启动项目。
在浏览器输入http://localhost:8080/hello测试
到此测试完成!!!