MySql 数据表
CREATE TABLE `test3` (
`id` int(11) NOT NULL,
`name` varchar(20) DEFAULT NULL,
`password` varchar(30) DEFAULT NULL,
PRIMARY KEY (`id`)
)
定义如下类
Test3Model
package com.demo.mybatis.domain;
public class Test3Model {
private int id;
private String name;
private String password;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
Test3Mapper
package com.demo.mybatis.mapper;
import com.demo.mybatis.domain.Test3Model;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
import java.util.List;
/**
* 通过注解实现操作数据接口
*/
@Mapper
public interface Test3Mapper {
@Select("select id,name,password from test3")
public List<Test3Model> getDataList();
@Insert("insert into test3(id,name,password)values(#{id},#{name},#{password})")
public Integer addData(Test3Model model);
}
Test3Service
package com.demo.mybatis.service;
import com.demo.mybatis.domain.Test3Model;
import java.util.List;
/**
* 操作数据表接口
*/
public interface Test3Service {
/**
* 查询表中数据
* @return
*/
public List<Test3Model> getDataList();
/**
* 新增数据
* @param model
* @return
*/
public Integer addData(Test3Model model);
}
Test3ServiceImpl
package com.demo.mybatis.service.impl;
import com.demo.mybatis.domain.Test3Model;
import com.demo.mybatis.mapper.Test3Mapper;
import com.demo.mybatis.service.Test3Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
@Service
public class Test3ServiceImpl implements Test3Service {
@Autowired
private Test3Mapper test3Mapper;
@Override
public List<Test3Model> getDataList() {
return test3Mapper.getDataList();
}
@Override
public Integer addData(Test3Model model) {
return test3Mapper.addData(model);
}
}
Test3Controller
package com.demo.mybatis.controller;
import com.demo.mybatis.domain.Test3Model;
import com.demo.mybatis.service.Test3Service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@RestController
@RequestMapping("test3") //定义访问根路径 http://localhost:8080/test3
public class Test3Controller {
@Autowired
private Test3Service t3Service;
@GetMapping("list")//定义get访问子路径 http://localhost:8080/test3/list
public List<Test3Model> getDataList(){
return t3Service.getDataList();
}
@PostMapping("add")//定义 post访问子路径 http://localhost:8080/test3/add
public Integer addData(@RequestBody Test3Model model){//@RequestBody 用于获取请求体中的数据
return t3Service.addData(model);
}
}
运行 DemoApplication
@SpringBootApplication
public class DemoApplication {
public static void main(String[] args) {
SpringApplication.run(DemoApplication.class);
}
}
通过Restlet测试如下