使用springboot框架和mybatis框架编写程序,查询所有书籍信息并显示在页面上(要求:①、使用注解进行框架整合 书籍信息存储在数据库中)。
时间: 2024-12-06 14:22:29 浏览: 16
在Spring Boot中整合MyBatis,你可以按照以下步骤操作:
1. **添加依赖**:
首先,在你的`pom.xml`文件中添加Spring Boot和MyBatis的依赖:
```xml
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
</dependency>
<!-- 如果使用的是MySQL -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
```
2. **创建实体类(Book.java)**:
定义一个代表书籍的实体类,使用Lombok或其他库进行注解简化属性:
```java
@Entity
public class Book {
@Id
private Long id;
private String title;
private String author;
// getter and setter...
}
```
3. **配置数据源和Mapper**:
在`application.properties`中配置数据源和JPA:
```properties
spring.datasource.url=jdbc:mysql://localhost:3306/bookstore
spring.datasource.username=root
spring.datasource.password=password
spring.jpa.hibernate.ddl-auto=update
mybatis.mapper-locations=classpath:mapper/*.xml
```
创建一个`BookMapper.xml`文件,用于定义SQL映射:
```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.example.book.BookMapper">
<select id="selectAllBooks" resultType="com.example.book.Book">
SELECT * FROM book;
</select>
</mapper>
```
4. **创建Service和Repository**:
`BookService.java`中注入Mapper,通过@Autowired自动装配:
```java
@Service
public class BookServiceImpl implements BookService {
private final BookMapper bookMapper;
@Autowired
public BookServiceImpl(BookMapper bookMapper) {
this.bookMapper = bookMapper;
}
@Override
public List<Book> selectAllBooks() {
return bookMapper.selectAllBooks();
}
}
```
5. **控制器(Controller)**:
在Controller里调用Service的方法,并将结果绑定到视图展示:
```java
@RestController
@RequestMapping("/books")
public class BookController {
@Autowired
private BookService bookService;
@GetMapping
public List<Book> getAllBooks() {
return bookService.selectAllBooks();
}
}
```
6. **模板引擎展示数据**:
使用Thymeleaf、Freemarker等模板引擎渲染HTML页面,显示查询结果。
阅读全文