[Mybaties入门程序]

[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实例。

img

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

img

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"?>

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

3.第一个mybaties Demo

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"?> INSERT INTO student(name,age,score) values(#{name},#{age},#{score})

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();

      }

    }

}

database.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull
username=root
password=root

测试类

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() {
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值