前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >Mybatis的基本使用方法

Mybatis的基本使用方法

作者头像
林老师带你学编程
发布2019-05-26 00:07:08
5760
发布2019-05-26 00:07:08
举报
文章被收录于专栏:强仔仔

1.导入mybatis的jar包:mybatis-x.x.x.jar

2.使用XML配置mybatis,创建SqlSessionFactory

  XML配置文件的名称通常为mybatis-config.xml,内容基本格式如下:

代码语言:javascript
复制
<?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="oracle.jdbc.driver.OracleDriver"/>
        <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"/>
        <property name="username" value="username"/>
        <property name="password" value="password"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="org/mybatis/example/BlogMapper.xml"/>
    <!-- <package name="com.example.manager.mapper"/> -->
  </mappers>
</configuration>

  该配置文件使用文件流的形式读入,通过mybatis的工具类Resources加载资源文件:

代码语言:javascript
复制
String resource = "org/mybatis/example/mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);

3.从 SqlSessionFactory 中获取 SqlSession

代码语言:javascript
复制
SqlSession session = sqlSessionFactory.openSession();
try {
  Blog blog = (Blog) session.selectOne("org.mybatis.example.BlogMapper.selectBlog", 101);
} finally {
  session.close();
}

4.最简单的使用方法:mybatis-config.xml + mapper.xml + test.java

mybatis-config.xml配置

代码语言:javascript
复制
<mapper resource="org/mybatis/example/BlogMapper.xml"/>

resource的路径通常为包路径,众多mapper.xml通常被放置在一个包下

------------------------------------

mapper.xml

代码语言:javascript
复制
<?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" resultType="Map">
    select * from Blog where id = #{id}
  </select>
</mapper>
代码语言:javascript
复制
namespace:命名空间,映射查询的关键参数
id:调用方法定义
resultType:结果集对象类型(Map可以被HashMap接收,然后转为json,也可以自定义类型)
传递参数:参数替换分两种:#{id} => 预处理语句的? || '${id}' => 直接替换为变量
-----------------------------------
test.java
代码语言:javascript
复制
public static void main(String[] args) {
    SqlSessionFactory sqlSessionFactory;
    SqlSession session = null;
    try {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        session = sqlSessionFactory.openSession();
        HashMap<String,String> result = session.selectOne("selectBlog", 110);
        System.out.println("Result: "+result);
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if(session != null){
            session.close();
        }
    }
}

session.selectOne是session自带方法(selectList可以获取多条数据),传入的第一个字符串就是之前定义的id,第二个参数是传入的参数(多个参数可以使用一个HashMap来传参)。

5.简单抽象方法:mybatis-config.xml + mapper.xml + interface.java + test.java

mybatis-config.xml

代码语言:javascript
复制
<package name="com.mybatis.manager.mapper"/>

mapper.xml

代码语言:javascript
复制
<mapper namespace="com.mybatis.manager.mapper.ReleaseDTOMapper">
  <select id="getReleaseNote" parameterType="map" resultType="map">
    SELECT rn.* FROM GPCM_RELEASE_NOTE rn where rn.state = #{STATE} and rn.upgrade_id = #{UPGRADE_ID}
  </select>
  <select id="getUpgradeNote" parameterType="map" resultType="map">
    SELECT un.* FROM GPCM_UPGRADE_NOTE un
  </select>
</mapper>

interface.java

代码语言:javascript
复制
public interface ReleaseDTOMapper {    
    public HashMap<String,String> getReleaseNote(HashMap<String,String> param);
    
    public ArrayList<HashMap<String,String>> getUpgradeNote();
}

test.java

代码语言:javascript
复制
public static void main(String[] args) {
    SqlSessionFactory sqlSessionFactory;
    SqlSession session = null;
    try {
        String resource = "mybatis-config.xml";
        InputStream inputStream = Resources.getResourceAsStream(resource);
        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        session = sqlSessionFactory.openSession();
        ReleaseDTOMapper mapper = session.getMapper(ReleaseDTOMapper.class);
        
        HashMap<String,String> param = new HashMap<String,String>();
        param.put("STATE", "N");
        param.put("UPGRADE_ID","2");
        HashMap<String,String> result = mapper.getReleaseNote(param);
        System.out.println("Result: "+result);
        List<HashMap<String,String>> rs = mapper.getUpgradeNote();
        for(HashMap<String,String> r : rs){
            System.out.println("Result: "+r);
        }            
    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {
        if(session != null){
            session.close();
        }
    }
}

6.通用方法:使用自定义数据类型映射参数和结果集

mapper.xml

代码语言:javascript
复制
<?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="com.mybatis.manager.mapper.ReleaseDTOMapper">
  <resultMap id="BaseResultMap" type="com.mybatis.manager.persist.ReleaseNoteDTO" >
    <result column="RELEASE_ID" property="releaseId" jdbcType="INTEGER" />
    <result column="RELEASE_NAME" property="releaseName" jdbcType="VARCHAR" />
    <result column="RELEASE_DESC" property="releaseDesc" jdbcType="VARCHAR" />
    <result column="UPGRADE_ID" property="upgradeId" jdbcType="INTEGER" />
    <result column="STATE" property="state" jdbcType="VARCHAR" />
    <result column="CREATE_DATE" property="createDate" jdbcType="TIMESTAMP" />
    <result column="MOD_DATE" property="modDate" jdbcType="TIMESTAMP" />
    <result column="UPGRADE_DATE" property="upgradeDate" jdbcType="TIMESTAMP" />
    </resultMap>
  <select id="getReleaseNote" parameterType="com.mybatis.manager.persist.ReleaseNoteDTO" resultMap="BaseResultMap">
    SELECT rn.* FROM GPCM_RELEASE_NOTE rn where rn.state = #{state,jdbcType=VARCHAR} and rn.upgrade_id = #{upgradeId,jdbcType=INTEGER}
  </select>
</mapper>

  注意resultType -> resultMap,列与java对象的参数必需要对应,否则获取的结果就是null。

  传入的参数为一个是可以定义parameterType="java.lang.Integer",多个参数必需合为一个对象传输,如Map或自定义Dto。

  可以使用多表查询,将结果集传入一个自定义Dto中,结果集绑定如下:

<resultMap id = "Upgrade" type="com.mybatis.manager.persist.UpgradeNoteDto"> <result column="UPGRADE_ID" property="upgradeId" jdbcType="INTEGER" /> <result column="UPGRADE_NAME" property="upgradeName" jdbcType="VARCHAR" /> </resultMap> <resultMap id="BaseResultMap" type="com.mybatis.manager.persist.ReleaseNoteDto" > <result column="RELEASE_ID" property="releaseId" jdbcType="INTEGER" /> <result column="RELEASE_NAME" property="releaseName" jdbcType="VARCHAR" /> <result column="RELEASE_DESC" property="releaseDesc" jdbcType="VARCHAR" /> <association property = "upgrade" javaType="com.mybatis.manager.persist.UpgradeNoteDto" resultMap = "Upgrade"/> </resultMap> property = "upgrade"在Dto中定义为 private UpgradeNoteDto upgrade;

ReleaseNoteDTO.java 自定义数据模型

代码语言:javascript
复制
public class ReleaseNoteDTO {
    private Integer releaseId;
    private String releaseName;
    private String releaseDesc;
    private Integer upgradeId;
    private String state;
    private Date createDate;
    private Date modDate;
    private Date upgradeDate;
    /*******************
    *GETTER/SETTER
    *******************/
}

interface.java

代码语言:javascript
复制
public interface ReleaseNoteDtoMapper {    
    public ReleaseNoteDto getReleaseNote(ReleaseNoteDto param);    
}

test.java

代码语言:javascript
复制
ReleaseNoteDTO param = new ReleaseNoteDTO();
param.setState("N");
param.setUpgradeId(2);
ReleaseNoteDTO result = mapper.getReleaseNote(param);
System.out.println("Result: "+result.getReleaseDesc());

7.基本应用的结构参考

附录:相关参考资料

  官网中文教程 http://www.mybatis.org/mybatis-3/zh/getting-started.html

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2018年05月15日,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档