您现在的位置是:首页 > 后台技术 > MyBatisMyBatis

MyBatis入门(第一章)(图文)

第十三双眼睛2020-03-18【MyBatis】人已围观

简介本章通过一个简单的MyBatis的简单例子让大家对MyBatis有一个初步的了解。

准备数据库
学习MyBatis之前,先准备一个数据库,编码方式为utf-8,可以使用MySql的客户端工具来实现.执行下面语句来创建一个学生表student

CREATE TABLE `student` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增主键',
  `name` varchar(10) DEFAULT NULL COMMENT '姓名',
  `age` tinyint(4) DEFAULT NULL COMMENT '年龄',
  `height` smallint(6) DEFAULT NULL COMMENT '身高',
  `sex` tinyint(4) DEFAULT '1' COMMENT '性别1男0女',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

然后插入几条数据:
INSERT INTO student 
(NAME, age, height, sex)
VALUES ('张三', 20, 180, 1),('李四', 21, 181, 1),('王丽', 18, 175, 0),('张晨', 25, 179, 1);
配置MyBatis
配置MyBatis的方式有很多种,可以通过springbean的方式进行配置,也可以用java编码的方式,最常用的是使用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>
<!-- 
 1、mybatis可以使用properties来引入外部properties配置文件的内容
 resource是引入类路径下的资源
 url:引入网络网络路径或磁盘路径下的资源
 -->
<properties resource="dbconfig.properties"></properties>
<settings>
    <!-- 日志框架 -->
    <setting name="logImpl" value="LOG4J"/>
    <!-- 驼峰命名 -->
    <setting name="mapUnderscoreToCamelCase" value="true" />  
</settings>

<typeAliases>
    <typeAlias type="com.xjava.mybatis.entity.Student"/>
</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>

    <!-- 将我们写好的sql映射文件(EmployeeMapper.xml)一定要注册到全局配置文件(mybatis-config.xml)中 -->
<mappers>
    <mapper resource="com/xjava/mybatis/mapper/StudentMapper.xml"/>
</mappers>
</configuration>
简单讲解一下这个配置内容
<settings> 中的logImpl属性配置指定使用log4j输出日志信息
<typeAliases>元素下配置了一个类,也可以是一个包,通常再确定一个类的时候需要使用类的全限定名,如果频繁使用,这样配置后,就不需要写类的全类名,只要写类名就行,如Student.
<environments>环境配置中主要配置了数据库连接。
创建实体类和mapper文件
mybatis是一种结果映射类框架,这里创建的实体类实际上是一个数据值对象,再实际应用中,一般一个表会对应一个实体,称这个类为实体类。
package com.xjava.mybatis.entity;

import java.io.Serializable;

import lombok.Data;
@Data
public class Student implements Serializable{

    private static final long serialVersionUID = 1385354715743574653L;

    private Integer id;
    private String name;
    private Integer age;
    private Integer height;
    private Integer sex;
}    
<?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.xjava.mybatis.dao.StudentDao">
    
<select id="getStudent" resultType="Student">
    SELECT * FROM student
</select>    
    
</mapper>
<mapper>:xml的根元素,属性namespace定义了当前xml的命名空间
<select>元素,我们所定义的一个查询
id属性:定义了当前查询的一个唯一id
resultType:定义了当前查询的返回值类型,如果没有开启驼峰命名,需要使用resultMap
编写测试代码
package com.xjava.mybatis.test;
import java.io.Reader;
import java.util.List;
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.BeforeClass;
import org.junit.Test;
import com.xjava.mybatis.dao.StudentDao;
import com.xjava.mybatis.entity.Student;

public class StudentTest {
    
    private static SqlSessionFactory factory;
    
    
    static{
        try{
            Reader reader = Resources.getResourceAsReader("mybatis-config.xml");
            factory = new SqlSessionFactoryBuilder().build(reader);
            reader.close();
        }catch(Exception e){
            e.printStackTrace();
        }
    }
    
    public static void main(String arg[]){
        SqlSession sqlSession = factory.openSession();
        try{
            StudentDao studentDao = sqlSession.getMapper(StudentDao.class);
            List<Student> students = studentDao.getStudent();
            for(Student student:students){
                System.out.println(student.getId()+"-"+student.getName()+"-"+student.getAge());
            }
        
        
        }catch(Exception e){
            e.printStackTrace();
        }
    }  
}
对上面的代码做个简单的说明
通过Resources工具类将mybatis-config.xml配置文件读入readder.
再通过SqlSessionFactoryBuilder建造类使用reader创建SqlSessionFactory,再创建SqlSessionFactory的过程中,首先解析mybatis-config.xml配置文件,读取配置文件中的mappers后会读取全部的mapper.xml进行解析,再解析完成后,SqlSessionFactory就包含了所有的属性配置和执行SQL的信息
使用时,通过SqlSessionFactory获取一个连接。
使用完毕后,记得一定要关闭连接。
输出结果:

通过一系列的操作,我们让一个简单的mybatis例子跑了起来。


    
    

Tags:MyBatis   持久层

很赞哦! ()

文章评论

    共有条评论来说两句吧...

    用户名:

    验证码:

本站推荐

站点信息

  • 网站名称:JavaStudy
  • 建站时间:2019-1-14
  • 网站程序:帝国CMS7.5
  • 文章统计242篇文章
  • 标签管理标签云
  • 统计数据百度统计
  • 微信公众号:扫描二维码,关注我们