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();
}
}
}
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持億速云。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。