spring Boot 整合Mybatis框架

1.添加依赖(创建时勾选mybatis选框,也可以进去通过pom.xml右键spring里勾选,也可以配置pom.xml配置信息)
我们添加了mybatis依赖以后,spring框架启动时会对mybatis进行自动配置。例如SqlSessionFactory工厂对象的创建。
spring框架对帮我配置大多配置信息

    配置信息:
    <dependency>
    <groupId>org.mybatis.spring.boot</groupId>
    <artifactId>mybatis-spring-boot-starter</artifactId>
    <version>2.1.3</version>
    </dependency>
配置mybatis中的sql日志的输出:(com.cy为我们写的项目的根包)

application.propertiesz中配置

logging.level.com.cy=DEBUG

对数据库操作两种方式

第一种:通过在接口上添加注解的方式

@Mapper//表示将这个接口交给spring来管理让spring帮我们创建实现类
piblic inerface DaoMapper{
    @Delete("delete from db_datas where id=#{id}")
    void deleteById(Integer id);
}

第二种:通过配置xml文件来实现;一般使用于较复杂或动态sql

1:编写接口方法
@Mapper
piblic inerface DaoMapper{
    void deleteById(Integer id);
}

2.在resources目录下创建xml文件

<mapper namespace="接口全路径">
    <delete id="deleteById">
        delete from db_datas where id=#{id}
    </delete>
</mapper>

3.配置xml文件信息位置

mybatis.mapper-locations=classpath:/mapper/*.xml

4.编写测试类

@StingapplicationBoot
class textDaoMapper{
@Autowarid
private DaoMapper daomapper;//底层帮我们配置了sqlsession会话
    @Test
    public void text(){
    syso(daomapper.deleteById(2));
    }   
}

对动态sql的进阶

@Mapper
piblic inerface DaoMapper{
    void deleteById(Integer...ids);
}

<mapper namespace="接口全路径">
    <delete id="deleteById">
        delete from db_datas 
        <where>
        <if text="array!=null and array.length>0">
        id in
        <foreach collection="array" open="(" close=")" separator="," item="id">
        #{id}   //item="id"和#{id},名保持一致
        </foreach>
        </if>
        or 5=60
        </Where>
    </delete>
</mapper>
//注:这个array是底层帮我们创建的~~~~

棘丶
12 声望1 粉丝

下一篇 »
ajax