创建SpringBoot项目查看依赖
目录结构:
BookDao类
package com.example.dao;
import com.example.domain.Book;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;
@Mapper
public interface BookDao {
@Select("select * from Book where id=#{id}")
public Book getById(Integer id);
}
Book类
package com.example.domain;
public class Book {
private Integer id;
private String name;
private String type;
private String description;
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + ''' +
", type='" + type + ''' +
", description='" + description + ''' +
'}';
}
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;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
把原来的application.properties 注释掉,新建配置文件 application.yml
application.yml
spring:
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: root
password: ""
数据库表的sql语句:
CREATE TABLE `book` ( `id` int(11) NOT NULL, `name` varchar(32) NOT NULL, `type` varchar(32) NOT NULL, `description` varchar(512) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=utf8; -- -- Dumping data for table `book` -- INSERT INTO `book` (`id`, `name`, `type`, `description`) VALUES (1, '武动乾坤', '玄幻', ' 修炼一途,乃窃阴阳,夺造化,转涅盘,握生死,掌轮回。武之极,破苍穹,动乾坤!'); -- -- Indexes for dumped tables -- -- -- Indexes for table `book` -- ALTER TABLE `book` ADD PRIMARY KEY (`id`); COMMIT;
Springboot08MybatisApplicationTests类
package com.example;
import com.example.dao.BookDao;
import com.example.domain.Book;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
@SpringBootTest
class Springboot08MybatisApplicationTests {
@Autowired
private BookDao bookDao;
@Test
void testGetById(){
Book book=bookDao.getById(1);
System.out.println(book);
}
@Test
void contextLoads() {
}
}
运行结果 :testGetById()
整合数据源对象
设置数据源
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.cj.jdbc.Driver
url: jdbc:mysql://localhost:3306/test
username: root
password: ""
注意事项
SpringBoot 版本低于2.4.3 (不含),Mysql驱动版本大于8.0时,需要在url连接中配置时区
spring.datasource.url=jdbc:mysql://localhost:3306/test?serverTimezone=UTC



