使用全注解的方式实现SpringBoot,MyBatis,MySQL的整合
1.新建User表
2.pom.xml依赖配置
<!-- MyBatis的依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.1</version>
</dependency>
<!-- MySQL的依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
3.application.properties中添加MySQL配置
spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
4.User类
package com.capgemin.springboot12.pojo;
public class User {
private Integer id;
private String name;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
5.DAO层
package com.capgemin.springboot12.mapper;
import com.capgemin.springboot12.pojo.User;
import org.apache.ibatis.annotations.*;
import org.springframework.stereotype.Component;
import java.util.List;
@Mapper
@Component
public interface UserMapper {
/**
* 添加操作
*/
@Insert("insert into user(id,name) values(#{id},#{name})")
void insert(User user);
/**
* 删除操作
*/
@Delete("delete from user where id = #{id}")
Long delete(@Param("id") Integer id);
/**
* 更新操作
*/
@Update("update user set name=#{name},id = #{id}")
Long update(User user);
/**
* 查询所有
*/
@Select("select * from user")
List<User> selectAll();
/**
* 根据id查询
*/
@Select("select * from user where id = #{id}")
User selectById(@Param("id") Integer id);
}
6.Controller层
package com.capgemin.springboot12.controller;
import com.capgemin.springboot12.mapper.UserMapper;
import com.capgemin.springboot12.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
@RequestMapping("user")
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/selectAll")
public List<User> selectAll(){
return userMapper.selectAll();
}
}
这里只写了一个selectAll()方法。
7.测试
启动项目,在浏览器地址栏输入:http://localhost:8080/user/selectAll