Mybatis

Posted wu-zang

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Mybatis相关的知识,希望对你有一定的参考价值。

Mybatis

MyBatis 本是apache的一个开源项目iBatis 2010年这个项目由apache software foundation 迁移到了google code,并且改名为MyBatis 。2013年11月迁移到Github。iBATIS一词来源于“internet”和“abatis”的组合,是一个基于Java的持久层框架。iBATIS提供的持久层框架包括SQL Maps和Data Access Objects(DAOs)

MyBatis 是一款优秀的持久层框架,它支持定制化 SQL、存储过程以及高级映射。MyBatis 避免了几乎所有的 JDBC 代码和手动设置参数以及获取结果集。MyBatis 可以使用简单的 XML 或注解来配置和映射原生信息,将接口和 Java 的 POJOs(Plain Old Java Objects,普通的 Java对象)映射成数据库中的记录。

官方地址

简介使用

<!--全局配置文件 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>
<!-- * org/mybatis/example/BlogMapper.xml -->
<?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.dao.BlogMapper">  
<!-- 对应接口全类名位置 ## -->

<!-- 对应接口方法 ### -->
<select id="selectBlog" resultType="org.mybatis.example.bean.Blog">select * from Blog where id = #{id}</select> 

</mapper>
//## org.mybatis.example.dao.BlogMapper
public interface BlogMapper{
    // 对应mapper中方法 ###
    public Blog selectBlog(Integer id);
}

Mybatis底层与数据库交互是使用SqlSession完成的,SqlSession非线程安全,每次使用应当获取新对象,mapper接口的实现由mybatis生成一个代理对象。

public void test(){
  
SqlSessionFactory sqlSessionFactory = getSqlSessionFactory();
SqlSession session = sqlSessionFactory.openSession();
   try {  
           BlogMapper mapper = session.getMapper(BlogMapper.class);  
           Blog blog = mapper.selectBlog(1);  
   } finally {  session.close(); }    
}

全局配置文件

properties标签

<?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>  
  <properties resource="db.properties" url="网络路径/本地路径"></properties>
  <!--resource:类路径   url:网络路径/本地路径 -->
  <environments default="development">    
  <environment id="development">      
    <transactionManager type="JDBC"/>      
    <dataSource type="POOLED">        
      <property name="driver" value="${jdbc.driver}"/>        
      <property name="url" value="${jdbc.url}"/>        
      <property name="username" value="${jdbc.username}"/>        
      <property name="password" value="${jdbc.password}"/>      
    </dataSource>    
  </environment>  
</environments> 
</configuration>
#db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mydql://localhost:3306/db
jdbc.username=username
jdbc.password=password

settings标签

<?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>  
  <settings>
    <setting name="mapUnderscoreToCamelCaseEnables " value="true" />
    <!-- 驼峰命民适配 -->
  </settings>
</configuration>

typeAliases标签

<?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>  
 <typeAliases>
    <typeAlias type="org.mybatis.example.bean.Blog" alias="blog"></typeAlias>
   <!-- mapper中就不用写全类名了,不写alias即默认为类名-->
  <package name="org.mybatis.example.bean"/>
   <!--当前包及其子包自动别名-->
  </typeAliases>
</configuration>
<?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.dao.BlogMapper">  
<!-- blog 别名使用-->
<select id="selectBlog" resultType="blog">select * from Blog where id = #{id}</select> 
</mapper>
//通过@Alias注解使用别名
//批量扫描注解优先
@Alias("blog")
public class Blog{
  private Integer id;
  ...
}
Alias(默认别名) Mapped Type
_long long
_short short
_int int
_integer int
_double double
_float float
_boolean boolean
string String
byte Byte
long Long
short Short
int Integer
integer Integer
double Double
float Float
boolean Boolean
date Date
decimal BigDecimal
bigdecimal BigDecimal
map Map

plugins插件

在四大对象执行前后进行拦截,原理为动态代理。

  • Executor (update, query, flushStatements, commit, rollback, getTransaction, close, isClosed)
  • ParameterHandler (getParameterObject, setParameters)
  • ResultSetHandler (handleResultSets, handleOutputParameters)
  • StatementHandler (prepare, parameterize, batch, update, query)

environments标签

<?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="env">
          <transactionManager type="JDBC"/> <!-- 事务管理器  type: JDBC|MANAGED 自定义 -->
        <dataSource type="POOLED">  <!-- 数据源配置 type:UNPOOLED|POOLED|JNDI 自定义-->
          <property name="driver" value="${oracle.driver}"/>        
          <property name="url" value="${oracle.url}"/>        
          <property name="username" value="${oracle.username}"/>        
          <property name="password" value="${oracle.password}"/>  
        </dataSource>
        </environment>
    
      <environment id="development">      
        <transactionManager type="JDBC"/>      
        <dataSource type="POOLED">        
          <property name="driver" value="${jdbc.driver}"/>        
          <property name="url" value="${jdbc.url}"/>        
          <property name="username" value="${jdbc.username}"/>        
          <property name="password" value="${jdbc.password}"/>      
        </dataSource>    
      </environment>  
    
</environments> 
</configuration>

databaseIdProvider标签

<?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="env">
    <databaseIdProvider type="DB_VENDOR">
    <property name="MySQL" value="mysql"/>
    <property name="Oracle" value="oracle"/>
    <property name="SQL Server" value="sqlserver"/>
  </databaseIdProvider>
</configuration>

<?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.dao.BlogMapper">  
<!-- 发送带oracle的查询语句 -->
<select id="selectBlog" resultType="org.mybatis.example.bean.Blog">
        select * from Blog where id = #{id}</select> 
<select id="selectBlog" resultType="org.mybatis.example.bean.Blog" 
        databsesId="oracle">select * from Blog where id = #{id}</select> 
<select id="selectBlog" resultType="org.mybatis.example.bean.Blog" 
        databsesId="mysql">select * from Blog where id = #{id}</select> 
</mapper>

mapper标签

<!--全局配置文件 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>  
<mappers>    
  <mapper url=""></mapper>
  <!-- 磁盘路径 -->
  <mapper resource="org/mybatis/example/BlogMapper.xml"/>  
  <!-- 类路径 -->
  <mapper class="org.mybatis.example.dao.BlogMapperAnnotation"/>
  <!--1. mapper和接口 同名同路径-->
  <!--2. 添加注解方法的接口-->
  <package name="org.mybatis.example.dao"/>
  <!--  批量扫描 xml 接口 同包 -->
</mappers> 
</configuration>
//org.mybatis.example.dao.BlogMapperAnnotation
public interface BlogMapperAnnotation{
    // 对应mapper中方法 ###
    @Select("select * from Blog where id = #{id}")
    public Blog selectBlog(Integer id);
}

映射文件

CRUD

//## org.mybatis.example.dao.BlogMapper
public interface BlogMapper{
    // 对应mapper中方法 ###
    public Blog selectBlog(Integer id);
    public boolean insertdBlog(Blog blog);
    public Integer updateBlog(Blog blog);
    public boolean deleteBlog(Integer id);
  //自动返回 Integer 、Long、Boolean 类型
}
<!-- * org/mybatis/example/BlogMapper.xml -->
<?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.dao.BlogMapper">  

<select id="selectBlog" resultType="org.mybatis.example.bean.Blog">
            select * from Blog where id = #{id}
  </select> 
  
<insert id="insertdBlog" parameterType ="org.mybatis.example.bean.Blog">
    insert into Blog...values(#{属性名},#{属性名})
</insert>
  
<update id="updateBlog" parameterType ="org.mybatis.example.bean.Blog">
    update Blog set ... 字段 = #{属性名} where 字段 = #{属性名}
  </update>
  
<delete id="deleteBlog">
    delete from Blog where id = #{id}
  </delete>
  
</mapper>

获取自增主键

<!-- * org/mybatis/example/BlogMapper.xml -->
<?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.dao.BlogMapper">  
  
  <!-- mysql 等支持 自增主键 数据库-->
<insert id="insertdBlog" parameterType ="org.mybatis.example.bean.Blog"
        useGeneratedKeys="true" keyProperty="#{id}" databaseId="mysql">
  <!-- 使用自增主键策略 插入数据库操作完成后原插入对象的id属性将被赋值-->
    insert into Blog...values(#{属性名},#{属性名})
</insert>

  <!-- Oracle 从序列中获取 -->
<insert id="insertdBlog" parameterType ="org.mybatis.example.bean.Blog"
        databaseId="oracle">
    <selectKey KeyProperty="#{id}" order="BEFORE" resultTyoe"Integer">
    <!-- 使用查询序列 插入数据库操作完成后原插入对象的id属性将被赋值-->
    select Blog_sql.nextval from dual
  </selectKey>
    insert into Blog...values(#{id},#{属性名},#{属性名})
  </insert>
  
</mapper>

以上是关于Mybatis的主要内容,如果未能解决你的问题,请参考以下文章

SSM-MyBatis-05:Mybatis中别名,sql片段和模糊查询加getMapper

mybatis动态sql片段与分页,排序,传参的使用

MyBatis动态SQL标签用法

MYBATIS05_ifwherechoosewhentrimsetforEach标签sql片段

mybatis动态sql之利用sql标签抽取可重用的sql片段

[mybatis]动态sql_sql_抽取可重用的sql片段