Springboot整合mybatis步骤及注意事项

总结一下自己使用springboot整合mybatis的过程,写了一个类似于后台注册的片段,很基础,日后可能有进阶版。

一、首先添加依赖

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>2.2.0</version>
        </dependency>

二、建立Entity实体类和Mapper类

如图:
在这里插入图片描述
在resources文件夹下建立mybatis文件夹,文件夹下建立mapper文件夹,在其中 建立 *. xml文件,注意文件名与mapper包中的文件名保持一致
实体类@Entity 开头 mapper包 @Mapper 开头,在主文件中还要加上
@MapperScan(“com.example.august.mapper”) (扫描这个包,可以写自己的)

三、配置文件

mybatis文件夹中添加mybatis-config.xml文件,内容如下,可根据需要自由更改:

<?xml version="1.0" encoding="UTF-8" ?>
<!-- Copyright 2009-2012 The MyBatis Team Licensed under the Apache License,
	Version 2.0 (the "License"); you may not use this file except in compliance
	with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
	Unless required by applicable law or agreed to in writing, software distributed
	under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES
	OR CONDITIONS OF ANY KIND, either express or implied. See the License for
	the specific language governing permissions and limitations under the License. -->
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

    <settings>
        <!-- 这个配置使全局的映射器启用或禁用 缓存 -->
        <setting name="cacheEnabled" value="true" />
        <!-- 设置超时时间, 它决定驱动等待一个数据库响应的时间 -->
        <setting name="defaultStatementTimeout" value="100" />
        <setting name="jdbcTypeForNull" value="OTHER" />
    </settings>
</configuration>

然后在mybatis文件夹下建立mapper文件夹存放.xml文件。做完这些之后,进入application.properties文件,添加

mybatis.config-location=classpath:mybatis/mybatis-config.xml
mybatis.mapper-locations=classpath:mybatis/mapper/*.xml
mybatis.type-aliases-package=com.example.august.entity`

最后一个配置是实体类所在的位置,可以根据需要改成自己的。

四:Mybatis文件夹下mapper

列举一个片段

<?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.august.mapper.BookDao">

    <insert id="insert" parameterType="com.example.august.entity.Book">
        insert into book(title, number, price)
        values (#{title}, #{number}, #{price})
    </insert>
</mapper>

其中 id 是mapper包中对应的方法名,parameterType 参数类型,还有resultType 返回值类型,可以继续深入发掘,例如传参方法等问题

最后就可以在service包中的类中初始化mapper包下的类并使用其中的方法了

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值