SpringBoot的Mybatis注解版数据库操作
mybatis的依赖:
<dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>2.1.0</version> </dependency>
还是不使用tomcat的数据源,选择使用的是druid的数据源
还是引入druid的依赖、以及druid的yml配置、包括druid的config
我们在数据库再创建一个新的数据库,名为mybatis,用schame进行创表sql的执行,然后添加employee和department的变量的set/get的设定;
我们设定一个Mapper进行注解版的设定:(我们可以在每个Mapper上添加@Mapper的注解,也可以在主函数或者是配置函数上加上,这样,就可以随我们文件夹下的所有文件设定成Mapper)
@MapperScan(value = "com.zch.springboot_mybatis.Mapper"
package com.zch.springboot_mybatis.Mapper; import com.zch.springboot_mybatis.bean.Department; import org.apache.ibatis.annotations.*; //@Mapper public interface DepaertmentMapper { // mybatis的注解版 @Select("select * from department where id=#{id}") public Department getDdeptByid(Integer id); @Delete("delete from department where id=#{id}") public int deleteDeptByid(Integer id); @Options(useGeneratedKeys = true ,keyProperty = "id") @Insert("insert into department(departmentName) values(#{departmentName})") public int insertDept(Department department); @Update("update department set departmentName=#department where id={#id}") public int updateDept(Department depaertment); }
所有的sql都是写在@下
然后在controller进行请求的解析:
package com.zch.springboot_mybatis.Controller; import com.zch.springboot_mybatis.Mapper.DepaertmentMapper; import com.zch.springboot_mybatis.bean.Department; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RestController; @RestController public class DeptController { @Autowired DepaertmentMapper depaertmentMapper; private Department deleteDepartment; Department department=new Department(); //select实现 @GetMapping("/dept/{id}") public Department getDepartment(@PathVariable("id") Integer id){ return depaertmentMapper.getDdeptByid(id); } //delete实现 @GetMapping("/dept/delete/{id}") public Department deleteDepartment(@PathVariable("id") Integer id){ depaertmentMapper.deleteDeptByid(id); return deleteDepartment; } //insert实现 @GetMapping("/dept") public Department insertDept(Department department){ depaertmentMapper.insertDept(department); return department; } //update实现(失败) @GetMapping("/dept/update") public Department updateDepartment(@PathVariable("id") Department id ,@PathVariable("departmentName" )Department departmentname){ depaertmentMapper.updateDept(department); return deleteDepartment; } }
然后我们在进行数据的插入和访问的时候,我们就可以得到我们想要的东西