MyBatis初学

来源:互联网 发布:京津冀生态环境数据 编辑:程序博客网 时间:2024/05/22 04:52
MyBatis简介
MyBatis 是一个简化和实现了 Java 数据持久化层(persistence layer)的开源框架,它抽象了大量的 JDBC 冗余代码,并提供了一个简单易用的 API 和数据库交互。
MyBatis 的前身是 iBATIS,iBATIS 于 2002 年由 Clinton Begin 创建。MyBatis 3 是 iBATIS 的全新设计,支持注解和 Mapper。
MyBatis 流行的主要原因在于它的简单性和易使用性。在 Java 应用程序中,数据持久化层涉及到的工作有:将从数据库查询到的数据生成所需要的 Java 对象;将 Java 对象中的数据通过 SQL 持久化到数据库中。 MyBatis 通过抽象底层的 JDBC 代码,自动化 SQL 结果集产生 Java 对象、Java 对象的数据持久化数据库中的过程使得对 SQL 的使用变得容易。
MyBatis优势
● 它消除了大量的 JDBC 冗余代码
● 它有低的学习曲线
● 它能很好地与传统数据库协同工作
● 它可以接受 SQL 语句
● 它提供了与 Spring 和 Guice 框架的集成支持
● 它提供了与第三方缓存类库的集成支持
● 它引入了更好的性能
开始使用
要使用 MyBatis, 只需将 mybatis-x.x.x.jar 文件置于 classpath 中即可。
如果使用 Maven 来构建项目,则需将下面的 dependency 代码置于 pom.xml 文件中:
<dependency>  <groupId>org.mybatis</groupId>  <artifactId>mybatis</artifactId>  <version>x.x.x</version></dependency>
本节利用Mysql数据库(通过以下步骤)说明如何使用 MyBatis 开发一个简单的 Java 项目:
1. 新建表 students,插入样本数据 
2. 新建一个 Java 项目,将 MyBatis依赖添加到 pom.xml中 
3. 新建MyBatisSqlSessionFactory 类构建 SqlSessionFactory
4. 新建映射器 StudentMapper 接口和 StudentService 类 
5. 新建一个 JUnit 测试类来测试 StudentService 
新建表 STUDENTS,插入样本数据
使用图形界面或sql语句创建表并添加数据,我创建的表如下:

新建一个 Java 项目
如果你没有使用类似于 Maven 和 Gradle 之类的依赖管理构建工具,你需要手动下载这些依赖的 JAR 包,手动添加到 classpath 中。
你可以从http://code.google.com/p/mybatis
下载 MyBatis 的发布包 mybatis-3.4.5.zip。 它包含了 mybatis-3.4.5.jar 文件和可选的依赖包如 slf4j/log4j 日志 jar 包.
我们将使用 slf4j 日志记录框架和log4j 一起记录日志。
你可以从http://junit.org 上下载JUnit JAR文件,
https://dev.mysql.com/downloads/connector/j/下载 MySQL 数据库驱动,现在我的pom.xml文件如下:
<?xml version="1.0" encoding="UTF-8"?><project xmlns="http://maven.apache.org/POM/4.0.0"         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelVersion>4.0.0</modelVersion>    <groupId>MyBatisDemo</groupId>    <artifactId>MyBatisDemo</artifactId>    <version>1.0-SNAPSHOT</version>    <properties>        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>        <java.version>1.8</java.version>        <junit.version>4.11</junit.version>        <slf4j.version>1.7.21</slf4j.version>        <log4j.version>1.2.17</log4j.version>        <mybatis.version>3.4.5</mybatis.version>        <mysql.version>6.0.6</mysql.version>        <maven.compiler.plugin>3.3</maven.compiler.plugin>    </properties>    <dependencies>        <dependency>            <groupId>org.mybatis</groupId>            <artifactId>mybatis</artifactId>            <version>${mybatis.version}</version>        </dependency>        <dependency>            <groupId>mysql</groupId>            <artifactId>mysql-connector-java</artifactId>            <version>${mysql.version}</version>            <scope>runtime</scope>        </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>            <scope>runtime</scope>        </dependency>        <dependency>            <groupId>log4j</groupId>            <artifactId>log4j</artifactId>            <version>${log4j.version}</version>            <scope>runtime</scope>        </dependency>        <dependency>            <groupId>junit</groupId>            <artifactId>junit</artifactId>            <version>${junit.version}</version>            <scope>test</scope>        </dependency>    </dependencies></project>
现在创建一个JavaBean——Student.java
public class Student {     private Integer studId;     private String name;     private String email;     private Date dob;     // setters and getters } 
接下来创建 MyBatis 的主要配置文件 mybatis-config.xml,其中包括数据库连接信息,类型别名等等;然后再创建一个包含了映射的 SQL 语句的 xml 文件。
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>    <properties resource="application.properties"/>    <typeAliases>        <package name="com.neucloud.domain"/>    </typeAliases>    <environments default="development">        <environment id="development">            <transactionManager type="JDBC"/>            <dataSource type="POOLED">                <property name="driver" value="${jdbc.driverClassName}"/>                <property name="url" value="${jdbc.url}"/>                <property name="username" value="${jdbc.username}"/>                <property name="password" value="${jdbc.password}"/>            </dataSource>        </environment>    </environments>    <mappers>        <mapper resource="com/neucloud/mappers/StudentMapper.xml"/>    </mappers></configuration>
创建 SQL 映射器 XML 配置文件,假定为 StudentMapper.xml。 并且将它放在 com.neucloud.mappers 包中 ,内容如下:
<mapper namespace="com.neucloud.mappers.StudentMapper">      <resultMap type="Student" id="StudentResult">      <id    property="studId" column="stud_id"/>      <result property="name" column="name"/>      <result property="email" column="email"/>      <result property="dob" column="dob"/>   </resultMap>     <select id="findAllStudents" resultMap="StudentResult">       select * from Students   </select>      <select id="findStudentById" parameterType="int" resultType="Student">       select stud_id as studId, name, email, dob from Students where stud_id=#{studId}   </select>      <insert id="insertStudent" parameterType="Student">      INSERT INTO STUDENTS(STUD_ID,NAME,EMAIL,DOB) VALUES(#{studId},#{name},#{email},#{dob})   </insert>      <update id="updateStudent" parameterType="Student">      UPDATE STUDENTS SET NAME=#{name}, EMAIL=#{email}, DOB=#{dob} WHERE STUD_ID=#{studId}   </update>   </mapper>
创建一个 StudentMapper 接口
其定义的方法名和在 Mapper XML 配置文件定义的 SQL 映射语句名称相同
public interface StudentMapper{   List<Student> findAllStudents();   Student findStudentById(Integer id);   void insertStudent(Student student);   void updateStudent(Student student);}
新建MyBatisSqlSessionFactory 类构建 SqlSessionFactory
MyBatis 最关键的组成部分是 SqlSessionFactory,我们可以从中获取 SqlSession,并执行映射的 SQL 语句。SqlSessionFactory 对象可以通过基于 XML 的配置信息或者 Java API 创建
public class MyBatisSqlSessionFactory {    private static SqlSessionFactory sqlSessionFactory;    private static final Properties properties = new Properties();    static {        try {            InputStream is = DataSourceFactory.class.getResourceAsStream("/mysql.properties");            properties.load(is);        } catch (IOException e) {            e.printStackTrace();        }    }    private static SqlSessionFactory getSqlSessionFactory() {        if (sqlSessionFactory == null) {            InputStream inputStream = null;            try {                inputStream = Resources.getResourceAsStream("mybatis-config.xml");                sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);            } catch (IOException e) {                throw new RuntimeException(e.getCause());            } finally {                if (inputStream != null) {                    try {                        inputStream.close();                    } catch (IOException e) {                    }                }            }        }        return sqlSessionFactory;    }    public static SqlSession getSqlSession() {        return getSqlSessionFactory().openSession();    }}
再创建一个 StudentService.java 类
它实现对表 STUDENTS 的数据库操作
public class StudentService {    private Logger logger = LoggerFactory.getLogger(getClass());    public List<Student> findAllStudents() {        SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();        try {            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);            return studentMapper.findAllStudents();        } finally {            sqlSession.close();        }    }    public Student findStudentById(Integer studId) {        logger.debug("Select Student By ID :{}", studId);        SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();        try {            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);//       return studentMapper.findStudentById(studId);            //也可以不通过 Mapper 接口执行映射的 SQL 语句            return sqlSession.selectOne("com.neucloud.mappers.StudentMapper.findStudentById", studId);        } finally {            sqlSession.close();        }    }    public void createStudent(Student student) {        SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();        try {            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);            studentMapper.insertStudent(student);            sqlSession.commit();        } finally {            sqlSession.close();        }    }    public void updateStudent(Student student) {        SqlSession sqlSession = MyBatisSqlSessionFactory.getSqlSession();        try {            StudentMapper studentMapper = sqlSession.getMapper(StudentMapper.class);            studentMapper.updateStudent(student);            sqlSession.commit();        } finally {            sqlSession.close();        }    }}
现在写一个类测试一下吧
public class Test {    public static void main(String[] args) {        StudentService studentService=new StudentService();        Student student=studentService.findStudentById(1);        System.out.println(student.getEmail());    }}
就是这样,我们的程序完成了,而如果我们使用jdbc这样才操作方式,上述代码会有很多重复的代码:创建一个连接,创建一个 Statement 对象,设置输入参数,关闭资源(如connection,statement,resultSet) 。
MyBatis 抽象了上述的这些相同的任务,如准备需要被执行的 SQL statement 对象并且将 Java 对象作为输入数据传递给 statement 对象的任务,进而开发人员可以专注于真正重要的方面。
另外,MyBatis 还提供了其他的一些特性来简化持久化逻辑的实现:
● 它支持复杂的 SQL 结果集数据映射到嵌套对象图结构
● 它支持一对一和一对多的结果集和 Java 对象的映射
● 它支持根据输入的数据构建动态的 SQL 语句

MyBatis的工作原理
首先,我们配置了 MyBatis 最主要的配置文件mybatis-config.xml,里面包含了 JDBC 连接参数;配置了映射器Mapper XML 配置文件文件,里面包含了 SQL 语句的映射。
我们使用 mybatis-config.xml 内的信息创建了 SqlSessionFactory 对象。每个数据库环境应该只有一个SqlSessionFactory 对象实例,所以我们使用了单例模式只创建一个 SqlSessionFactory 实例。
我们创建了一个映射器 Mapper 接口-StudentMapper,其定义的方法签名和在 StudentMapper.xml 中定义的完全一样(即映射器 Mapper 接口中的方法名跟 StudentMapper.xml 中的 id 的值相同) 。注意 StudentMapper.xml 中namespace 的值被设置成 com.neucloud.mappers.StudentMapper,是 StudentMapper 接口的完全限定名。这使我们可以使用接口来调用映射的 SQL 语句。

在 StudentService.java 中,我们在每一个方法中创建了一个新的 SqlSession,并在方法功能完成后关闭SqlSession。每一个线程应该有它自己的 SqlSession 实例。SqlSession 对象实例不是线程安全的,并且不被共享。所以 SqlSession 的作用域最好就是其所在方法的作用域。从 Web 应用程序角度上看,SqlSession 应该存在于 request 级别作用域上。


参考:

http://www.mybatis.org/mybatis-3/zh/getting-started.html

原创粉丝点击