


The previous article "Mybatis series in simple terms (7)---mapper mapping file configuration insert, update, delete" introduced the usage of insert, update, and delete. This article will introduce the usage of select and resultMap. Select is undoubtedly our most commonly used and most complex one. Mybatis can help us perform advanced mapping well through resultMap. Let’s start looking at the options And the usage of resultMap:
Let’s look at the configuration of select first:
<select> id="selectPerson" <!-- 2. parameterType (可选配置, 默认为mybatis自动选择处理) 将要传入语句的参数的完全限定类名或别名, 如果不配置,mybatis会通过ParameterHandler 根据参数类型默认选择合适的typeHandler进行处理 parameterType 主要指定参数类型,可以是int, short, long, string等类型,也可以是复杂类型(如对象) --> parameterType="int" <!-- 3. resultType (resultType 与 resultMap 二选一配置) resultType用以指定返回类型,指定的类型可以是基本类型,可以是java容器,也可以是javabean --> resultType="hashmap" <!-- 4. resultMap (resultType 与 resultMap 二选一配置) resultMap用于引用我们通过 resultMap标签定义的映射类型,这也是mybatis组件高级复杂映射的关键 --> resultMap="personResultMap" <!-- 5. flushCache (可选配置) 将其设置为 true,任何时候只要语句被调用,都会导致本地缓存和二级缓存都会被清空,默认值:false --> flushCache="false" <!-- 6. useCache (可选配置) 将其设置为 true,将会导致本条语句的结果被二级缓存,默认值:对 select 元素为 true --> useCache="true" <!-- 7. timeout (可选配置) 这个设置是在抛出异常之前,驱动程序等待数据库返回请求结果的秒数。默认值为 unset(依赖驱动)--> timeout="10000" <!-- 8. fetchSize (可选配置) 这是尝试影响驱动程序每次批量返回的结果行数和这个设置值相等。默认值为 unset(依赖驱动)--> fetchSize="256" <!-- 9. statementType (可选配置) STATEMENT,PREPARED 或 CALLABLE 的一个。这会让 MyBatis 分别使用 Statement,PreparedStatement 或 CallableStatement,默认值:PREPARED--> statementType="PREPARED" <!-- 10. resultSetType (可选配置) FORWARD_ONLY,SCROLL_SENSITIVE 或 SCROLL_INSENSITIVE 中的一个,默认值为 unset (依赖驱动)--> resultSetType="FORWARD_ONLY"></select>
There always seem to be so many configurations, but the actual commonly used configurations There are only a few, depending on your own needs. It has been noted above whether they must be configured.
Let’s practice using the previous demo in time:
--------------------------- --------------------------------------------------The following is a practice for select demo------------------------------------------------- -----------------------------------------------
Database: Two new files are added Table (t_course, t_student)
t_course:
t_student:
Among them, 1 Students can choose multiple courses to study.
Let’s take the demo from the previous article and continue writing:
After adding, the project directory will look like this:
Course.java:
package com.dy.entity;public class Course { private int id; private String name; private int deleteFlag; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getDeleteFlag() { return deleteFlag; } public void setDeleteFlag(int deleteFlag) { this.deleteFlag = deleteFlag; } }
Student.java:
package com.dy.entity; import java.util.List;public class Student { private int id; private String idCard; private String name; private List<course> courseList; private int deleteFlag; public Student(int id, String idCard, String name, List<course> courseList, int deleteFlag) { this.id = id; this.idCard = idCard; this.name = name; this.courseList = courseList; this.deleteFlag = deleteFlag; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getIdCard() { return idCard; } public void setIdCard(String idCard) { this.idCard = idCard; } public String getName() { return name; } public void setName(String name) { this.name = name; } public List<course> getCourseList() { return courseList; } public void setCourseList(List<course> courseList) { this.courseList = courseList; } public int getDeleteFlag() { return deleteFlag; } public void setDeleteFlag(int deleteFlag) { this.deleteFlag = deleteFlag; } }</course></course></course></course>
CourseDao.java:
package com.dy.dao;import com.dy.entity.Course;public interface CourseDao { public Course findCourseById(int courseId); }
StudentDao.java:
package com.dy.dao;import com.dy.entity.Student;public interface StudentDao { public Student findStudentById(String idCard); }
courseDao.xml:
<mapper> <!-- 1.此处直接将resultType 设置为course, 一看就知道我设置了别名吧,如果没有设置别名,那么resultType = com.dy.entity.Course。 2.可能细心的你会发现:Course.java中的属性名与数据库字段名不一致,下面,我就在sql语句中用了as, 使之匹配,当然方法不止一种, 在学习了resultMap之后,你能看到一种更直观优雅的方式去将javabean中的属性与数据库字段名保持一致 3.findCourseById 与CourseDao中findCourseById方法对应, 那么传入的参数名称以及类型也应该保持对应关系。 4.可以看到,在sql语句中,通过#{}表达式可以获取参数。 5.下面这条sql语句,实际上的形式是怎么样的?还记得之前说过,mybatis默认为preparedStatement吧,那么,用我们jdbc代码来看,它其实就是: select course_id as id, course_name as name, course_delete_flg as deleteFlag from t_course where course_id=? --> <select> select course_id as id, course_name as name, course_delete_flg as deleteFlag from t_course where course_id=#{courseId} </select> </mapper>
CourseDaoTest.java:
package com.dy.dao; import java.io.IOException;import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Test; import com.dy.entity.Course;public class CourseDaoTest { @Test public void findCourseById() { SqlSessionFactory sqlSessionFactory = getSessionFactory(); SqlSession sqlSession = sqlSessionFactory.openSession(); CourseDao courseDao = sqlSession.getMapper(CourseDao.class); Course course = courseDao.findCourseById(1); } //Mybatis 通过SqlSessionFactory获取SqlSession, 然后才能通过SqlSession与数据库进行交互 private static SqlSessionFactory getSessionFactory() { SqlSessionFactory sessionFactory = null; String resource = "mybatis-conf.xml"; try { sessionFactory = new SqlSessionFactoryBuilder().build(Resources .getResourceAsReader(resource)); } catch (IOException e) { e.printStackTrace(); } return sessionFactory; } }
In the above example, we briefly demonstrated the use of select for course, but there is a question worth thinking about: A student can correspond to multiple courses, so how to deal with this pair in mybatis What about many, or even many-to-many, one-to-one relationships?
Here, we have to mention resultMap. The resultMap function of mybatis is very powerful and can handle complex relationship mapping. So how to configure resultMap? Don’t worry, here it comes:
resultMap的配置:
<!-- 1.type 对应类型,可以是javabean, 也可以是其它 2.id 必须唯一, 用于标示这个resultMap的唯一性,在使用resultMap的时候,就是通过id指定 --> <resultmap> <!-- id, 唯一性,注意啦,这个id用于标示这个javabean对象的唯一性, 不一定会是数据库的主键(不要把它理解为数据库对应表的主键) property属性对应javabean的属性名,column对应数据库表的列名 (这样,当javabean的属性与数据库对应表的列名不一致的时候,就能通过指定这个保持正常映射了) --> <id></id> <!-- result与id相比, 对应普通属性 --> <result></result> <!-- constructor对应javabean中的构造方法 --> <constructor> <!-- idArg 对应构造方法中的id参数 --> <idarg></idarg> <!-- arg 对应构造方法中的普通参数 --> <arg></arg> </constructor> <!-- collection,对应javabean中容器类型, 是实现一对多的关键 property 为javabean中容器对应字段名 column 为体现在数据库中列名 ofType 就是指定javabean中容器指定的类型 --> <collection></collection> <!-- association 为关联关系,是实现N对一的关键。 property 为javabean中容器对应字段名 column 为体现在数据库中列名 javaType 指定关联的类型 --> <association></association> </resultmap>
好啦,知道resutMap怎么配置后,咱们立即接着上面的demo来练习一下吧:
------------------------------------------------------------------下面是用resultMap处理一对多关系的映射的示例-------------------------------------------------------------
一个student对应多个course, 典型的一对多,咱们就来看看mybatis怎么配置这种映射吧:
studentDao.xml:
<mapper> <!-- 这儿定义一个resultMap --> <resultmap> <!-- 数据库中主键是id, 但是我这儿却是指定idCard为主键,为什么? 刚刚讲了,id用来表示唯一性, 我们可以认为只要idCard一样,那么他就是同一个学生。 如果此处用数据库中id, 那么mybatis将会认为数据库中每条记录都是一个student, 这显然不符合逻辑 --> <id></id> <result></result> <result></result> <result></result> <!-- 这儿就是实现一对多的关键。 在Student中,courseList为List<Course>, 因此,ofType也应该与之对应(当然,我用了别名,不然要蛋疼的写全名了)。 collection的子标签是在指定Course的映射关系(由于Course的javabean的属性名与数据库的列名不一致) --> <collection> <id></id> <result></result> <result></result> </collection> </resultmap> <!-- 这儿将返回类型设置成了上面指定的studentMap --> <select> SELECT s.*, c.* FROM t_student s LEFT JOIN t_course c ON s.stu_course_id=c.course_id WHERE s.stu_id_card=#{idCard} </select> </mapper>
StudentDaoTest.java:
package com.dy.dao;import java.io.IOException; import java.util.List; import org.apache.ibatis.io.Resources; import org.apache.ibatis.session.SqlSession; import org.apache.ibatis.session.SqlSessionFactory; import org.apache.ibatis.session.SqlSessionFactoryBuilder;import org.junit.Test; import com.dy.entity.Course;import com.dy.entity.Student;public class StudentDaoTest { @Test public void findCourseById() { SqlSessionFactory sqlSessionFactory = getSessionFactory(); SqlSession sqlSession = sqlSessionFactory.openSession(); StudentDao studentDao = sqlSession.getMapper(StudentDao.class); Student student = studentDao.findStudentById("20140101"); List<course> courseList = student.getCourseList(); for (Course course: courseList) { System.out.println(course.getId() + " " + course.getName()); } } //Mybatis 通过SqlSessionFactory获取SqlSession, 然后才能通过SqlSession与数据库进行交互 private static SqlSessionFactory getSessionFactory() { SqlSessionFactory sessionFactory = null; String resource = "mybatis-conf.xml"; try { sessionFactory = new SqlSessionFactoryBuilder().build(Resources .getResourceAsReader(resource)); } catch (IOException e) { e.printStackTrace(); } return sessionFactory; } }</course>
相信通过以上demo, 大家也能够使用mybatis的select 和 resultMap的用法了。上面demo只演示了一对多的映射,其实多对一、多对多也与它类似,所以我就没演示了,有兴趣的可以自己动手再做做。
好啦,本次就写到这儿了。(PS,生病一周了,所以到现在才更新博客)。
以上就是深入浅出Mybatis系列(八)---mapper映射文件配置之select、resultMap 的内容,更多相关内容请关注PHP中文网(www.php.cn)!

缓存的概述和分类概述缓存就是一块内存空间.保存临时数据为什么使用缓存将数据源(数据库或者文件)中的数据读取出来存放到缓存中,再次获取的时候,直接从缓存中获取,可以减少和数据库交互的次数,这样可以提升程序的性能!缓存的适用情况适用于缓存的:经常查询但不经常修改的(eg:省市,类别数据),数据的正确与否对最终结果影响不大的不适用缓存的:经常改变的数据,敏感数据(例如:股市的牌价,银行的汇率,银行卡里面的钱)等等MyBatis缓存类别一级缓存:它是sqlSession对象的缓存,自带的(不需要配置)不

MyBatis允许使用插件来拦截的方法Executor(update,query,flushStatements,commit,rollback,getTransaction,close,isClosed)ParameterHandler(getParameterObject,setParameters)ResultSetHandler(handleResultSets,handleOutputParameters)StatementHandler(prepare,parameterize,ba

mybatis分页的方式:1、借助数组进行分页,首先查询出全部数据,然后再list中截取需要的部分。2、借助Sql语句进行分页,在sql语句后面添加limit分页语句即可。3、利用拦截器分页,通过拦截器给sql语句末尾加上limit语句来分页查询。4、利用RowBounds实现分页,需要一次获取所有符合条件的数据,然后在内存中对大数据进行操作即可实现分页效果。

简介今天开发时想将自己写好的代码拿来优化,因为不想在开发服弄,怕搞坏了到时候GIT到生产服一大堆问题,然后把它分离到我轮子(工具)项目上,最后运行后发现我获取List的时候很卡至少10秒,我惊了平时也就我的正常版本是800ms左右(不要看它很久,因为数据量很大,也很正常。),前提是我也知道很慢,就等的确需要优化时,我在放出我优化的plus版本,回到10秒哪里,最开始我刚刚接到这个app项目时,在我用PageHelper.startPage(page,num);(分页),还没等查到的数据封装(Pa

当某些sql因为不知名原因堵塞时,为了不影响后台服务运行,想要给sql增加执行时间限制,超时后就抛异常,保证后台线程不会因为sql堵塞而堵塞。一、yml全局配置单数据源可以,多数据源时会失效二、java配置类配置成功抛出超时异常。importcom.alibaba.druid.pool.DruidDataSource;importcom.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;importorg.apache.

mybatis调用mysql存储过程并获取返回值1、mysql创建存储过程#结束符号默认;,delimiter$$语句表示结束符号变更为$$delimiter$$CREATEPROCEDURE`demo`(INinStrVARCHAR(100),outourStrVARCHAR(4000))BEGINSETourStr='01';if(inStr=='02')thensetourStr='02';en

SpringBoot打印mybatis的执行sql1、使用场景应为在开发过程之中跟踪后端SQL语句,因什么原因导致的错误。需要在Debug过程之中打印出执行的SQL语句。所以需要配置一下SpringBoot之中,Mybatis打印SQL语句。2、具体实现application.properties(yml)中配置的两种方式:1.logging.level.dao包名(daopackage)=debug2.mybatis.configuration.log-impl=org.apache.ibat

一、什么是缓存缓存是内存当中一块存储数据的区域,目的是提高查询效率。MyBatis会将查询结果存储在缓存当中,当下次执行相同的SQL时不访问数据库,而是直接从缓存中获取结果,从而减少服务器的压力。什么是缓存?存在于内存中的一块数据。缓存有什么作用?减少程序和数据库的交互,提高查询效率,降低服务器和数据库的压力。什么样的数据使用缓存?经常查询但不常改变的,改变后对结果影响不大的数据。MyBatis缓存分为哪几类?一级缓存和二级缓存如何判断两次Sql是相同的?查询的Sql语句相同传递的参数值相同对结


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

Notepad++7.3.1
Easy-to-use and free code editor

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.