遇到的问题:
1.Invalid bound statement (not found)
分两种解决办法:
接口文件和映射文件分开:
mybatis.mapper-locations=classpath:mappers/*.xml
在application.properties配置文件中指定映射文件的位置,这个配置只有接口和映射文件不在同一个包的情况下,才需要指定。
接口文件和映射文件在一起:
此时,Mybatis的xml映射文件不会编译到target的class目录下,所以我们需要在pom.xml文件中配置resource
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>*/.xml</include>
</includes>
</resource>
</resources>
2.java.sql.SQLException: The server time zone value '�й���ʱ��' is unrecognized or represents more than
根据警告说明数据库驱动采用的是新的驱动器SPI机制加载的, 解决办法
1.改驱动 com.mysql.cj.jdbc.Driver
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
2.链接url的时区必须加上, 需要用到的地方都要加上
spring.datasource.url=jdbc:mysql://localhost:3306/spring?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC
整个过程:
1.在pom.xml文件添加mybatis相关依赖:
<!--MyBatis整合SpringBoot的起步依赖-->
<dependency>
<groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId>
<version>2.0.0</version>
</dependency>
<!--MySQL的驱动依赖-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
2.在Mybatis反向工程生成的StudentMapper接口上加一个Mapper注解
@Mapper作用:mybatis自动扫描数据持久层的映射文件及DAO接口的关系
@Mapper
public interface BookMapper {
int insert(Book record);
int insertSelective(Book record);
}
3.编写业务层:
public interface bookService {
void insert(Book book);
void inserterr(Book book);
}
@Service
public class bookServiceImp implements bookService{
@Autowired
private BookMapper bookMapper;
@Override
public void insert(Book book) {
bookMapper.insert(book);
}
}
这里自动可能会出现:
但没影响,也可正常执行。
4.编写控制层:
@Autowired
private bookService bookService;
@RequestMapping("/testmybatis")
public @ResponseBody String insertBook(@RequestParam String bookName,Integer isbn,BigDecimal price){
System.out.println(bookName);
Book book=new Book();
book.setIsbn(isbn);
book.setBookName(bookName);
book.setPrice(price);
System.out.println(book);
bookService.insert(book);
return "hi";
}
5.开启springboot,测试即可
http://localhost:8080/testmybatis?isbn=7&bookName=spring&price=10