MyBatis与SpringBoot

本文介绍了MyBatis的基本概念和工作原理,并详细阐述了如何在SpringBoot项目中集成MyBatis,包括配置数据库连接、添加依赖、创建实体类和DAO。通过测试用例演示了MyBatis的使用过程,同时解决了一些常见的错误问题,如配置文件路径错误和初始化SQL脚本的放置位置。
摘要由CSDN通过智能技术生成

Mybatis

1、什么是MyBatis?

   MyBatis是支持普通SQL查询、存储过程和高级映射的优秀持久层框架。MyBatis消除了几乎所有的JDBC代码和参数的手工设置,以及对结果的检索。MyBatis可以使用简单的xml或注解用于配置和原始映射,将接口和Java的POJO(plain oldjava objects,普通的Java对象)映射成数据库中的记录。

 

2、原理

   每一个MyBatis的应用程序都以一个SqlSessionFactory对象的实例为核心。SqlSessionFactory对象的实例可以通过SqlSessionFactoryBuilder对象来获得。SqlSessionFactoryBuilder对象可以通过xml配置文件,或者从Configuration类实例中来构建SqlSessionFactory对象。

3、MyBatis和SpringBoot结合

分三步,将MyBatis导入我的SpringBoot工程中:

(1)在application.porperties增加spring配置数据库URL

spring.datasource.url=jdbc:mysql://localhost:3306/fastnews?useUnicode=true&characterEncoding=utf8&useSSL=false
spring.datasource.username=root
spring.datasource.password=root
mybatis.config-location=classpath:mybatis-config.xml
#logging.level.root=DEBUG
spring.velocity.suffix=.html
spring.velocity.cache=false
spring.velocity.toolbox-config-location=toolbox.xml

 

(2)porm.xml增加依赖

<dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <scope>runtime</scope>
</dependency>
<dependency>
   <groupId>org.mybatis.spring.boot</groupId>
   <artifactId>mybatis-spring-boot-starter</artifactId>
   <version>1.1.1</version>
</dependency>

(3)在templates包下添加mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>

    <settings>
        <!-- Globally enables or disables any caches configured in any mapper under this configuration -->
        <setting name="cacheEnabled" value="true"/>
        <!-- Sets the number of seconds the driver will wait 
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值