Mybatis从入门到精通(一)

2022-11-29 16:11:41 浏览数 (1)

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录,自由灵活生成(半自动化,大部分需要程序员编写sql)。

Mybatis官方文档:http://www.mybatis.org/mybatis-3/zh/index.html

一、框架原理:

mybatisconfig.xml:(是mybatis的全局配置文件,名称不固定的)配置了数据源、事务等mybatis运行环境 mapper.xml:配置sql语句 SqlSessionFactory:(会话工厂),根据配置文件创建工厂作用:创建SqlSession SqlSession:(会话),是一个接口,面向用户(程序员)的接口作用:操作数据库(发出sql增、删、改、查) Executor:(执行器),是一个接口(基本执行器、缓存执行器)作用:SqlSession内部通过执行器操作数据库 mapped statement:(底层封装对象)作用:对操作数据库存储封装,包括 sql语句,输入参数、输出结果类型。

二、开始使用

1)环境: jdk1.8,mysql5.6,IDEA,必要jar包 若使用maven可使用下面AVG导入(当前选择版本3.4.5):

代码语言:javascript复制
<dependency>
  <groupId>org.mybatis</groupId>
  <artifactId>mybatis</artifactId>
  <version>3.4.5</version>
</dependency>

2)创建必要配置文件: log4j.properties(log4j日志配置文件):

代码语言:javascript复制
#初始化定义日志级别
log4j.rootLogger=DEBUG,Console

#输出到控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.layout=org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
log4j.logger.org.apache=INFO

mybatis-config.xml(mybatis配置文件):

代码语言:javascript复制
<?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>
    <properties resource="jdbc.properties" />
    <settings>
        <!--设置自动驼峰命名转换-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
    <!-- 和spring整合后 environments配置将废除 -->
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${driver}"/>
                <property name="url" value="${url}"/>
                <property name="username" value="${username}"/>
                <property name="password" value="${password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!--加载映射文件-->
        <mapper resource="com/lcry/mybatis/dao/EmployeeMapper.xml"/>
    </mappers>
</configuration>

jdbc.properties(数据库信息配置):

代码语言:javascript复制
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/mybatis?useUnicode=true&characterEncoding=utf-8
username=root
password=123456

Employee.java(实体类):

代码语言:javascript复制
package com.lcry.mybatis.bean;

public class Employee {
    private  Integer id ;
    private  String lastname;  //此处有坑
    private  String email;
    private  String gander;  //此处有坑

    public Integer getid() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getLastname() {
        return lastname;
    }

    public void setLastname(String lastname) {
        this.lastname = lastname;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getGander() {
        return gander;
    }

    public void setGander(String gander) {
        this.gander = gander;
    }

    @Override
    public String toString() {
        return "Employee{"  
                "id="   id  
                ", lastname='"   lastname   '''  
                ", email='"   email   '''  
                ", gander='"   gander   '''  
                '}';
    }
}

EmployeeDao.java(接口):

代码语言:javascript复制
package com.lcry.mybatis.dao;

import com.lcry.mybatis.bean.Employee;

public interface EmployeeDao {
     Employee getEmp(Integer id);
     void  insertemp(Employee employee);
     boolean updateemp(Employee employee);
     Integer deleteemp(Integer id);

}

EmployeeMapper.xml(映射文件配置):

代码语言:javascript复制
<?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">
<!--命名空间,可自定义,若绑定接口,必须和接口名保持一致-->
<!--id为唯一标示-->
<mapper namespace="com.lcry.mybatis.dao.EmployeeDao">
    <select id="getEmp" resultType="com.lcry.mybatis.bean.Employee">
        select * from tbl_employee where id = #{id}
    </select>

    <insert id="insertemp"  useGeneratedKeys="true" keyProperty="id">
        insert into tbl_employee VALUES(null,#{lastname},#{gander},#{email})
    </insert>

    <update id="updateemp">
/*此处解决坑last_name*/
        update tbl_employee set last_name = #{lastname} ,gender=#{gander},email=#{email} where id=#{id}
    </update>
    <delete id="deleteemp">
        DELETE  FROM tbl_employee WHERE id =#{id}
    </delete>
</mapper>

3)开始测试

MyBatisTest.java(测试方法):

代码语言:javascript复制
package com.lcry.mybatis.test;

import com.lcry.mybatis.bean.Employee;
import com.lcry.mybatis.dao.EmployeeDao;
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 org.junit.Test;
import java.io.IOException;
import java.io.InputStream;

public class MyBatisTest {
        //获取配置,创建sqlSessionFactory工厂
    public static SqlSessionFactory getsqlsession() throws IOException {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        return sqlSessionFactory;
    }

    @Test
    public void test01() throws IOException {
        SqlSession sqlSession = getsqlsession().openSession();
        try {
            //查询方法
            Employee employee = sqlSession.selectOne("com.lcry.mybatis.dao.EmployeeDao.getEmp", 10);
            System.out.println(employee);
        } finally {
            sqlSession.close();
        }

    }

    @Test
    public void test02() throws IOException {
        SqlSession sqlSession = getsqlsession().openSession(true);
        try {
            EmployeeDao employee = sqlSession.getMapper(EmployeeDao.class);
            //查询方法
            Employee emp = employee.getEmp(10);
            System.out.println(emp.getid());
            //插入方法
            Employee employee1 = new Employee();
            employee1.setLastname("lcry");
            employee1.setEmail("1@qq.com");
            employee1.setGander("1");
            employee.insertemp(employee1);
            System.out.println(employee1.toString());
            //更新方法
            boolean b = employee.updateemp(employee1);
            System.out.println(b   employee1.toString());
            //删除方法
            Integer rows = employee.deleteemp(13);
            System.out.println(rows);
        } finally {
            sqlSession.close();
        }

    }
}

我的项目结构如下:

补一份数据库sql文件(tbl_employee.sql):

代码语言:javascript复制
SET FOREIGN_KEY_CHECKS=0;

-- ----------------------------
-- Table structure for tbl_employee
-- ----------------------------
DROP TABLE IF EXISTS `tbl_employee`;
CREATE TABLE `tbl_employee` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `last_name` varchar(255) DEFAULT NULL,
  `gender` char(1) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;

-- ----------------------------
-- Records of tbl_employee
-- ----------------------------
INSERT INTO `tbl_employee` VALUES ('10', 'lcry', '1', '1@qq.com');
INSERT INTO `tbl_employee` VALUES ('11', 'lcry', '1', '1@qq.com');
INSERT INTO `tbl_employee` VALUES ('12', 'lcry', '1', '1@qq.com');
INSERT INTO `tbl_employee` VALUES ('14', 'lcry', '1', '1@qq.com');

以上就完成了简单的增删查改,赶紧去试试吧~~

0 人点赞