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。

相关推荐

  1. Mybatis使用

    2024-01-20 07:06:05       28 阅读
  2. mybatis-plus使用

    2024-01-20 07:06:05       20 阅读
  3. mybatis标签使用

    2024-01-20 07:06:05       45 阅读
  4. Mybatis-Plus】关于使用mybaties-plus出现问题

    2024-01-20 07:06:05       15 阅读
  5. mybatisinclude和sql使用

    2024-01-20 07:06:05       12 阅读
  6. mybatis使用

    2024-01-20 07:06:05       14 阅读
  7. Mybatis之like、likeRight、likeLeft使用

    2024-01-20 07:06:05       18 阅读

最近更新

  1. TCP协议是安全的吗?

    2024-01-20 07:06:05       16 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-20 07:06:05       16 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-20 07:06:05       15 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-20 07:06:05       18 阅读

热门阅读

  1. spark的jdbc接口,类似于hiveserver2

    2024-01-20 07:06:05       31 阅读
  2. JVM介绍

    JVM介绍

    2024-01-20 07:06:05      28 阅读
  3. 【LeetCode】哈希表精选5题

    2024-01-20 07:06:05       38 阅读
  4. 1.19 力扣中等图论

    2024-01-20 07:06:05       34 阅读
  5. JVM的即时编译(JIT)优化原理:加速程序的执行

    2024-01-20 07:06:05       28 阅读
  6. 网络 - 网速很慢一定是网不好引起的吗?

    2024-01-20 07:06:05       33 阅读
  7. UDP协议

    UDP协议

    2024-01-20 07:06:05      32 阅读
  8. MySQL Interview Speedrun

    2024-01-20 07:06:05       29 阅读