单独使用MyBatis的简单示例

时间:2022-11-28 05:13:03

 

单独使用MyBatis的简单示例:
mybaties-config.xml:
MyBatis配置文件

<?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>
    <typeAliases><!-- 别名 -->
        <typeAlias alias="role" type="com.xc.pojo.Role"/>
    </typeAliases>   <!-- 数据库环境 -->
    <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/springmvc?useSSL=false&amp;serverTimezone=Hongkong&amp;characterEncoding=utf-8&amp;autoReconnect=true"/>
                <property name="username" value="root"/>
                <property name="password" value="123456"/>
            </dataSource>
        </environment>
    </environments>   <!-- 映射文件 -->
    <mappers>
        <mapper resource="mapper/RoleMapper.xml"/>
    </mappers>
</configuration>

 


Role.java:
POJO对象
构造一个POJO对象。最终查询会映射到它上面,或者将其保存到数据库中。

package com.xc.pojo;


public class Role {
    
    //CREATE TABLE `t_role` (
    //   `id` int(12) NOT NULL AUTO_INCREMENT,
    //   `role_name` varchar(60) NOT NULL,
    //   `note` varchar(512) DEFAULT NULL,
   //   PRIMARY KEY (`id`)
   // )

    private Long id;
    private String roleName;
    private String note;

   //get...set...
}

 


RoleMapper.java:
映射器接口
其中,insertRole代表插入一个Role对象;deleteRole则是删除;updateRole是修改一个Role对象;getRole是获取一个Role对象;findRoles则是通过角色名称获得一个角色对象列表。

package com.xc.mapper;

import com.xc.pojo.Role;
import org.apache.ibatis.annotations.Select;

import java.util.List;

public interface RoleMapper {

    public Role getRole(Long id);

    @Select("select id, role_name as roleName, note from t_role where id=#{id}")
    public Role getRole2(Long id);

    public int insertRole(Role role);

    public int deleteRole(Long id);

    public int updateRole(Role role);

    public List<Role> findRoles(String roleName);

}

 


RoleMapper.xml:
映射器XML文件,描述映射关系,SQL等内容
这是一些比较简单的SQL语句,insert、delete、select、update元素代表了增、删、查、改,而它们里面的元素id则标识了对应的SQL。parameterType标出了是什么类型的参数,re-sultType则代表结果映射成为什么类型。其中insert、delete和update返回的都是影响条数。

<?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.xc.mapper.RoleMapper">
    <insert id="insertRole" parameterType="role">         
    insert into t_role(role_name, note) values(#{roleName}, #{note}) </insert> <delete id="deleteRole" parameterType="long">
    delete from t_role where id= #{id} </delete> <update id="updateRole" parameterType="role">
    update t_role set role_name = #{roleName}, note = #{note} where id= #{id} </update> <select id="getRole" parameterType="long" resultType="role">
    select id, role_name as roleName, note from t_role where id = #{id} </select> <select id="findRoles" parameterType="string" resultType="role">
    select id, role_name as roleName, note from t_role where role_name like concat('%', #{roleName}, '%') </select> </mapper>

 


Chapter3Main测试类:
程序入口,拥有main方法

import com.xc.mapper.RoleMapper;
import com.xc.pojo.Role;
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 test {

    public static void main(String[] args) {

        String resource = "mybatis-config.xml";
        try {

            InputStream inputStream = Resources.getResourceAsStream(resource);
            //SqlSessionFactoryBuilder(构造器):它会根据配置或者代码来生成SqlSessionFactory,采用的是分步构建的Builder模式。
            //SqlSessionFactory(工厂接口):依靠它来生成SqlSession,使用的是工厂模式。
            SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

            //SqlSession(会话):一个既可以发送SQL执行返回结果,也可以获取Mapper的接口。在现有的技术中,一般我们会让其在业务逻辑代码中“消失”,而使用的是MyBatis提供的SQL Mapper接口编程技术,它能提高代码的可读性和可维护性。
            SqlSession sqlSession = sqlSessionFactory.openSession();
            //SQL Mapper(映射器):MyBatis新设计存在的组件,它由一个Java接口和XML文件(或注解)构成,需要给出对应的SQL和映射规则。它负责发送SQL去执行,并返回结果。
            RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
            Role role = roleMapper.getRole(1L);
            System.out.println(role.toString());
            Role role2 = roleMapper.getRole2(1L);
            System.out.println(role2.toString());

        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}

 

 

Chapter3Main2测试类:

package com.xc.main;

import com.xc.mapper.RoleMapper;
import com.xc.pojo.Role;
import com.xc.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.SqlSession;
import org.apache.log4j.Logger;

public class Chapter3Main2 {

    // Logger log = Logger.getLogger(Chapter3Main.class);
    private static Logger log = Logger.getLogger(Chapter3Main2.class);

    public static void main(String[] args) {

        SqlSession sqlSession = null;
        try {
            sqlSession = SqlSessionFactoryUtils.openSqlSession();
            //通过SqlSession获取了一个RoleMapper接口对象
            RoleMapper roleMapper = sqlSession.getMapper(RoleMapper.class);
            //通过getRole方法获取对象
            Role role = roleMapper.getRole(1L);
            log.info(role.getRoleName());
        } finally {
            if (sqlSession != null) {
                //正确关闭SqlSession对象
                sqlSession.close();
            }
        }
    }
}

 


SqlSessionFactoryUtils.java:

package com.xc.util;

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

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

/**
 * 使用mybatis-config.xml文件,通过SQLSessionFactory-Builder来构建SqlSessionFactory。由于SqlSessionFactory应该采用单例模式,所以这里使用单例模式去构建它
 */
public class SqlSessionFactoryUtils {

    private final static Class<SqlSessionFactoryUtils> LOCK = SqlSessionFactoryUtils.class;
    private static SqlSessionFactory SqlSessionFactory = null;

    //构造方法中加入了private关键字,使得其他代码不能通过new的方式来创建它。
    private SqlSessionFactoryUtils() {
    }

    public static SqlSessionFactory getSqlSessionFactory() {
        //加入synchronized关键字加锁,主要是为了防止在多线程中多次实例化SqlSessionFactory对象,从而保证SqlSessionFactory的唯一性。
        synchronized (LOCK) {
            if (SqlSessionFactory != null) {
                return SqlSessionFactory;
            }
            String resource = "mybatis-config.xml";
            InputStream inputStream;
            try {
                inputStream = Resources.getResourceAsStream(resource);
                SqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
            } catch (IOException e) {
                e.printStackTrace();
                return null;
            }
            return SqlSessionFactory;
        }
    }

    //openSqlSession方法的作用则是创建SqlSession对象。
    public static SqlSession openSqlSession() {
        if (SqlSessionFactory == null) {
            getSqlSessionFactory();
        }
        return SqlSessionFactory.openSession();
    }
}

 

log4j.properties

通过logj4.properties文件配置,让MyBatis打印了其运行过程的轨迹。我们可以清晰地看到了日志打印出来的SQL、SQL参数,以及返回的结果数,这样有利于监控MyBatis的运行过程和定位问题的所在。

log4j.rootLogger=DEBUG,stdout
log4j.logger.org.mybatis=DEBUG
log4j.appender.stdout=org.apache.log4j.ConsoleAppender 
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout 
log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n

 

附:

pom.xml

<properties>
    <slf4j.version>1.7.12</slf4j.version>
</properties>

<!-- 日志文件管理包 -->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-api</artifactId>
    <version>${slf4j.version}</version>
</dependency>
<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-log4j12</artifactId>
    <version>${slf4j.version}</version>
</dependency>

<!--<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.25</version>
</dependency>-->
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.12</version>
</dependency>
<!-- mybatis -->
<dependency>
    <groupId>org.mybatis</groupId>
    <artifactId>mybatis</artifactId>
    <version>3.4.1</version>
</dependency>