一、Springboot整合mybatis
maven中添加对数据库与mybatis的依赖
1 <dependencies>
2 <dependency>
3 <groupId>org.springframework.boot</groupId>
4 <artifactId>spring-boot-starter-web</artifactId>
5 </dependency>
6 <dependency>
7 <groupId>org.mybatis.spring.boot</groupId>
8 <artifactId>mybatis-spring-boot-starter</artifactId>
9 </dependency>
10 <dependency>
11 <groupId>mysql</groupId>
12 <artifactId>mysql-connector-java</artifactId>
13 </dependency>
14 <dependency>
15 <groupId>com.alibaba</groupId>
16 <artifactId>druid</artifactId>
17 </dependency>
18 </dependencies>
添加application.properties关于mybatis的配置
1 spring.datasource.driverClassName=com.mysql.jdbc.Driver
2 spring.datasource.url=jdbc:mysql://127.0.0.1:3306/dbName
3 spring.datasource.username=root
4 spring.datasource.password=root
5 spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
6 mybatis.type-aliases-package=io.guangsoft.pojo
mapper的xml文件所在目录需要在springboot启动类中配置扫描
1 @SpringBootApplication
2 @MapperScan("io.guangsoft.mapper")
数据库表设计
1 create table users(
2 id int(11) not null auto_increment,
3 name varchar(25) default null,
4 age int default null,
5 primary key (id)
6 )engine=InnoDB default charset=utf8;
pojo
1 public class User {
2 private Integer id;
3 private String name;
4 private Integer age;
5 public Integer getId() {
6 return id;
7 }
8 public void setId(Integer id) {
9 this.id = id;
10 }
11 public String getName() {
12 return name;
13 }
14 public void setName(String name) {
15 this.name = name;
16 }
17 public Integer getAge() {
18 return age;
19 }
20 public void setAge(Integer age) {
21 this.age = age;
22 }
23 }
mapper
1 public interface UserMapper {
2 void insertUser(User user);
3 List<User> selectUserAll();
4 }
1 <mapper namespace="io.guangsoft.mapper.UserMapper">
2 <insert id="insertUser" parameterType="user">
3 insert into user(name, age) values (#{name}, #{age})
4 </insert>
5 <select id="selectUserAll" resultType="user">
6 select id, name, age from user
7 </select>
8 </mapper>
service
1 @Service
2 @Transactional
3 public class UserServiceImpl implements UserService {
4 @Autowired
5 private UserMapper userMapper;
6 @Override
7 public void addUser(User user) {
8 this.userMapper.insertUser(user);
9 }
10 }
controller
1 @Controller
2 @RequestMapping("/user")
3 public class UserController {
4 @Autowired
5 private UserService userService;
6 @RequestMapping("/{page}")
7 public String showPage(String page) {
8 return page;
9 }
10 @RequestMapping("/addUser")
11 public String addUser(User user) {
12 this.userService.addUser(user);
13 return "ok";
14 }
15 }