1、添加依赖包和配置数据源
在官网找到对应的依赖
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.2.2</version>
</dependency>
数据源不变
application.yml
spring:
datasource:
username: root
password: 12345
url: jdbc:MysqL://localhost:3306/ssmbuild?useSSL=true&useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai
driver-class-name: com.MysqL.cj.jdbc.Driver
#这个是指定对应的扫描包和配置文件,相当于不用写mybatis的配置文件了
mybatis:
type-aliases-package: com.wcy.pojo
mapper-locations: classpath:mybatis/mapper/*.xml
2、创建pojo和mapper
Books类
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
@Data
@AllArgsConstructor
@NoArgsConstructor
public class Books {
private int bookID;
private String bookName;
private int bookCounts;
private String detail;
}
BookMapper类
import com.wcy.pojo.Books;
import org.apache.ibatis.annotations.Mapper;
import org.springframework.stereotype.Repository;
import java.util.List;
//这个注解表示这是mybatis的一个mapper类
@Mapper
@Repository
public interface BookMapper {
List<Books> queryAllBooks();
}
BookMapper.xml
<?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="com.wcy.mapper.BookMapper">
<select id="queryAllBooks" resultType="Books">
select * from ssmbuild.books
</select>
</mapper>
3、编写控制器
BookController类
@RestController
public class BookController {
@Autowired
private BookMapper bookMapper;
@GetMapping("/queryAllBooks")
public List<Books> queryAllBooks() {
List<Books> bookList = bookMapper.queryAllBooks();
for (Books book : bookList) {
System.out.println(book);
}
return bookList;
}
}
测试结果:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。