mybatis:getting started

来源:互联网 发布:skitch是什么软件 编辑:程序博客网 时间:2024/06/11 11:06
Material Design  : google推出

可调用sql、procedure
替代jdbc代码以及手工参数set和结果集的获取
可以使用xml、Annotation作为配置

核心SqlSessionFactory,可由SqlSessionFactoryBuilder构建
可根据xml configuration构建,也可以根据一个Configuration类的实例构建。

Mybatis有一个工具类Resources,用于从classpath或者其他位置加载资源。

String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

mybatis-config.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>
<environments default="development">
      <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                  <property name="driver" value="${driver}"/>
                  <property name="url" value="${url}"/>
                  <property name="username" value="${username}"/>
                  <property name="password" value="${password}"/>
            </dataSource>
      </environment>
</environments>
<mappers>
      <mapper resource="org/mybatis/example/BlogMapper.xml"/>
</mappers>
</configuration>
    
以上代码相当于
DataSource dataSource = BlogDataSourceFactory.getBlogDataSource();
TransactionFactory transactionFactory = new JdbcTransactionFactory();
Environment environment = new Environment("development", transactionFactory, dataSource);
Configuration configuration = new Configuration(environment);
configuration.addMapper(BlogMapper.class);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configuration
BlogMapper是添加的mapper,可以通过annotation来定义,默认还是会去找BlogMapper.xml作为映射配置。
复杂的映射Annotation实现不了。比如Nested Join Mapping

SqlSession,用于执行SQL命令。
之前的版本,直接用session去select
SqlSession session = sqlSessionFactory.openSession();
try{
   Blog blog = session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
}finally{
   session.close();
}
现在更安全的写法,先构造一个mapper,然后用mapper去select
SqlSession session = sqlSessionFactory.openSession();
try{
   BlogMapper mapper = session.getMapper(BlogMapper.class);
   Blog blog = mapper.selectBlog(101); //对应于xml配置文件里面的id
}finally{
   session.close();
}
mapper的示例
<?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="org.mybatis.example.BlogMapper">//对应于session.selectOne("...")
   <select id="selectBlog" parameterType="int" resultType="Blog">
      select * from Blog where id = #{id}
   </select>
</mapper>
如果是全名mybatis可以直接look up到,比如com.mypackage.MyMapper.selectAllThings;
如果是selectAllThings,应该也能lookup到,但是如果存在多个selectAllThings,会报错

使用Annotation进行map
package org.mybatis.example;
public interface BlogMapper{
      @Select("SELECT * FROM blog WHERE id = #{id}")
      Blog selectBlog(int id)
}

生命周期:
  • SqlSessionFactoryBuilder,最好是method scope,创建完了SqlSessionFactory就没用了
  • SqlSessionFactory, 应该在整个生命周期内存在,没必要重新create或者dipose它。可采用Singleton或者Static Singleton实现
  • SqlSession
    • 应当是method或者request scope。
    • SqlSession不是线程安全的,每个线程应该有自己的SqlSession,不同线程不能共享sqlsessin。
    • 绝对不要把sqlsession作为一个类的static甚至普通的成员变量。
    • 不要在一个被管理的生命周期范围内去保持对sqlsession的引用,比如servlet framework的httpsession。
    • 如果使用web框架,可以让SqlSession的范围同httprequest的一致。即,接收一个HTTP Request的时候,打开一个sqlsession,返回一个HTTP Response的时候,返回一个sqlsession。
    • SqlSession是一定需要close的,要放在finally中
      SqlSession session = sqlSessionFacotry.openSession();
      try{
        //do work
      }finally{
        session.close();
      }
  • Mapper
    • mapper是绑定到statement的interface
    • mapper不需要显式的去close。mapper有sqlsession创建,理论上讲他的生命周期和sqlsession是一致的,但最好还是以method为scope。
    • 所以要这么写
SqlSession session = sqlSessionFactory.openSession();
try{
     BlogMapper mapper = session.getMapper(BlogMapper.class); 
      //mapper放在trycatch里面,用完了就算了
}finally{
     session.close();
}

0 0
原创粉丝点击