首页 > 编程 > Java > 正文

获取Java的MyBatis框架项目中的SqlSession的方法

2019-11-26 14:15:50
字体:
来源:转载
供稿:网友

从XML中构建SqlSessionFactory
从XML文件中构建SqlSessionFactory的实例非常简单。这里建议你使用类路径下的资源文件来配置.

String resource = "org/mybatis/example/Configuration.xml";  Reader reader = Resources.getResourceAsReader(resource);  sqlMapper = new SqlSessionFactoryBuilder().build(reader);  

XML配置文件包含对MyBatis系统的核心设置,包含获取数据库连接实例的数据源和决定事务范围和控制的事务管理器。如例:

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

当然,在XML配置文件中还有很多可以配置的,上面的示例指出的则是最关键的部分。

从SqlSessionFactory中获取SqlSession
现在,我们已经知道如何获取SqlSessionFactory对象了,基于同样的启示,我们就可以获得SqlSession的实例了。SqlSession对象完全包含以数据库为背景的所有执行SQL操作的方法。你可以用SqlSession实例来直接执行已映射的SQL 语句。例如:

SqlSession session = sqlMapper.openSession();  try{    Blog blog = (Blog)session.selectOne("org.mybatis.example.BlogMapper.selectBlog",101);  }finally{    session.close();  }  

现在有一种更简洁的方法。使用合理描述参数和SQL语句返回值的接口(比如BlogMapper.class),这样现在就更简单,更安全的代码,没有容易发生的字符串文字和转换的错误。例如:

SqlSession session = sqlSessionFactory.openSession();  try {    BlogMapper mapper = session.getMapper(BlogMapper.class);    Blog blog = mapper.selectBlog(101);  }finally{    session.close();  } 

探究已映射的SQL语句
这里给出一个基于XML映射语句的示例,这些语句应该可以满足上述示例中SqlSession对象的调用。

<?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">    <select id="selectBlog" parameterType="int" resultType="Blog">      select * from Blog where id = #{id}    </select>  </mapper>  

在命名空间“com.mybatis.example.BlogMapper”中,它定义了一个名为“selectBlog”的映射语句,这样它允许你使用完全限定名“org.mybatis.example.BlogMapper.selectBlog”来调用映射语句,我们下面示例中的写法也就是这样的。

Blog blog = (Blog)session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);  

但下面的调用更有优势:
映射接口对应映射xml文件的命令空间,接口方法对应映射xml文件中定义的SQL映射的ID。???????????

BlogMapper mapper = session.getMapper(BlogMapper.class);  Blog blog = mapper.selectBlog(101);  

首先它不是基于文字的,那就更安全了。第二,如果你的IDE有代码补全功能,那么你可以利用它来操纵已映射的SQL语句。第三,不需要强制类型转换,同时BlogMapper接口可以保持简洁,返回值类型很安全(参数类型也很安全)。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表