mybatis的使用

基础介绍

mybatis是通过对JDBC的封装实现的,他是针对ORM的。'datasource也是对于JDBC的封装,但是它是针对连接管理的。

半ORM框架Object Relationship Mapping 对象关系映射

半ORM:需要在mapper文件中配置映射关系

作用:用来操作数据库,解决原始jdbc代码冗余

mybatis-config.xml

(1)environment设置数据源

(2)类型别名

(3)mapper文件的注册

mapper文件

(1)dao方法的实现---sql语句

开发步骤:

1.entity

2.类型别名

3.表

4.dao接口

5.mapper文件

6.mapper文件的注册

7.API编程

mybatis开发流程

mybatis流程:

(1)引入pom

(2)编写mybatis-config.xml文件在resources目录,配置数据源和mybatis的设置

(3)编写mapper文件在resources/mapper目录,和dao类配合

(4)创建SessionFactory

(5)建立Session,断开Session

配置mybatis

public StudentDao(String configPath) throws IOException {
    InputStream inputStream = Resources.getResourceAsStream(configPath);    
    sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
    }

但是使用

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

就可以直接使用SqlSessionFactory直接注入就行了,springboot给配置好了

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>
    <!-- Global settings -->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>

    <!-- Type aliases -->
    <typeAliases>
        <typeAlias alias="User" type="com.example.model.User"/>
        <!-- Other type aliases... -->
    </typeAliases>

    <!-- Plugins (if any) -->
    <plugins>
        <plugin interceptor="com.example.plugins.MyPlugin">
            <!-- Plugin-specific configuration -->
        </plugin>
    </plugins>

    <!-- Environments -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="com.alibaba.druid.pool.DruidDataSource">
                <property name="driverClassName" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/mydatabase"/>
                <property name="username" value="your_username"/>
                <property name="password" value="your_password"/>
                <!-- Druid specific properties -->
                <property name="initialSize" value="5"/>
                <property name="maxActive" value="20"/>
                <!-- Other properties... -->
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="classpath:mapper/student_mapper.xml"/>
    </mappers>
</configuration>

mapper.xml
<?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.demo1.dao.StudentDao">
    <select id="findAll" resultType="com.yogurt.po.Student">
        SELECT * FROM schedule_system.student;
    </select>

    <insert id="insert" parameterType="com.yogurt.po.Student">
        INSERT INTO schedule_system.student (name) VALUES (#{name});
    </insert>

    <delete id="delete" parameterType="int">
        DELETE FROM schedule_system.student WHERE id = #{id};
    </delete>
</mapper>

InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession sqlSession = sqlSessionFactory.openSession();

代理对象

UserDao userDao=sqlSession.getMapper(UserDao.class);

List users=userDaol.queryAll();

dao接口

代理对象

如何在resourece目录下和接口目录相同?编译以后文件在一个目录就行了 resource/top/haidong/mapper

包扫描加载mapper接口(代替mapper的配置)

表中字段名和java类的属性不同,无法映射的解决方法:

(1)给select语句中的字段名起别名。as

(2)使用resultmap映射

<resultMap id="brandResultMap" type="brand">
id是主键的映射,result是一般字段的映射
<id colum="key_permiay" property="keyPermiay">
<result colum="brand_name"property="brandName">
<result colum="company_name" property="companyName">
</resultMap>
<select id="selectAll" resultMap="brandResultMap">
select * from tb
</select>

sql参数

参数占位符,${}有sql注入的风险

#{}:在sql中使用?代替

${}:sql直接注入

parameterType:传入参数类型,可以省略。

sql中的特殊字符(比如<,和xml特殊字符冲突)的处理:

(1)转义字符

(2)<![CDATA [内容]>:写一个CD就能跳出来了

多条件查询

dao接口传入sql 的多个占位符参数,如何一一对应?

(1)散装参数注入sql占位符,在dao接口参数使用@Param:@Param("参数占位符名称")

(2)将参数封装成对象,要求对象属性要和占位符名称一一对应。

将对象传入。

(3)传入map

单条件动态查询

where
<choose >
<when test="a!=null and a!=""" ">
    state= #{state}
</when>
<when test="">
</when>
<otherwise>
</otherwise>

多条件动态查询

select * from t
<where>
<if test="state!=null">
    state=#{state}
</if>
<if test="title!=null">
    title=#{title}
</if>
</where>

where元素只会在子元素返回内容的情况下才插入where语句,若开头为"AND"或者"OR",会去掉。

mybatis默认开启事务,进行增删改操作后需要sqlSession.commit();手动提交。

更新

<update id="updateAuthorIfNecessary">
  update Author
    <set>
      <if test="username != null">username=#{username},</if>
      <if test="password != null">password=#{password},</if>
      <if test="email != null">email=#{email},</if>
      <if test="bio != null">bio=#{bio}</if>
    </set>
  where id=#{id}
</update>

set会自动删掉if字段内的逗号,以及自动添加"set"

MyBatis 会通过 Mapper XML 文件来实现 DAO 接口

生命周期

SqlSessionFactoryBuilder:这个就是一个建造者类,随时可以被创建使用和丢弃,没什么问题,SqlSessionFactoryBuilder 实例的最佳作用域是方法作用域

SqlSessionFactory:一个应用程序创建一个就行了,可以使用单例模式来实现。

SqlSession:最佳实践是方法作用域和请求作用域,不能将它和任何一个类绑定。

映射器实例:和sqlsession一样,方法作用域或请求。

sqlsession和connection的关系

在sqlsessionfacotory创建sqlsession时候,给sqlsession分配一个connection,当sqlsession关闭时候关闭connection。

sqlsessionfactory管理数据库连接,它是通过configuration来创建连接的,而不是driverManager。

相关推荐
这孩子叫逆8 分钟前
Spring Boot项目的创建与使用
java·spring boot·后端
星星法术嗲人12 分钟前
【Java】—— 集合框架:Collections工具类的使用
java·开发语言
黑不溜秋的26 分钟前
C++ 语言特性29 - 协程介绍
开发语言·c++
一丝晨光31 分钟前
C++、Ruby和JavaScript
java·开发语言·javascript·c++·python·c·ruby
天上掉下来个程小白33 分钟前
Stream流的中间方法
java·开发语言·windows
xujinwei_gingko44 分钟前
JAVA基础面试题汇总(持续更新)
java·开发语言
liuyang-neu1 小时前
力扣 简单 110.平衡二叉树
java·算法·leetcode·深度优先
sp_wxf1 小时前
Lambda表达式
开发语言·python
一丝晨光1 小时前
Java、PHP、ASP、JSP、Kotlin、.NET、Go
java·kotlin·go·php·.net·jsp·asp
罗曼蒂克在消亡1 小时前
2.3MyBatis——插件机制
java·mybatis·源码学习