【MyBatis】一、MyBatis概述与基本使用

Mybatis概述

Mybatis是一个半自动化的框架,需要自己写sql语句,对比JDBC其有耦合性更低的SQL语句与Java代码,各司其职不相互冗杂,对比Hibernate与JPA其又有更灵活的SQL编写能力。

环境搭建

引入相关依赖并打jar包

    <dependencies>
        
        <dependency>
            <groupId>org.mybatisgroupId>
            <artifactId>mybatisartifactId>
            <version>3.5.7version>
        dependency>
        
        <dependency>
            <groupId>junitgroupId>
            <artifactId>junitartifactId>
            <version>4.12version>
            <scope>testscope>
        dependency>
        
        
        <dependency>
            <groupId>com.mysqlgroupId>
            <artifactId>mysql-connector-jartifactId>
            <version>8.0.32version>
        dependency>
    dependencies>

在resource下新建mybatis-config.xml文件,并粘贴以下配置:


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.cj.jdbc.Driver"/>
                <property name="url" value="jdbc:mysql://localhost:3306/MyBatis"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            dataSource>
        environment>
    environments>
    
    <mappers>
        <mapper resource="mappers/UserMapper.xml"/>
    mappers>
configuration>

在mapper文件夹下创建UserMapper接口,每张表对应一个Mapper接口

在resource下创建xml配置文件

在mapper标签下进行sql语句的编写


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.qinghe.mybatis.mapper.UserMapper">

    
    
mapper>

例如一个insert语句:


DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">

<mapper namespace="com.qinghe.mybatis.mapper.UserMapper">


    <insert id="insertUser">
        insert into t_user values(null, 'admin', '123456', 23, 'm', '[email protected]')
    insert>


mapper>

一个插入语句的示例

创建一个mapper层的接口

public interface UserMapper {


    /**
     * 添加用户信息
     * @return
     */
    int insertUser();
}

在test中的测试如下:

public class MyBatisTest {
    @Test
    public void testMyBatis() throws IOException {
        //加载配置文件
        InputStream is = Resources.getResourceAsStream("mybatis-config.xml");
        //获取SqlSessionFactoryBuilder,工厂模式
        SqlSessionFactoryBuilder sqlSessionFactoryBuilder = new SqlSessionFactoryBuilder();
        //获取sqlSessionFactory,传入配置文件的流信息
        SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBuilder.build(is);
        //获取sqlSession,sqlSession是数据库与Java进行数据交换的中介,就像是HttpSession时浏览器与Java的中介一样
        //openSession中的参数true为自动提交的意思
        SqlSession sqlSession = sqlSessionFactory.openSession(true);
        //获取mapper接口对象,getMapper(CLass)方法使用代理模式,在底层创建了一个UserMapper对象并赋值给mapper
        UserMapper mapper = sqlSession.getMapper(UserMapper.class);
        //调用方法
        int result = mapper.insertUser();
        //提交事务,语句必须执行过事务提交之后才会在数据库显示
        //要么在sqlSessionFactory创建对象时开启自动提交,要么就手动提交
//        sqlSession.commit();
        System.out.println("result:" + result);
    }
}

添加日志功能

在resource文件夹下创建日志的配置文件:log4j.xml并添加如下配置:


DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="STDOUT" class="org.apache.log4j.ConsoleAppender">
        <param name="Encoding" value="UTF-8" />
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%-5p %d{MM-dd HH:mm:ss,SSS} %m (%F:%L) \n" />
        layout>
    appender>
    <logger name="java.sql">
        <level value="debug" />
    logger>
    <logger name="org.apache.ibatis">
        <level value="info" />
    logger>
    <root>
        <level value="debug" />
        <appender-ref ref="STDOUT" />
    root>
log4j:configuration>

Mybatis-config.xml配置文件详解


DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>


    <properties resource="jdbc.properties" />

    <typeAliases>

        <typeAlias type="com.qinghe.mybatis.pojo.User" alias="User">typeAlias>

        <package name="com.qinghe.mybatis.pojo">package>
    typeAliases>

    
    <environments default="development">
        <environment id="development">

            <transactionManager type="JDBC"/>

            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driver}"/>
                <property name="url" value="${jdbc.url}"/>
                <property name="username" value="${jdbc.username}"/>
                <property name="password" value="${jdbc.password}"/>
            dataSource>
        environment>
    environments>
    
    <mappers>





        <package name="com.qinghe.mybatis.mapper">package>
    mappers>
configuration>

你可能感兴趣的:(Mybatis,mybatis)