本文主要是介绍MyBatis篇】四. MyBatis高级第三章 注解开发(共三章),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
MyBatis高级第三章 注解开发
github源码(day56-mybatis-senior) https://github.com/1196557363/ideaMavenProject
【MyBatis篇】四. MyBatis高级第一章 #{}和${}符号的区别
【MyBatis篇】四. MyBatis高级第二章 缓存
项目准备
- 因为在同一个module中所以大环境不用改,参考第一章的项目准备
- 将接口com.wpj.dao.IUserDao2 改为 com.wpj.dao3.IUserDao2 已示区分知识点
- 注解开发可以不用mapper映射文件
- MyBatis的mapper映射记得加。
1. Select
1.1 MyBatis.xml
<mappers><mapper resource="mapper/IUserDao2.xml"/><mapper resource="mapper2/IUserDao2.xml"/><!--如果是注解开发这里要写接口--><mapper class="com.wpj.dao3.IUserDao2" />
</mappers>
1.2 IUserDao2接口
package com.wpj.dao3;import com.wpj.bean.*;
import org.apache.ibatis.annotations.*;/*** ClassName: IUserDao2* Description:** @author JieKaMi* @version 1.0* @date: 2020\1\7 0007 19:02* @since JDK 1.8*/
public interface IUserDao2 {@Select(value="select * from user where id = #{id}")User getUserById(Integer id);
}
1.3 test
import com.wpj.bean.*;import com.wpj.dao3.*;
import org.apache.ibatis.io.*;
import org.apache.ibatis.session.*;
import org.junit.*;import java.io.*;/*** ClassName: MyBatisTest* Description:** @author JieKaMi* @version 1.0* @date: 2020\1\7 0007 19:19* @since JDK 1.8*/
public class MyBatisTest3 {@Testpublic void testGetUserById(){String config = "MyBatis.xml";InputStream is = null;try {is = Resources.getResourceAsStream(config);SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);SqlSession sqlSession = sqlSessionFactory.openSession();IUserDao2 userDao = sqlSession.getMapper(IUserDao2.class);User user = userDao.getUserById(1);System.out.println(user);sqlSession.close();} catch (IOException e) {e.printStackTrace();} finally {if(is!=null) {try {is.close();} catch (IOException e) {e.printStackTrace();}}}}
}
2 Results
@Results(value={@Result(id =true, property="id", column="id"),@Result(property="name", column="name"),@Result(property="pwd", column="pwd"),@Result(property="age", column="age")})
@Select(value="select * from user where id = #{id}")
User getUserById(Integer id);
3 ResultMap复用
@Results(id="userResults",value={@Result(id =true, property="id", column="id"),@Result(property="name", column="name"),@Result(property="pwd", column="pwd"),@Result(property="age", column="age")})
@Select(value="select * from user where id = #{id}")
User getUserById(Integer id);@ResultMap("userResults")
User getUserById2(Integer id);
这篇关于MyBatis篇】四. MyBatis高级第三章 注解开发(共三章)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!