Maven依赖
通过IDEA的Spring Initializr选择需要的依赖,我用到了图下的这些
配置文件application.properties
# 服务器端口
server.port=8080
# 数据库
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mall?useSSL=false&serverTimezone=Asia/Shanghai
spring.datasource.username=root
spring.datasource.password=123
#mybatis
# 映射文件位置
mybatis.mapper-locations=classpath:mapper/*Mapper.xml
mybatis.configuration.map-underscore-to-camel-case=true
MVC
-
bean
@Data public class User { private String id; private String username; private String password; }
-
controller
@Controller public class UserController { @Autowired UserService userService; @RequestMapping("getUsers") @ResponseBody public Object getUsers(){ return userService.getUsers(); } }
-
service
@Service public class UserServiceImpl implements UserService { @Autowired UserMapper userMapper; @Override public Object getUsers() { return userMapper.getUsers(); } }
-
mapper
public interface UserMapper { List<User> getUsers(); }
启动类配置
@SpringBootApplication
@MapperScan("com.my.code.user.mapper")//扫描Mapper类
public class MallUserApplication {
public static void main(String[] args) {
SpringApplication.run(MallUserApplication.class, args);
}
}
Mapper映射文件
<?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.my.code.user.mapper.UserMapper">
<select id="getUsers" resultType="com.my.code.user.bean.User">
select * from user
</select>
</mapper>