Java API
Now that you know how to configure MyBatis and create mapping files, you are ready to improve your skills. MyBatis' Java API is where you reap the efforts you have made. As you'll see, compared to JDBC, MyBatis greatly simplifies your code and keeps it simple, easy to understand and maintain. MyBatis 3 has introduced many important improvements to make SQL mapping better.
MyBatis 3 is built on a comprehensive and powerful Java configuration API. This configuration API is the basis of XML-based MyBatis configuration and is also the basis of new annotation-based configuration.
Annotations provide a simple way to implement simple mapping statements without introducing a lot of overhead.
The corresponding targets and labels of Mybatis common annotations are shown in the table:
| annotation | Target | Corresponding XML tags |
| @CacheNamespace | kind | <cache> |
| @CacheNamespaceRef | kind | <cacheRef> |
| @Results | method | <resultMap> |
| @Result | method | <result> <id> |
| @One | method | <association> |
| @Many | method | <collection> |
@Insert @Update @Delete | method | <insert> <update> <delete> |
@InsertProvider @UpdateProvider @DeleteProvider @SelectProvider | method | <insert> <update> <delete> <select> Allows the creation of dynamic SQL |
| @Param | parameter | N/A |
| @Options | method | Properties of mapping statements |
| @select | method | <select> |
The meaning of common annotations of Mybatis:
@CacheNamespace(size = 512): Defines the use of built-in caches within this namespace
@Options(useCache = true, flushCache = false, timeout = 10000): Option switch for some queries
@Param("id"): Globally qualified alias, the position of the query parameters in the sql statement is no longer in the form of 0, 1, 2, 3..., sequential subscripts, but the corresponding name, which is defined here.
@Results is an array with @Result as the element. @Result represents the mapping relationship of a single attribute-field. id = true means that the id field is the primary key. Mybatis will give necessary optimizations during query. All @Results in the array form a mapping relationship of a single record, while @Results is a collection of a single record. In addition, there is a very important annotation @ResultMap, which is similar to @Results
@Select("query statement"), @Insert("add statement"), @Update("update statement") and @Delete("delete statement") represent operations to query, add, update and delete data.
Next, let’s take a look at the use of annotations.
(1) Use of regular annotations (no custom map operations required):
Example 1
//Add author @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 author @Delete("deletefrom author where id = #{id}")@Options(flushCache= false, timeout = 10000)public voiddeleteAuthor(@Param("id") int id); Tip: You need to register a mapper before calling the method:
sessionFactory.getConfiguration().addMapper(TestInteger.class);
Or configure <mapper></mapper> in mapper.xml
After registering, get the mapper interface to call normally
(2) If you need to customize the map, you can use the Results annotation:
Example 2
//Query all author information @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();//Query the information of a certain author @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); If the result set structure returned by multiple queries is the same, you can use @ResultMap to define the return structure. Using this annotation, you will have to configure your resultMap in your mapping file. @ResultMap(value = "name") is the resultMap ID in the mapping file. In this way, you need to register your configuration file in <mapper> and use @ResultMap in the interface to reference the resultMap ID in the configuration file as follows:
Example 3
SelfMapper.xml
//Each line of record is a 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();//Note that the returned List collection Complete case
Interface code
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.Results; 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},#{deptId})") @Options(useGeneratedKeys=true,keyProperty="stuId") int saveOne(StudentEntity stu); @Select("select * from Student where stuId=#{stuId}") @Results( //As long as the property value that is inconsistent with the column name is configured, value={ @Result(column="gender",property="sex") } ) StudentEntity queryById(Integer stuId); @Select("select * from Student where gender=#{qqq} and address=#{area}") @Results( //As long as the configuration property value={ @Result(column="gender",property="sex") } ) List<StudentEntity> queryByMany(HashMap theMap); //Universal association annotation configuration @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); } Case 1 Query an object
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(); //Associate the sql configuration in the interface with the core configuration file 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(); } } } Case 2 Pass multiple parameters and query multiple objects
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(); //Associate the sql configuration in the interface with the core configuration file factory.getConfiguration().addMapper(IStudentDao.class); IStudentDao stuDao=session.getMapper(IStudentDao.class); HashMap paramMap=new HashMap(); paramMap.put("qqq", "male"); paramMap.put("area", "student dormitory"); 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(); } } } Case 3 Add an object
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(); //Related the sql configuration in the interface with the core configuration file factory.getConfiguration().addMapper(IStudentDao.class); IStudentDao stuDao=session.getMapper(IStudentDao.class); StudentEntity stu=new StudentEntity("testC#", "Male", 21, "Pluto"); stu.setDeptIdd(10); int result=stuDao.saveOne(stu); session.commit(); System.out.println("Save successfully:"+stu.getStuId()); } catch (Exception e) { e.printStackTrace(); } finally{ MybatisUtil.closeSession(); } } }Case 4 Use hashmap for association query
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. Get session session=MybatisUtil.getSession(); factory=MybatisUtil.getFactory(); //Associate the sql configuration in the interface with the core configuration file factory.getConfiguration().addMapper(IStudentDao.class); IStudentDao stuDao=session.getMapper(IStudentDao.class); HashMap paramMap=new HashMap(); paramMap.put("sex", "male"); paramMap.put("deptName", "Computer System"); //5. Execute statement 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(); } } }The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.