mybatis是持久层框架,我们之前学习springboot的使用与数据库进行连接使用的是jdbctemple虽然那个也很方便,但是mybatis也很重要
首先我们要像平常一样构建springboot项目,有启动器,有控制器,有实体类等等
仅仅是多了映射接口和映射文件而已
我所谓的映射接口只是我所理解的真实情况可能会有误差,
接口里定义的方法会在我写的映射配置文件中会有实现方法,
而我的映射配置文件中的方法仅仅考虑sql语句的实现即可,
然后我们就可以对数据库进行增删改查的操作啦
启动器类
package cn.lnfvc;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
@SpringBootApplication
@MapperScan(basePackages = "cn.lnfvc.mapper")
public class App {
public static void main(String[] args) {
SpringApplication.run(App.class);
}
}
实体类
package cn.lnfvc.pojo;
public class Book {
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;
}
}
映射接口
package cn.lnfvc.mapper;
import cn.lnfvc.pojo.Book;
import org.apache.ibatis.annotations.Mapper;
import java.util.List;
@Mapper
public interface BookMapper {
List<Book> findAllBooks();
String addBooks();
String upData();
String delete();
}
控制器类
package cn.lnfvc.controller;
import cn.lnfvc.mapper.BookMapper;
import cn.lnfvc.pojo.Book;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import java.util.List;
@RestController
public class BookController {
@Resource
private BookMapper bookMapper;
@GetMapping("/books")
public List<Book> findAllBooks(){
return bookMapper.findAllBooks();
}
@GetMapping("/add")
public String addBooks(){
bookMapper.addBooks();
return "success";
}
@GetMapping("/upDate")
public String upData(){
bookMapper.upData();
return "success";
}
@GetMapping("/delete")
public String delete(){
bookMapper.delete();
return "success again";
}
}
说在配置文件前
我们的配置文件中是对数据库进行连接配置
和找到映射接口,实现我们想要的方法,
application.yml
mybatis:
# config-location: classpath:mybatis-config.xml
mapper-locations: mapping/BookMapper.xml
spring:
datasource:
url: jdbc:mysql://localhost:3309/ssa
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: 123
mybatis配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="cn.lnfvc.mapper.BookMapper">
<resultMap id="BookMapper" type="cn.lnfvc.pojo.Book">
<id property="id" column="id"/>
<result property="name" column="name"/>
</resultMap>
<select id="findAllBooks" resultType="cn.lnfvc.pojo.Book">
select * from ssa_test
</select>
<select id="addBooks" resultType="cn.lnfvc.pojo.Book">
insert into ssa_test values (15,'ssa')
</select>
<select id="upData" resultType="cn.lnfvc.pojo.Book">
update ssa_test set name = 'is me' where id=15
</select>
<select id="delete" resultType="cn.lnfvc.pojo.Book">
delete from ssa_test where id=15
</select>
</mapper>
下图是我的项目路径图
路径图
网友评论