1,新建项目
2,配置文件
Gradle文件:
compile('org.springframework.boot:spring-boot-starter-web')
compile('org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.2')
runtime('mysql:mysql-connector-java')
// https://mvnrepository.com/artifact/com.alibaba/druid
compile group: 'com.alibaba', name: 'druid', version: '1.1.9'
testCompile('org.springframework.boot:spring-boot-starter-test')
yml文件:
server:
port: 8080
#公共配置与profiles选择无关 mapperLocations指的路径是src/main/resources
mybatis:
type-aliases-package: com.meng.entity
#开发配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/db_mybatis
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
# 使用druid数据源
type: com.alibaba.druid.pool.DruidDataSource
3,数据库设计
CREATE TABLE `tb_user` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'ID',
`username` varchar(50) NOT NULL COMMENT '用户名',
`age` int(11) NOT NULL COMMENT '年龄',
`ctm` datetime NOT NULL COMMENT '创建时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;
4,代码书写
entity:需要自己生成getter,setter方法,无参构造器和有参构造器,也可以生成toString方法
private int id;
private String username;
private int age;
private Date ctm;
mapper:
public interface UserMapper {
@Select("SELECT * FROM tb_user WHERE id = #{id}")
User getUserById(Integer id);
}
service:
@Service
public class UserService {
@Autowired
private UserMapper uMapper;
public User getUserByMapperId(Integer id) {
return uMapper.getUserById(id);
}
}
controller:
@RestController
public class UserController {
@Autowired
private UserService uService;
@RequestMapping("/getMapperuser")
public User getUserBymapper() {
User u = uService.getUserByMapperId(2);
return u;
}
}