Mybatis简单的案例(1)2018-08-16

mybatis的基本构成

1、SqlSessionFactoryBuilder(构造器):根据配置信息或代码来生成SqlSessionFactory
2、SqlSessionFactory:依靠工厂来生成SqlSession(会话)
3、SqlSession:发送SQL去执行并返回结果,也可以获取mapper的接口(Executor 才是真正执行sql)。
4、 Mapper:它是由一个Java接口和XML文件(注解)构成的,需要给出对应的SQL和映射规则。它负责发送sql去执行,并返回结果。

mybatis的基本构成的生命周期:

1、SqlSessionFactoryBuilder:在方法内部有效,只用于生成SqlSessionFactory
2、SqlSessionFactory:用于生成SqlSession(会话)整个mybatis应用生命周期(单例)
3、SqlSession:相当于一个Connection,一个请求数据库的
4、Mapper:是一个接口,发送sql返回需要的值,最大生命跟SqlSession范围一样大。

一个最简单的mybatis:

准备实体:

import java.util.Date;

public class Account {
    private Long id;

    private String creator;

    private Date createTime;

    private Date updateTime;

    private String username;

    private String password;

    private String phone;

    public Long getId() {
        return id;
    }

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

    public String getCreator() {
        return creator;
    }

    public void setCreator(String creator) {
        this.creator = creator == null ? null : creator.trim();
    }

    public Date getCreateTime() {
        return createTime;
    }

    public void setCreateTime(Date createTime) {
        this.createTime = createTime;
    }

    public Date getUpdateTime() {
        return updateTime;
    }

    public void setUpdateTime(Date updateTime) {
        this.updateTime = updateTime;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username == null ? null : username.trim();
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password == null ? null : password.trim();
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone == null ? null : phone.trim();
    }


    @Override
    public String toString() {
        return "Account{" +
                "id=" + id +
                ", creator='" + creator + '\'' +
                ", createTime=" + createTime +
                ", updateTime=" + updateTime +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", phone='" + phone + '\'' +
                '}';
    }
}

准备映射器

import com.example.study.mybatis.dao.entity.Account;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

@Mapper
public interface AccountMapper {
    @Select("select * from changjiang_account where id = #{id}")
    Account selectByPrimaryKey(Long id);


}

测试代码:

import com.example.study.mybatis.dao.entity.Account;
import com.example.study.mybatis.dao.mapper.AccountMapper;
import org.apache.ibatis.datasource.pooled.PooledDataSource;
import org.apache.ibatis.mapping.Environment;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.apache.ibatis.transaction.TransactionFactory;
import org.apache.ibatis.transaction.jdbc.JdbcTransactionFactory;

public class MybatisTest {
    public static void main(String[] args){
        SqlSession sqlSession = null;
        try {
            sqlSession = getSqlSessionFactory().openSession();
            AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
            Account account = mapper.selectByPrimaryKey(1L);

            System.out.println(account);

        }catch (Exception e){
            System.out.println("执行失败");
        }finally {
            if (sqlSession != null){
                sqlSession.close();
            }
        }

    }

    private static SqlSessionFactory getSqlSessionFactory() {
        //创建线程池
        PooledDataSource dataSource = new PooledDataSource();
        dataSource.setDriver("com.mysql.jdbc.Driver");
        dataSource.setUrl("jdbc:mysql://xx.xxx.xxx:3306/stream?characterEncoding=utf8");
        dataSource.setUsername("xxx");
        dataSource.setPassword("xxx");
        //构建数据库事物
        TransactionFactory transactionFactory = new JdbcTransactionFactory();
        //构建数据库✅环境
        Environment evironment = new Environment("default",transactionFactory,dataSource);
        //构建Configuration对象
        Configuration configuration = new Configuration(evironment);
        //注册一个别名
        configuration.getTypeAliasRegistry().registerAlias("account", Account.class);
        //添加映射器
        configuration.addMapper(AccountMapper.class);
        /**
         * 以上是Mybatis配置信息的处理过程正常开发中主要通过xml配置的
         * 以下是创建sqlSessionFactory
         */
        SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration);
        return sqlSessionFactory;
    }
}

从上面的代码我们mybatis主要构件的执行流程:


mybatis.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 1. 简介 1.1 什么是 MyBatis ? MyBatis 是支持定制化 SQL、存储过程以及高级映射的优秀的...
    笨鸟慢飞阅读 5,680评论 0 4
  • 在中国式的教育体制之下,我相信有很多的中国家长给孩子规划的人生道路一定都是:亲子班→幼儿园→义务教育(小学、初中)...
    青岛校草丨聪花阅读 272评论 0 0
  • 在很多人看来,大海里的资源不外乎有点鱼,有点咸水。其实,这个现象只是说明了人们对大海的了解,仅仅局限于眼睛看到的,...
    星星_aafb阅读 322评论 0 0
  • 你就在我的眼前摔倒, 可能真的不疼, 但我怎么能原谅自己, 当初没在这里多种一些草!
    简村小吹阅读 200评论 3 4