Java API
既然你已经知道如何配置 MyBatis 和创建映射文件,你就已经准备好来提升技能了。 MyBatis 的 Java API 就是你收获你所做的努力的地方。正如你即将看到的,和 JDBC 相比, MyBatis 很大程度简化了你的代码而且保持简洁,很容易理解和维护。MyBatis 3 已经引入 了很多重要的改进来使得 SQL 映射更加优秀。
MyBatis 3构建在基于全面且强大的Java配置API上。该配置API是基于XML的MyBatis配置的基础,也是新的基于注解配置的基础。
注解提供了一种简单的方式来实现简单映射语句,而不会引入大量的开销。
Mybatis常用注解对应的目标和标签如表所示:
| 注解 | 目标 | 对应的XML标签 | 
| @CacheNamespace | 类 | <cache> | 
| @CacheNamespaceRef | 类 | <cacheRef> | 
| @Results | 方法 | <resultMap> | 
| @Result | 方法 | 				 <result> <id> | 		
| @One | 方法 | <association> | 
| @Many | 方法 | <collection> | 
| 				 @Insert @Update @Delete | 			方法 | 				 <insert> <update> <delete> | 		
| 				 @InsertProvider @UpdateProvider @DeleteProvider @SelectProvider | 			方法 | 				 <insert> <update> <delete> <select> 允许创建动态SQL | 		
| @Param | 参数 | N/A | 
| @Options | 方法 | 映射语句的属性 | 
| @select | 方法 | <select> | 
Mybatis常用注解的含义:
@CacheNamespace(size = 512):定义在该命名空间内允许使用内置缓存
@Options(useCache = true, flushCache = false, timeout = 10000):一些查询的选项开关
@Param("id"):全局限定别名,定义查询参数在sql语句中的位置不再是顺序下标0,1,2,3......的形式,而是对应名称,该名称在此处定义。
@Results是以@Result为元素的数组,@Result表示单条属性——字段的映射关系,id = true表示该id字段是主键,查询时mybatis会给予必要的优化。数组中所有的@Result组成了单个记录的映射关系,而@Results则是单个记录的集合。另外,还有一个非常重要的注解@ResultMap,其与@Results类似
@Select("查询语句")、@Insert("增加语句")、@Update("更新语句")和@Delete("删除语句")表示对数据进行查询、添加、更新和删除的操作。
接下来,咱们来看一下注解的使用。
(1) 常规注解使用(不需要自定义map的操作):
示例1
//添加作者@Insert("Insertinto Author(username,password,email,address,phone) " +"values(#{username},#{password},#{email},#{address},#{phone})")@Options(useGeneratedKeys=true,keyProperty="authId",flushCache= false, timeout = 10000)public voidaddAuthor(Author author);  //删除作者@Delete("deletefrom author where id = #{id}")@Options(flushCache= false, timeout = 10000)public voiddeleteAuthor(@Param("id") int id);提示: 调用方法前需要注册映射器:
sessionFactory.getConfiguration().addMapper(TestInteger.class);
或者在mapper.xml中配置<mapper class="映射器接口路径"></mapper>
注册之后再获取mapper接口正常调用
(2)有需要自定义map的情况可以使用Results注解:
示例2
//查询所有作者信息@Select("select * from author")@Options(flushCache = false, timeout = 10000,useCache=true)@Results( value = {  @Result(id=true,column="id",property="id"),  @Result(property="username",column="username"),  @Result(property="password",column="password"),  @Result(property="email",column="email"),   @Result(property="address",column="address"),  @Result(property="phone",column="phone") })public List<Author> findAuthors();//查询某作者信息@Select("select * from author where id =#{id}")@Options(flushCache = false, timeout =10000,useCache=true)@Results( value = {@Result(id=true,column="id",property="id"),   @Result(property="username",column="username"),   @Result(property="password",column="password"),  @Result(property="email",column="email"),@Result(property="address",column="address"),  @Result(property="phone",column="phone")  })public Author findAuthorById(@Param("id") intid);如果多个查询返回的结果集结构都一样,可以使用@ResultMap定义返回结构,使用该注解,你将不得不在你的映射文件中配置你的resultMap,而@ResultMap(value = "名")即为映射文件中的resultMap ID,如此一来,你需要在<mapper>中注册你的配置文件,在接口中使用@ResultMap来引用配置文件中的resultMap ID如下:
示例3
SelfMapper.xml
//每行记录是一个hashmap<resultMaptype="java.util.HashMap" id="selfMap"> <resultproperty="n" column="city_name" /> ...............</resultMap>
SelfMapper.java:
@Select("select a.id,b.name,c.state from...........")@ResultMap(value="selfMap")public List<HashMap> sel();//注意,返回的是List集合完整案例
接口代码
package com.obtk.dao; import java.util.HashMap; import java.util.List; import org.apache.ibatis.annotations.Insert; import org.apache.ibatis.annotations.Options; import org.apache.ibatis.annotations.Result; import org.apache.ibatis.annotations.Results; import org.apache.ibatis.annotations.Select; import com.obtk.entitys.StudentEntity; public interface IStudentDao {  @Insert("insert into Student(stuName,gender,age,address,deptIdd)"+    "values(#{stuName},#{gender},#{age},#{address},#{deptIdd})")  @Options(useGeneratedKeys=true,keyProperty="stuId")  int saveOne(StudentEntity stu);    @Select("select * from Student where stuId=#{stuId}")  @Results(   //只要配置和列名不一致的属性   value={    @Result(column="gender",property="sex")   }  )  StudentEntity queryById(Integer stuId);    @Select("select * from Student where gender=#{qqq} and address=#{area}")  @Results(   //只要配置和列名不一致的属性   value={    @Result(column="gender",property="sex")   }  )  List<StudentEntity> queryByMany(HashMap theMap);    //万能关联注解配置  @Select("select * from student s inner join department d"    +" on s.deptIdd=d.deptId"    +" where s.gender=#{sex}"    +" and d.departName=#{deptName}")  List<HashMap> queryByQnn(HashMap theMap);   } 案例1 查询一个对象
package com.obtk.test; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.obtk.dao.IStudentDao; import com.obtk.entitys.StudentEntity; import com.obtk.utils.MybatisUtil; public class AnnoSelectOne {  public static void main(String[] args) {   SqlSession session=null;   SqlSessionFactory factory=null;   try {    session=MybatisUtil.getSession();    factory=MybatisUtil.getFactory();    //把接口里面的sql配置和核心配置文件进行关联    factory.getConfiguration().addMapper(IStudentDao.class);    IStudentDao stuDao=session.getMapper(IStudentDao.class);    StudentEntity stu=stuDao.queryById(129);    System.out.println(stu.getStuName()+","+stu.getSex()      +","+stu.getAddress()+","+stu.getStuId());   } catch (Exception e) {    e.printStackTrace();   }finally{    MybatisUtil.closeSession();   }  } } 案例2 传递多个参数,查询多个对象
package com.obtk.test; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.obtk.dao.IStudentDao; import com.obtk.entitys.StudentEntity; import com.obtk.utils.MybatisUtil; public class AnnoSelectMany {  public static void main(String[] args) {   SqlSession session=null;   SqlSessionFactory factory=null;   try {    session=MybatisUtil.getSession();    factory=MybatisUtil.getFactory();    //把接口里面的sql配置和核心配置文件进行关联    factory.getConfiguration().addMapper(IStudentDao.class);    IStudentDao stuDao=session.getMapper(IStudentDao.class);    HashMap paramMap=new HashMap();    paramMap.put("qqq", "男");    paramMap.put("area", "学生宿舍");    List<StudentEntity> stuList=stuDao.queryByMany(paramMap);    for(StudentEntity stu :stuList){     System.out.println(stu.getStuName()+","+stu.getSex()       +","+stu.getAddress()+","+stu.getStuId());    }   } catch (Exception e) {    e.printStackTrace();   }finally{    MybatisUtil.closeSession();   }  } } 案例3 添加对象
package com.obtk.test; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.obtk.dao.IStudentDao; import com.obtk.entitys.StudentEntity; import com.obtk.utils.MybatisUtil; public class AnnoSaveTest {  public static void main(String[] args) {   SqlSession session=null;   SqlSessionFactory factory=null;   try {    session=MybatisUtil.getSession();    factory=MybatisUtil.getFactory();    //把接口里面的sql配置和核心配置文件进行关联    factory.getConfiguration().addMapper(IStudentDao.class);    IStudentDao stuDao=session.getMapper(IStudentDao.class);    StudentEntity stu=new StudentEntity("testC#",      "男", 21, "冥王星");    stu.setDeptIdd(10);    int result=stuDao.saveOne(stu);    session.commit();    System.out.println("保存成功:"+stu.getStuId());   } catch (Exception e) {    e.printStackTrace();   }finally{    MybatisUtil.closeSession();   }  } } 案例4 利用hashmap进行关联查询
package com.obtk.test; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import com.obtk.dao.IStudentDao; import com.obtk.entitys.StudentEntity; import com.obtk.utils.MybatisUtil;  public class AnnoJoinQnn {  public static void main(String[] args) {   SqlSession session=null;   SqlSessionFactory factory=null;   try {    //4.得到session    session=MybatisUtil.getSession();    factory=MybatisUtil.getFactory();    //把接口里面的sql配置和核心配置文件进行关联    factory.getConfiguration().addMapper(IStudentDao.class);    IStudentDao stuDao=session.getMapper(IStudentDao.class);    HashMap paramMap=new HashMap();    paramMap.put("sex", "男");    paramMap.put("deptName", "计算机系");    //5.执行语句    List<HashMap> stuList=stuDao.queryByQnn(paramMap);    for(HashMap theObj : stuList){     System.out.println(theObj.get("stuId")+","+theObj.get("gender")       +","+theObj.get("stuName")+","+theObj.get("departName"));    }   } catch (Exception e) {    e.printStackTrace();   }finally{    MybatisUtil.closeSession();   }  } } 以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持VeVb武林网。
新闻热点
疑难解答
图片精选