说明:创建springboot工程,数据库表book,实体类Book


说明:创建了book表,添加了id,type,name,description字段。

说明:生成对应的get和set方法,构造方法等
- package com.forever.domain;
-
- public class Book {
- // 使用的是包装类型
- private Integer id;
- private String type;
- private String name;
- private String description;
-
- public Book() {
- }
-
- public Book(Integer id, String type, String name, String description) {
- this.id = id;
- this.type = type;
- this.name = name;
- this.description = description;
- }
-
- @Override
- public String toString() {
- return "Book{" +
- "id=" + id +
- ", type='" + type + '\'' +
- ", name='" + name + '\'' +
- ", description='" + description + '\'' +
- '}';
- }
-
- public Integer getId() {
- return id;
- }
-
- public void setId(Integer id) {
- this.id = id;
- }
-
- public String getType() {
- return type;
- }
-
- public void setType(String type) {
- this.type = type;
- }
-
- public String getName() {
- return name;
- }
-
- public void setName(String name) {
- this.name = name;
- }
-
- public String getDescription() {
- return description;
- }
-
- public void setDescription(String description) {
- this.description = description;
- }
- }
说明:配置Mybatis
说明:test是数据的名称
- #下面这些内容是为了让MyBatis映射
- #指定Mybatis的Mapper文件
- mybatis.mapper-locations=classpath:mappers/*xml
- #指定Mybatis的实体目录
- mybatis.type-aliases-package=com.forever.mybatis.entity
- #数据库连接信息
- #驱动类名称
- spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
- #数据库连按的url
- spring.datasource.url=jdbc:mysql://localhost:3306/test
- #普连接数据库的用户名
- spring.datasource.username=root
- #连接数库的密码
- spring.datasource.password=123456
说明:Mapper是一个用于映射数据库表和Java对象的工具。它可以帮助开发人员将数据库表中的数据映射到Java对象中,从而简化数据库操作的过程。其实可以将接口认为了对象了(内部有处理)
- package com.forever.mapper;
-
- import com.forever.domain.Book;
- import org.apache.ibatis.annotations.Mapper;
- import org.apache.ibatis.annotations.Select;
-
- import java.util.List;
-
-
- //运行时,会自动生成该接口实现类对象(代理对象),并且将对象交给IOC容器管理
- @Mapper
- public interface BookMapper {
- //查询全部用户信息
- @Select("select * from book")
- // list方法名
- public List
list(); - }
说明:@SpringBootTest整合单元测试的注释,通过注入的方式拿到bookMapper
- package com.forever;
-
- import com.forever.domain.Book;
- import com.forever.mapper.BookMapper;
- import org.junit.jupiter.api.Test;
- import org.springframework.beans.factory.annotation.Autowired;
- import org.springframework.boot.test.context.SpringBootTest;
-
- import java.util.List;
-
- @SpringBootTest //springboot整合单元测试的注释
- class SpringbootMybatisQuickstartApplicationTests {
- // 注入
- @Autowired
- private BookMapper bookMapper;
- @Test
- // 定义一个测试listBook方法的功能
- public void testListBook(){
- List
bookList= bookMapper.list(); - bookList.stream().forEach(book->{
- System.out.println(book);
- });
- }
-
- }
