SpringBoot整合MyBatis-Plus

MyBatis-Plus (opens new window)(简称 MP)是一个 MyBatis (opens new window)的增强工具,在 MyBatis 的基础上只做增强不做改变,为简化开发、提高效率而生。

 

 

 1、导入 MyBatis-Plus 所需要的依赖

 select Spring WebSpring Data JPA, and MySQL Driver.

<dependency>
        <groupId>com.baomidou</groupId>
        <artifactId>mybatis-plus-boot-starter</artifactId>
        <version>Latest Version</version>
    </dependency>

出错将Latest Version改为maven中存在的版本号

2、配置数据库连接信息

复制代码
#上下文地址
server.servlet.context-path=/ch6_5
#数据库地址,设置时区serverTimezone=asia/Shanghai
spring.datasource.url=jdbc:mysql://localhost:3306/test?characterEncoding=utf8&serverTimezone=asia/Shanghai
#数据库用户名
spring.datasource.username=root
#数据库密码
spring.datasource.password=root
#数据库驱动,SQL 8 改为com.mysql.cj.jdbc.Driver
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
复制代码

 解决MySQL时区问题

mysql中  SET GLOBAL time_zone = '+8:00';并去掉配置中时区设置

3、测试数据库是否连接成功

复制代码
@SpringBootTest
class SpringbootDataJdbcApplicationTests {

    //DI注入数据源
    @Autowired
    DataSource dataSource;

    @Test
    public void contextLoads() throws SQLException {
        //看一下默认数据源
        System.out.println(dataSource.getClass());
        //获得连接
        Connection connection =   dataSource.getConnection();
        System.out.println(connection);
        //关闭连接
        connection.close();
    }
}
复制代码

4.创建实体类

复制代码
@Data
public class User {
    private Long id;
    private String name;
    private Integer age;
    private String email;
}
复制代码

 

5.创建mapper目录以及对应的 Mapper 接口

复制代码
public interface UserMapper extends BaseMapper<User> {

}
复制代码

6. 在sprinboot启动类中添加@MapperScan注解

复制代码
@SpringBootApplication
@MapperScan("com.YourDirectory")
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(QuickStartApplication.class, args);
    }

}
复制代码

 7.测试

@SpringBootTest
public class SampleTest {

    @Autowired
    private UserMapper userMapper;

    @Test
    public void testSelect() {
        System.out.println(("----- selectAll method test ------"));
        List<User> userList = userMapper.selectList(null);
        Assert.assertEquals(5, userList.size());
        userList.forEach(System.out::println);
    }

}

控制台 输出

User(id=1, name=Jone, age=18, email=test1@baomidou.com)
User(id=2, name=Jack, age=20, email=test2@baomidou.com)
User(id=3, name=Tom, age=28, email=test3@baomidou.com)
User(id=4, name=Sandy, age=21, email=test4@baomidou.com)
User(id=5, name=Billie, age=24, email=test5@baomidou.com)

 

posted @ 2021-07-07 10:57  幻影如梦  阅读(102)  评论(0)    收藏  举报