1、在pom.xml中引用依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.1.3</version>
</dependency>
2、在Application.yml中配置数据源
spring:
datasource:
url: jdbc:mysql://localhost:3306/dbname?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=PRC
username: root
password: root
driver-class-name: com.mysql.cj.jdbc.Driver
3、创建Entify
package com.example.demo.entity;
public class UserEntity {
private String user_name;
private String tel;
public String getTel() {
return tel;
}
public String getUser_name() {
return user_name;
}
public void setTel(String tel) {
this.tel = tel;
}
public void setUser_name(String user_name) {
this.user_name = user_name;
}
}
4、创建Mapper
package com.example.demo.mapper;
import com.example.demo.entity.UserEntity;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
import java.util.List;
public interface UserMapper {
@Select("Select user_name,tel From user where tel = #{tel}")
List<UserEntity> findByName(@Param("tel") String tel);
@Insert("Insert Into user (tel,user_name) Values(#{tel},#{user_Name})")
int insert(@Param("tel") String tel, @Param("user_Name") String user_Name);
}
注:Mapper使用的是interface接口
5、写控制器
package com.example.demo.controller;
import com.alibaba.fastjson.JSONArray;
import com.example.demo.entity.UserEntity;
import com.example.demo.mapper.UserMapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
import java.util.Map;
@RestController
@MapperScan("com.example.demo.mapper")
public class UserController {
@Autowired
private UserMapper userMapper;
@RequestMapping("/addUser")
public String addUser(String userName,String tel){
return userMapper.insert(tel,userName) >0?"success":"fail";
}
@RequestMapping("/getUser")
public List<UserEntity> getUser(String tel){
List<UserEntity> dataList = (List<UserEntity>) userMapper.findByName(tel);
return dataList;
}
}
说明:实现相应的逻辑是通过调用Mapper中对应的方法
6、创建SpringBootApplication
package com.example.demo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan("com.example.demo.mapper")
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class, args);
}
}
注:@MapperScan("com.example.demo.mapper")此项需要添加,框架默认找不到Mapper