美文网首页
Mybatis简单的案例(1)2018-08-16

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

作者: Seetheworl_6675 | 来源:发表于2018-08-16 22:42 被阅读0次

    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

    相关文章

      网友评论

          本文标题:Mybatis简单的案例(1)2018-08-16

          本文链接:https://www.haomeiwen.com/subject/yfhgbftx.html