勿谓今日不学而有来日,勿谓今年不学而有来年。
日月逝矣,岁不我延。

Mybatis的配置与CURD操作

MyBatis 是一款优秀的持久层ORM框架,简单易上手。

IDEA基于Maven配置Mybatis

1、创建Maven项目,模板选择quickstart,注意包名!

2、配置Maven 选择本地的Maven或者IDEA自带的Maven

3 、在pom.xml中引入Mybatis和jdbcDrive依赖

 <dependencies>
   .......
    <!--MysqlDrive-->
    <dependency>
      <groupId>mysql</groupId>
      <artifactId>mysql-connector-java</artifactId>
      <version>6</version>
    </dependency>
    <!--Mybatis-->
      <dependency>
          <groupId>org.mybatis</groupId>
          <artifactId>mybatis</artifactId>
          <version>3.4.4</version>
      </dependency>
  </dependencies>

引入以上两个依赖后目录会变成以下结构:

4、创建配置文件

在main下创建resource文件夹并Mark Directory as Resources Root

创建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>
        <!--当返回行的所有列都是空时,MyBatis默认返回null-->
        <setting name="returnInstanceForEmptyRow" value="true"/>
        <!--log4j打印sql-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

    <environments default="development">

        <environment id="development">
            <!--使用了 JDBC 的提交和回滚设置,它依赖于从数据源得到的连接来管理事务作用域-->
            <transactionManager type="JDBC"/>
            <!--使用数据池,复用实例-->
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/>
                <!--<property name="driver" value="com.mysql.cj.jdbc.Driver"/>-->
                <property name="url" value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai&amp;characterEncoding=utf8"/>
                <property name="username" value="root"/>
                <property name="password" value="root"/>
            </dataSource>
        </environment>
    </environments>

    <mappers>
        <mapper resource="UserDAO.xml"></mapper>
    </mappers>

</configuration>

5、配置log4j输出sql语句:

在pom.xml中引入log4j依赖

<!--Logj4-->
      <dependency>
          <groupId>log4j</groupId>
          <artifactId>log4j</artifactId>
          <version>1.2.17</version>
      </dependency>

在Mybatis-config.xml中<settings>节点配置sql输出

<settings>
        <!--log4j打印sql-->
        <setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>

6、编写实体类并编写映射文件UserDao.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="user">
    
</mapper>

Mybatis的CURD操作

SqlSession工具类

普通的SqlSessionFactory SqlSession获取

SqlSession是线程不安全的所以不能共享也就不能提取出来。

        String resource = "Mybatis-config.xml";
        //创建SqlSessionFactoryBuilder对象
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        // 配置文件输入流
        InputStream inputStream = Resources.getResourceAsStream(resource);
        //创建SessionFactory
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
        //开启session
        SqlSession session = sqlSessionFactory.openSession();

实际使用中会频繁的创建SqlSessionFactory SqlSession所以抽取成工具类,直接获取SqlSessionFactory或者SqlSession

package cn.llanc.utils;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class SqlSessionUtils {
    private static SqlSessionFactory sqlSessionFactory;
    //静态初始化块  只加载一次
    static {
        try {
            //创建SqlSessionFactoryBuilder对象
            SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
            //获取输入流
            InputStream inputStream = Resources.getResourceAsStream("Mybatis-config.xml");
            //创建SessionFactory
            sqlSessionFactory = sqlSessionFactoryBuilder.build(inputStream);
            sqlSession=sqlSessionFactory.openSession(true);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        return sqlSessionFactory;
    }
}

查询

UserDao.xml

<!--在select节点中不允许含有注释-->
        <!--字符串拼接时 如果传入参数为普通类型则${}中只能写value-->
        <!--SELECT * from `user` where name LIKE #{name}-->
<mapper  namespace="user">
    <!--主键返回 id set给User.id-->
    <select id="getUserById" resultType="cn.llanc.pojo.User">
        SELECT * FROM `user` WHERE id = #{id}
    </select>
    <!--姓名模糊查询-->
    <select id="getUserByName" parameterType="string" resultType="cn.llanc.pojo.User">
        SELECT * from `user` where name LIKE '%${value}%'
    </select>
</mapper>

java代码

        User user = session.selectOne("getUserById", "1");
        System.out.println(user);
        session.commit();
        session.close();

插入

UserDao.xml

<!--                                                        自动返回主键   启动自增               主键  -->
    <insert id="insertUser" parameterType="cn.llanc.pojo.User" useGeneratedKeys="true" keyProperty="id">
        <!--<selectKey keyProperty="id" resultType="int" order="AFTER">-->
            <!--SELECT LAST_INSERT_ID()-->
        <!--</selectKey>-->
        INSERT INTO `user`(`name`, `sex`, `brith`) VALUES (#{name}, #{sex}, #{brith});
    </insert>

注意返回主键的方式有两种

java代码

        User user = new User();
        user.setName("王五");
        user.setSex("男");
        user.setBrith(Date.valueOf("1994-2-3"));
        session.insert("user.insertUser", user);
        System.out.println(user.getId());
        session.close();

修改和删除

UserDao.xml

<!--修改 -->
    <update id="updateUser" parameterType="cn.llanc.pojo.User">
        UPDATE `mybatis`.`user` SET `name` = #{name}, `sex` = #{sex}, `brith` = #{brith} WHERE `id` = #{id};
    </update>
    <!--删除-->
    <delete id="deleteUser" parameterType="int">
        DELETE from `user` where id=#{id}
    </delete>

java代码

@Test
    public void updateUser(){
        SqlSessionFactory sqlSessionFactory= SqlSessionUtils.getSqlSessionFactory();
        SqlSession session = sqlSessionFactory.openSession(true);//参数b 用于指示是否自动提交事务
        User user = session.selectOne("getUserById",14);
        user.setName("李四");
        user.setBrith(Date.valueOf("1994-12-12"));
        session.update("user.updateUser", user);
        session.close();
    }

    @Test
    public void deleteUser(){
        SqlSession session = SqlSessionUtils.getSqlSession();//参数b 用于指示是否自动提交事务
        session.delete("user.deleteUser", 13);
        session.close();
    }

源码见:https://github.com/llanc/Mybatis

赞(1)
未经允许不得转载:喋喋不休 » Mybatis的配置与CURD操作

评论 抢沙发

评论前必须登录!

 

精品网站

有券无忧电脑壁纸精选