小编给大家分享一下Mybatis的基础知识点,相信大部分人都还不怎么了解,因此分享这篇文章给大家参考一下,希望大家阅读完这篇文章后大有收获,下面让我们一起去了解一下吧!

mybatis

mybatis-config.xml详细配置(配置时要把多余的属性删除 不能有中文 否则报错!)

<?xmlversion="1.0"encoding="UTF-8"?><!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTDConfig3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><!--configuration核心配置配置文件的根元素--><configuration><!--属性:定义配置外在化--><properties></properties><!--设置:定义mybatis的一些全局性设置--><settings><!--具体的参数名和参数值--><settingname=""value=""/></settings><!--类型名称:为一些类定义别名--><typeAliases><!--实体类少建议第一种取别名方式--><typeAliastype="包路径"alias="别名"></typeAlias><!--实体类多建议第二种取别名方式默认情况下用这种方式别名为类名首字母最好小写--><packagename="包名"/></typeAliases><!--类型处理器:定义Java类型与数据库中的数据类型之间的转换关系--><typeHandlers></typeHandlers><!--对象工厂--><objectFactorytype=""></objectFactory><!--插件:mybatis的插件,插件可以修改mybatis的内部运行规则--><plugins><plugininterceptor=""></plugin></plugins><!--环境:配置mybatis的环境--><environmentsdefault="development"><!--环境变量:可以配置多个环境变量,比如使用多数据源时,就需要配置多个环境变量--><environmentid="development"><!--事务管理器--><transactionManagertype="JDBC"/><!--数据源配置连接我的数据库--><dataSourcetype="POOLED"><propertyname="driver"value="com.mysql.jdbc.Driver"/><propertyname="url"value="jdbc:mysql://localhost:3306/mybatis?serverTimezone=GMT%2B8&amp;useSSL=true&amp;useUnicode=true&amp;characterEncoding=UTF-8"/><propertyname="password"value="123"/><propertyname="username"value="root"/></dataSource></environment></environments><!--数据库厂商标识--><databaseIdProvidertype=""></databaseIdProvider><!--映射器:指定映射文件或者映射类--><mappers><mapperresource="com/kang/w/dao/impl/UserMapper.xml"></mapper></mappers></configuration>

分页

减少数据访问量
limt实现分页
sql语句: select * from 表名 limt 0,5;

0:数据开始的位置

5:数据的长度

第一种:使用Mybatis
1接口

List<User>getUserByLimit(Map<String,Object>map);

2mapeer.xml

<selectid="getUserByLimit"parameterType="map"resultType="user">select*frommybatis.userlimit${starIndex},${pageSize}</select>

2-1结果集映射

<resultMapid="map"type="User"><resultproperty="pwd"column="password"></result></resultMap>

3测试

@TestpublicvoidgetUserByLimitTest(){SqlSessionsqlSession=MyBatisUtils.getSqlSession();UserMappermapper=sqlSession.getMapper(UserMapper.class);HashMaphashMap=newHashMap<String,Object>();hashMap.put("starIndex",1);hashMap.put("pageSize",2);ListuserByLimit=mapper.getUserByLimit(hashMap);for(Objecto:userByLimit){System.out.println(o);}sqlSession.close();}

第二种:使用RowBounds方法
1.接口
List getUserList();
2.实现接口

<selectid="getUserList"resultType="user">select*frommybatis.user</select>

3.测试:

/***测试使用RowBounds实现分页*/@TestpublicvoidgetUserByLimitRowBoundsTest(){SqlSessionsqlSession=MyBatisUtils.getSqlSession();RowBoundsrowBounds=newRowBounds(0,2);List<User>userList=sqlSession.selectList("com.kuang.w.dao.UserMapper.getUserList",null,rowBounds);for(Useruser:userList){System.out.println(user);}//关闭sqlSession.close();}

第三种:使用Mybatis的分页插件 pageHeIper

sql 多对一处理

数据库 :
pojo
数据库中teacher-table表 对应实体类 Teacher

packagecom.kuang.w.pojo;importlombok.Data;/***@authorW*/@DatapublicclassTeacher{privateinttId;privateStringtName;}

数据库中user表 对应 实体类Student

packagecom.kuang.w.pojo;importlombok.Data;/***@authorW*/@DatapublicclassStudent{privateintid;privateinttid;privateStringname;privateStringpassword;privateTeacherteacher;}

1.接口

List<Student>getStudentList();

2.xml配置实现接口

<!--多对一查询1子查询mysql通过一个表里是数据与另一个表的一个数据相的情况下查询另一个的数据一起显示--><selectid="getStudentList"resultMap="studentTeacher">select*frommybatis.user;</select><resultMapid="studentTeacher"type="Student"><!--复杂属性对象用:association集合用:collection--><!--column数据库中的字段property实体类中的属性--><resultproperty="id"column="id"/><resultproperty="name"column="name"/><resultproperty="password"column="password"/><!--javaType一个Java类的全限定名,或一个类型别名(关于内置的类型别名,可以参考上面的表格)。如果你映射到一个JavaBean,MyBatis通常可以推断类型。然而,如果你映射到的是HashMap,那么你应该明确地指定javaType来保证行为与期望的相一致。--><associationproperty="teacher"column="tid"javaType="Teacher"select="getTeacher"></association></resultMap><selectid="getTeacher"resultType="Teacher">select*frommybatis.teacher_tablewheretid=#{id};</select>

<!--2多表联查--><selectid="getStudentList"resultMap="StudentList">selectu.iduid,u.nameuname,u.passwordupassword,u.tidutid,t.tnamefrommybatis.useru,mybatis.teacher_tabletwheret.tid=u.tid;</select><!--映射--><resultMapid="StudentList"type="Student"><resultcolumn="uid"property="id"/><resultcolumn="utid"property="tid"/><resultcolumn="uname"property="name"/><resultcolumn="upassword"property="password"/><associationproperty="teacher"javaType="Teacher"><resultproperty="tName"column="tname"></result></association></resultMap>

mybatis-config.xm配置

<?xmlversion="1.0"encoding="UTF8"?><!DOCTYPEconfigurationPUBLIC"-//mybatis.org//DTDConfig3.0//EN""http://mybatis.org/dtd/mybatis-3-config.dtd"><configuration><propertiesresource="db.properties"/><settings><settingname="logImpl"value="STDOUT_LOGGING"/></settings><typeAliases><typeAliastype="com.kuang.w.pojo.Teacher"alias="teacher"/><typeAliastype="com.kuang.w.pojo.Student"alias="student"/></typeAliases><environmentsdefault="development"><environmentid="development"><transactionManagertype="JDBC"/><dataSourcetype="POOLED"><propertyname="driver"value="${driver}"/><propertyname="url"value="${url}"/><propertyname="password"value="${password}"/><propertyname="username"value="${username}"/></dataSource></environment></environments><mappers><!--<mapperresource="com/kuang/w/dao/TeacherMapper.xml"></mapper><mapperresource="com/kuang/w/dao/StudentMapper.xml"></mapper>--><mapperclass="com.kuang.w.dao.StudentMapper"></mapper><mapperclass="com.kuang.w.dao.TeacherMapper"></mapper></mappers></configuration>

3 测试

@TestpublicvoidgetStudentListTest(){SqlSessionsqlSession=MyBatisUtils.getSqlSession();StudentMappermapper=sqlSession.getMapper(StudentMapper.class);List<Student>studentList=mapper.getStudentList();for(Studentstudent:studentList){System.out.println(student);}sqlSession.commit();sqlSession.close();}

sql 一对多处理

数据表结构 对应的实体类 不变

第一种方式: 多表联查
1接口

List<Teacher>getTeacher(inttid);

2.1 xml实现接口

<selectid="getTeacher"resultMap="TeacherStudent">selectt.tid,t.tname,u.id,u.name,u.passwordfrommybatis.useru,mybatis.teacher_tabletwheret.tid=u.tidandt.tid=#{tid};</select>

2.2映射配置

<resultMapid="TeacherStudent"type="Teacher"><resultproperty="tName"column="tname"/><resultproperty="tId"column="tid"/><!--复杂属性对象用:association集合用:collection--><collectionproperty="students"ofType="Student"><!--javaType指定属性类型一个Java类的全限定名--><resultcolumn="id"property="id"></result><resultcolumn="name"property="name"></result><resultcolumn="password"property="password"></result><resultcolumn="tid"property="tid"></result></collection></resultMap>

3测试

/*测试一对多*/@TestpublicvoidgetTeacherTest2(){SqlSessionsqlSession=MyBatisUtils.getSqlSession();TeacherMappermapper=sqlSession.getMapper(TeacherMapper.class);List<Teacher>teacher=mapper.getTeacher(1);for(Teacherteacher1:teacher){System.out.println(teacher1);}//提交事务架子这里可以不要sqlSession.commit();//关闭sqlSession.close();}

结果

com.intellij.rt.junit.JUnitStarter-ideVersion5-junit4com.kuang.w.dao.myTest,getTeacherTest2Logginginitializedusing'classorg.apache.ibatis.logging.stdout.StdOutImpl'adapter.PooledDataSourceforcefullyclosed/removedallconnections.PooledDataSourceforcefullyclosed/removedallconnections.PooledDataSourceforcefullyclosed/removedallconnections.PooledDataSourceforcefullyclosed/removedallconnections.OpeningJDBCConnectionCreatedconnection164974746.SettingautocommittofalseonJDBCConnection[com.mysql.cj.jdbc.ConnectionImpl@9d5509a]==>Preparing:selectt.tid,t.tname,u.id,u.name,u.passwordfrommybatis.useru,mybatis.teacher_tabletwheret.tid=u.tidandt.tid=?;==>Parameters:1(Integer)<==Columns:tid,tname,id,name,password<==Row:1,狂神,1,天王盖地虎,111<==Row:1,狂神,2,小波,123<==Row:1,狂神,3,雷神,922<==Row:1,狂神,5,马儿扎哈,123<==Total:4Teacher(tId=1,tName=狂神,students=[Student(id=1,tid=1,name=天王盖地虎,password=111),Student(id=2,tid=1,name=小波,password=123),Student(id=3,tid=1,name=雷神,password=922),Student(id=5,tid=1,name=马儿扎哈,password=123)])ResettingautocommittotrueonJDBCConnection[com.mysql.cj.jdbc.ConnectionImpl@9d5509a]ClosingJDBCConnection[com.mysql.cj.jdbc.ConnectionImpl@9d5509a]Returnedconnection164974746topool.Processfinishedwithexitcode0

第二种方式: 子查询
1接口

List<Teacher>getTeacher(inttid);

2 实现接口

<!--第二种方式:子查询--><selectid="getTeacher3"resultMap="TeacherStudent3">select*frommybatis.teacher_tablewheretid=#{tid};</select><resultMapid="TeacherStudent3"type="Teacher"><!--复杂属性对象用:association集合用:collection我们需要单独处理对象:association集合:collectionjavaType=""指定属性的类型!集合中的泛型信息,我们使用ofType获取--><resultcolumn="tid"property="tId"/><resultcolumn="tname"property="tName"/><collectionproperty="students"javaType="ArrayList"ofType="Student"select="getStudentByTeacherId"column="tid"></collection></resultMap><selectid="getStudentByTeacherId"resultType="Student">select*frommybatis.userwheretid=#{tid};</select>

3测试 同上

以上是“Mybatis的基础知识点”这篇文章的所有内容,感谢各位的阅读!相信大家都有了一定的了解,希望分享的内容对大家有所帮助,如果还想学习更多知识,欢迎关注亿速云行业资讯频道!