Mybatis快速入门(一)

一、传统jdbc开发

1)优点:简单易学,上手快,非常灵活构建SQL,效率高。
2)缺点:代码繁琐,难以写出高质量的代码(例如:资源的释放,SQL注入安全性等)开发者既要写业务逻辑,又要写对象的创建和销毁,必须管底层具体数据库的语法(例如:分页)。
3)适合于超大批量数据的操作,速度快。

二、hibernate单表开发

1)优点:不用写SQL,完全以面向对象的方式设计和访问,不用管底层具体数据库的语法,(例如:分页)便于理解。
2)缺点:处理复杂业务时,灵活度差, 复杂的HQL难写难理解,例如多表查询的HQL语句。
3)适合于中小批量数据的操作,速度慢。

三、什么是mybatis,mybatis有什么特点?

1)基于上述二种支持,我们需要在中间找到一个平衡点呢?结合它们的优点,摒弃它们的缺点,
这就是myBatis,现今myBatis被广泛的企业所采用。
2)MyBatis 本是apache的一个开源项目iBatis, 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。
3)iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAO)。
4)jdbc/dbutils/springdao,hibernate/springorm,mybaits同属于ORM解决方案之一。

四、mybatis快速入门

1)创建一个mybatis这么一个java web工程或java工程
2)导入mybatis和mysql/oracle的jar包到/WEB-INF/lib目录下
mybatis包
3)创建students.sql表

--mysql语法
create table students(
   id  int(5) primary key,
   name varchar(10),
   sal double(8,2)
);
--oracle语法
create table students(
   id  number(5) primary key,
   name varchar2(10),
   sal number(8,2)
);

4)创建Student.java

/**
 * 学生
 */
public class Student {
    private Integer id;
    private String name;
    private Double sal;
    public Student(){}
    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 Double getSal() {
        return sal;
    }
    public void setSal(Double sal) {
        this.sal = sal;
    }
}

5)在entity目录下创建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="mynamespace">
    <insert id="add1">
        insert into students(id,name,sal) values(1,'eric',7000)
    </insert>
    <insert id="add2" parameterType="mybatis.app.Student">
        insert into students(id,name,sal) values(#{id},#{name},#{sal})
    </insert>
</mapper>

6)在src目录下创建mybatis.xml配置文件

"><!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="com.mysql.jdbc.Driver"/> 
                <property name="url" value="jdbc:mysql://127.0.0.1:3306/mybatis"/>  
                <property name="username" value="root"/>    
                <property name="password" value="root"/>    
            </dataSource>
        </environment>  
    </environments>
    <mappers>
        <mapper resource="mybatis/app/StudentMapper.xml"/>
    </mappers>
</configuration>

7)在util目录下创建MyBatisUtil.java类,并测试与数据库是否能连接

/**
 * MyBatis工具类
 */
public class MyBatisUtil {
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    private static SqlSessionFactory sqlSessionFactory;
    static{
        try {
            Reader reader = Resources.getResourceAsReader("mybatis.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    private MyBatisUtil(){}
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession == null){
            sqlSession = sqlSessionFactory.openSession();
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }
    public static void closeSqlSession(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession != null){
            sqlSession.close();
            threadLocal.remove();
        }
    }
    public static void main(String[] args) {
        Connection conn = MyBatisUtil.getSqlSession().getConnection();
        System.out.println(conn!=null?"连接成功":"连接失败");
    }
}

8)在dao目录下创建StudentDao.java类并测试

/**
 * 持久层
 */
public class StudentDao {
    /**
     * 增加学生(无参)
     */
    public void add1() throws Exception{
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try{
            sqlSession.insert("mynamespace.add1");
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            sqlSession.commit();
        }
        MyBatisUtil.closeSqlSession();
    }
    /**
     * 增加学生(有参)
     */
    public void add2(Student student) throws Exception{
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try{
            sqlSession.insert("mynamespace.add2",student);
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            sqlSession.commit();
        }
        MyBatisUtil.closeSqlSession();
    }
    public static void main(String[] args) throws Exception{
        StudentDao dao = new StudentDao();
        dao.add1();
        dao.add2(new Student(2,"Jack",8000));
    }
}

五、mybatis工作流程

1)通过Reader对象读取src目录下的mybatis.xml配置文件(该文本的位置和名字可任意)。
2)通过SqlSessionFactoryBuilder对象创建SqlSessionFactory对象。
3)从当前线程中获取SqlSession对象。
4)事务开始,在mybatis中默认。
5)通过SqlSession对象读取StudentMapper.xml映射文件中的操作编号,从而读取sql语句。
6)事务提交,必写。
7)关闭SqlSession对象,并且分开当前线程与SqlSession对象,让GC尽早回收。

六、MybatisUtil工具类的作用

1)在静态初始化块中加载mybatis配置文件和StudentMapper.xml文件一次。
2)使用ThreadLocal对象让当前线程与SqlSession对象绑定在一起。
3)获取当前线程中的SqlSession对象,如果没有的话,从SqlSessionFactory对象中获取SqlSession对象。
4)获取当前线程中的SqlSession对象,再将其关闭,释放其占用的资源。

/**
 * MyBatis工具类
 */
public class MyBatisUtil {
    private static ThreadLocal<SqlSession> threadLocal = new ThreadLocal<SqlSession>();
    private static SqlSessionFactory sqlSessionFactory;
    static{
        try {
            Reader reader = Resources.getResourceAsReader("mybatis.xml");
            sqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }
    private MyBatisUtil(){}
    public static SqlSession getSqlSession(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession == null){
            sqlSession = sqlSessionFactory.openSession();
            threadLocal.set(sqlSession);
        }
        return sqlSession;
    }
    public static void closeSqlSession(){
        SqlSession sqlSession = threadLocal.get();
        if(sqlSession != null){
            sqlSession.close();
            threadLocal.remove();
        }
    }
    public static void main(String[] args) {
        Connection conn = MyBatisUtil.getSqlSession().getConnection();
        System.out.println(conn!=null?"连接成功":"连接失败");
    }
}

七、基于MybatisUtil工具类,完成CURD操作

1)StudentDao.java

/**
 * 持久层
 */
public class StudentDao {
    /**
     * 增加学生
     */
    public void add(Student student) throws Exception{
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try{
            sqlSession.insert("mynamespace.add",student);
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            sqlSession.commit();
            MyBatisUtil.closeSqlSession();
        }
    }
    /**
     * 修改学生
     */
    public void update(Student student) throws Exception{
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try{
            sqlSession.update("mynamespace.update",student);
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            sqlSession.commit();
            MyBatisUtil.closeSqlSession();
        }
    }
    /**
     * 查询单个学生
     */
    public Student findById(int id) throws Exception{
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try{
            Student student = sqlSession.selectOne("mynamespace.findById",id);
            return student;
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            sqlSession.commit();
            MyBatisUtil.closeSqlSession();
        }
    }
    /**
     * 查询多个学生
     */
    public List<Student> findAll() throws Exception{
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try{
            return sqlSession.selectList("mynamespace.findAll");
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            sqlSession.commit();
            MyBatisUtil.closeSqlSession();
        }
    }
    /**
     * 删除学生
     */
    public void delete(Student student) throws Exception{
        SqlSession sqlSession = MyBatisUtil.getSqlSession();
        try{
            sqlSession.delete("mynamespace.delete",student);
        }catch(Exception e){
            e.printStackTrace();
            sqlSession.rollback();
            throw e;
        }finally{
            sqlSession.commit();
            MyBatisUtil.closeSqlSession();
        }
    }

2)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="mynamespace">
    <insert id="add" parameterType="mybatis.app.Student">
        insert into students(id,name,sal) values(#{id},#{name},#{sal})
    </insert>
    <update id="update" parameterType="mybatis.app.Student">
        update students set name=#{name},sal=#{sal} where id=#{id}
    </update>
    <select id="findById" parameterType="int" resultType="mybatis.app.Student">
        select id,name,sal from students where id=#{anything}
    </select>
    <select id="findAll" resultType="mybatis.app.Student">
        select id,name,sal from students
    </select>
    <delete id="delete" parameterType="mybatis.app.Student">
        delete from students where id=#{id}
    </delete>
</mapper>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值