spring restful + MyBatis快速入门

本文介绍了为何选择restful、MyBatis和Gradle,并提供了使用MyBatis和RESTful创建Spring Boot应用的步骤,包括代码示例和运行指南。完整代码可在指定Gitee链接中获取。

为什么是restful

具体的解释大家可以百度百科,好处你可以百度出大把,概括一句话,这是目前的主流,无特殊需求的前提下,尽可能使用restful风格(特殊需求其实也不少)

为什么是MyBatis

相对于hibernate,MyBatis其实并没有那么方便,但我这里主要是基于这点考虑。如果是多表联合查询,hibernate的可定制化的复杂度远高于MyBatis,因为是完全的orm,性能优化的难度也远高于MyBatis。打个简单的比方,你把hibernate看成一个黑匣子,他很好用,但是如果你要对他进行定制化或者改良,他很不好用。类似于C++的STL。用起来很方便,写起来很痛苦。所以,用啥大家可以自己考虑,但我会偏好MyBatis

为什么是gradle

maven的依赖库冲突的解决没有gradle好,gradle全兼容maven,又有做的更好的地方,为啥不用呢?

怎么用MyBatis

通过@Mpaaer注解,库会自动生成代理类,来干具体的活。我们则要通过写增删改查的注解来实现各种操作。(这只是第一个例子,所以先麻烦点。实际可以用MyBatis的自动下划线驼峰转换)
代码入下

package com.example.demospringboot.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Options;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Result;
import org.apache.ibatis.annotations.Results;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import com.example.demospringboot.domains.Employee;

@Mapper
public interface EmployeeMapper {
	
	@Insert("insert into employee(name, emp_Id, deptCode, passport_No) values (#{name}, null, #{deptCode}, #{passportNo})")
	@Options(useGeneratedKeys=true, keyProperty="empId")
	public int createEmployee(Employee emp);
	
	@Select("SELECT * FROM employee WHERE emp_Id = #{empId}")
	@Results({
		@Result(property = "empId", column = "emp_Id"),
	    @Result(property = "passportNo", column = "passport_No")})
	public Employee getEmplyee(@Param("empId") Long empId);
	
	@Select("select * from employee")
	@Results({
		@Result(property = "empId", column = "emp_Id"),
	    @Result(property = "passportNo", column = "passport_No")})
	public List<Employee> getAllEmployee();
	
	@Update("update employee set name=#{name}, emp_Id=#{empId}, deptCode=#{deptCode},passport_No=#{passportNo} where emp_Id=#{empId}")
	public int updateEmployee(Employee emp);
	
	@Delete("delete from employee where emp_Id=#{empId} ")
	public boolean deleteEmployee(@Param("empId") Long empId);
	
	@Select("SELECT * FROM employee WHERE deptCode = #{deptCode}")
	@Results({
		@Result(property = "empId", column = "emp_Id"),
	    @Result(property = "passportNo", column = "passport_No")})
	public List<Employee> getEmployeeByDeptCode(String deptCode);


}

怎么用restful

注解 @RestController 帮助您

package com.example.demospringboot.controller.employcontroller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.hateoas.Link;
import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.mvc.ControllerLinkBuilder;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import com.example.demospringboot.domains.Department;
import com.example.demospringboot.domains.Employee;
import com.example.demospringboot.mapper.DepartmentMapper;
import com.example.demospringboot.mapper.EmployeeMapper;
import com.example.demospringboot.service.*;

@RestController
@RequestMapping("/employee")
public class EmployeeController {
	private static Logger logger = LoggerFactory.getLogger(EmployeeController.class);

	@Autowired
	EmpoyeeService empService;

	@RequestMapping(value="/createEmp", method = RequestMethod.POST)
	public Employee createEmployee(@RequestBody Employee emp){

		return empService.createEmployee(emp);
	}

	@RequestMapping(value="/getEmp/{empId}",method = RequestMethod.GET)
	public Employee getEmplyee(@PathVariable Long empId){
		logger.info("calling employee service");
		return empService.getEmplyee(empId);
	}

	@RequestMapping(value="/getEmps",method = RequestMethod.GET, produces = "application/json;charset=UTF-8")
	public List<Employee> getEmployees(){
		List<Employee> employees = empService.getEmployees();
		return employees;
	}


	@RequestMapping(value="/updateEmp",method = RequestMethod.POST)
	public Employee updateEmployee(@RequestBody Employee emp){
		return empService.updateEmployee(emp);
	}

	@RequestMapping(value="/delEmp/{empId}", method = RequestMethod.PUT )
	public boolean deleteEmployee(@PathVariable Long empId){

		return empService.deleteEmployee(empId);
	}
}

完整代码在哪里?

https://gitee.com/makefriend8/spring-sample/tree/master/spring-boot-mybatis-rest

代码怎么用?

第一步

git clone https://gitee.com/makefriend8/spring-sample.git

其中文件夹spring-boot-mybatis-rest下的工程就是本次的样例,使用idea打开 下载目录\spring-sample\spring-boot-mybatis-rest\build.gradle 就可以编译运行了。

第二步

注意resources目录下的schema.sql文件。
第一次运行的代码入下

--DROP table department;

create table department
(
  deptCode varchar(255) not null,
  deptNAme varchar(255) not null,
  primary key(deptCode)
  
);

--DROP table employee;

create table employee
(
   name varchar(255) not null,
   emp_Id integer not null AUTO_INCREMENT,
   deptCode varchar(255) not null,
   passport_No varchar(255) not null, 
   PRIMARY KEY(emp_Id ),
   FOREIGN KEY(deptCode)
   REFERENCES department(deptCode)
);

第二次以及之后运行的代码

DROP table department;

create table department
(
  deptCode varchar(255) not null,
  deptNAme varchar(255) not null,
  primary key(deptCode)
  
);

DROP table employee;

create table employee
(
   name varchar(255) not null,
   emp_Id integer not null AUTO_INCREMENT,
   deptCode varchar(255) not null,
   passport_No varchar(255) not null, 
   PRIMARY KEY(emp_Id ),
   FOREIGN KEY(deptCode)
   REFERENCES department(deptCode)
);

第三步 测试

这个很关键哦。后面文章还会用到。
找个POSTMAN

输入 http://127.0.0.1:8080/employee/getEmps (GET方式,其实用浏览器也可以,不过建议弄个POSTMAN)

看到输出

[
    {
        "name": "Haneef",
        "empId": 1001,
        "deptCode": "ADM",
        "passportNo": "E1234567",
        "links": []
    },
    {
        "name": "sandeep",
        "empId": 1002,
        "deptCode": "ADM",
        "passportNo": "E1234987",
        "links": []
    },
    {
        "name": "Aseem",
        "empId": 1003,
        "deptCode": "QA",
        "passportNo": "E1234455",
        "links": []
    },
    {
        "name": "Firdous",
        "empId": 1004,
        "deptCode": "MGR",
        "passportNo": "E1234342",
        "links": []
    }
]

那就全部搞定了。

第一篇文章就结束了。。这只是个引子。下一篇会介绍swagger.

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值