Mybaties入门程序

1.什么是mybaties

  mybaties   是一个持久层框架,也可以称为ORM的一种实现( Object relational mapping),支持普通sql,存储过程和高级映射。

2.入门

  2.1SqlSession实例

     每个Mybaties程序都以一个SqlSession对象的实例为核心。那么什么是SqlSession,他到底有什么用?我在源码的注释里面看到了这么一句话:“The primary Java interface for working with MyBatis.
   , Through this interface you can execute commands, get mappers and manage transactions.(java使用mybaties的主要接口,通过这个接口你可以执行命令,获取映射和管理事务)”。看到这个我觉得这  个sqlsession对象应该是可以满足我们第一个demo的crud了。既然他是一个接口 ,那我们使用的话一定是使用他的实现类,该接口下有两个实现类(DefaultSqlSession和SqlSessionManager).本文我们先  使用DefaultSqlSession。

  2.2 SqlSessionFactoryBuilder  

    这个类的说明很简单 Builds {@link SqlSession} instances(创建SqlSession实例).ok,我们就通过这个类来获取一下sqlsession实例。

我们发现这个类有多个重载的build方法,既然是获取操作数据库的对象,那么连接数据库的四要素肯定是要以某种形式作为build方法的参数传入的,但返回的并不是SqlSession对象,而是一个SqlSessionFactory,那我们在看一下这个SqlSessionFactory是用来做什么的,其实熟悉设计模式的人看到这个方法就知道他是干啥的了。 我们还是跟一下源码吧。

Creates an {@link SqlSession} out of a connection or a DataSource 从连接或者数据源中获取一个sqlsession,ok 我们现在找到了获取sqlsession的方法了,他也提供了许多重载的方法,我们先使用第一个吧。

  2.3 SqlSessionFactoryBuilder中build方法的参数之mabaties主配置文件(demo中命名为mybaties.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="config/jdbc.properties"><!-- 加载jdbc属性文件-->
    </properties>
    <typeAliases>
        <package name="com.easyunion.entity" /><!-- 以包的形式定义别名,别名即为简单类名-->
    </typeAliases>    
    <environments default="mysqlEM">
        <environment id="mysqlEM">
            <!-- <transactionManager type="JDBC">jdbc的事务管理</transactionManager> -->
            <transactionManager type="JDBC"></transactionManager>
            <dataSource type="POOLED">
                <property name="driver" value="${jdbc.driverClass}" />
                <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/easyunion/dao/studentMapper.xml" />
    </mappers>
</configuration>

当然 构建SqlSessionFactory的方式不仅限于xml文件,也可以从JavaConfig中获取,这里我们使用xml。本文的目的是先让第一个mybaties demo跑起来。主配置文件和mapper.xml文件就放在后面的文章中进行详细的解释。因为有太多的细节,我认为单独写一篇文章是有必要的。

3.第一个mybaties Demo

   3.1工程目录

package com.easyunion.entity;
//学生pojo
public class Student {
    private Integer id;
    private String name;
    private Integer age;
    private double score;

    public Student() {

    }

    public Student(String name, Integer age, double score) {
        this.name = name;
        this.age = age;
        this.score = score;
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", age=" + age
                + "score" + score + "]";
    }

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public double getScore() {
        return score;
    }

    public void setScore(double score) {
        this.score = score;
    }

}
package com.easyunion.dao;

import com.easyunion.entity.Student;

public interface IStudentDao {
       //添加学生
    void  insertStudent(Student  student);
    
    
}
StudentMapper.xml

<?
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="student"> <insert id="insertStudent"> INSERT INTO student(name,age,score) values(#{name},#{age},#{score}) </insert> </mapper>

dao接口的实现类

package com.easyunion.dao.impl;

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;

import com.easyunion.dao.IStudentDao;
import com.easyunion.entity.Student;
import com.easyunion.util.SqlSessionUtil;

public class StudentDaoImpl implements IStudentDao {
    SqlSession sqlSession = null;

    @Override
    public void insertStudent(Student student) {

        sqlSession = SqlSessionUtil.getSqlSession("config/mybaties.xml");

        sqlSession.insert("insertStudent", student);

        sqlSession.commit();

        SqlSessionUtil.colseSqlSession(sqlSession);

    }

}

获取sqlsession的工具类

package com.easyunion.util;

import java.io.IOException;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
/**
 * 工具类
 * @author lwh
 *
 */
public class SqlSessionUtil {

    private static SqlSessionFactory factory;

    /**
     * 获取Mybaties的sqlSession对象
     * 
     * @param xmlPath
     *            mybaties主要配置文件的位置
     * @throws IOException
     * 
     */
    public static SqlSession getSqlSession(String xmlPath) {
        SqlSession sqlSession = null;

        try {
            if (factory == null) {
                factory = new SqlSessionFactoryBuilder().build(Resources
                        .getResourceAsStream(xmlPath));
                
            }
            sqlSession = factory.openSession();
            return sqlSession;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sqlSession;
    }

    /**
     * 关闭sqlSession
     * 
     * @param sqlSession
     */
    public static void colseSqlSession(SqlSession sqlSession) {
        if (sqlSession != null) {
            sqlSession.close();

        }

    }

}

jdbc.properties

jdbc.driverClass = com.mysql.jdbc.Driver
jdbc.url =jdbc:mysql://127.0.0.1:3306/test
jdbc.username= root
jdbc.password =123456

 测试类

package com.easyunion.test;



import org.junit.Before;
import org.junit.Test;

import com.easyunion.dao.IStudentDao;
import com.easyunion.dao.impl.StudentDaoImpl;
import com.easyunion.entity.Student;


public class TestCase {

    private IStudentDao stuDao;

    @Before
    public void init() {
        stuDao = new StudentDaoImpl();
    }

    @Test
    public void testInsert() {

        Student st = new Student("mybaties", 7, 90);

        stuDao.insertStudent(st);

    }

    @Test
    public void test() {
        

    }

}

猜你喜欢

转载自www.cnblogs.com/easyunion/p/9035919.html