创建数据库及数据表:
CREATE DATABASE /*!32312 IF NOT EXISTS*/`springbootdb` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `springbootdb`;
/*Table structure for table `user` */
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`username` varchar(16) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2,创建User.java
package com.spb.SpringBootDemo.vo;
public class User {
private String id;
private String username;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
3, 在pom.xml中加入:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
4, 在resource下加入application.properties文件,mysql和mybatis可以根据自己的地址配置。
spring.datasource.url=jdbc:mysql://localhost:3306/springbootdb?useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
mybatis.typeAliasesPackage=org.spring.springboot.domain
mybatis.mapperLocations=classpath:mapper/*.xml
1
2
3
4
5
6
7
8
9
5,新增UserDao,并在resources下面创建mapper目录,在下面创建UserMapper.xml
package com.spb.SpringBootDemo.dao;
import java.util.List;
import com.spb.SpringBootDemo.vo.User;
/**
*
* @author Administrator
*
*/
public interface UserDao {
/**
* 新增用户
* @param user
*/
void createUser(User user);
/**
* 查询用户列表
* @return
*/
List
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
id, username
insert into
user(id,username)
values
(#{id},#{username})
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
6,最后增加service和实现controller,这里service省略。
package com.spb.SpringBootDemo.rest;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.spb.SpringBootDemo.service.IUserService;
import com.spb.SpringBootDemo.vo.User;
@RestController
@RequestMapping("/user")
public class UserController {
@Autowired
private IUserService service;
@RequestMapping("/userList")
public List
return service.findAllUser();
}
@RequestMapping("/add")
public String addUser(@RequestBody User user){
if(user!=null){
service.createUser(user);
return "success";
}else{
return "error";
}
}
}
app.java中加入注解@MapperScan("com.spb.SpringBootDemo.dao")
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
测试:
运行项目
用postman测试
源码:http://download.csdn.net/download/u012343297/10163177