MyBatis学习二

MyBatis

配置文件优化

1、可以将配置信息单独放入db.properties中,然后在动态引入

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/数据库名称
username=用户名
password=密码

2、通过mybatis的配置文件加载

<configuration>
      <properties resource="db.properties"/>
</configuration>

引入之后 使用${key}取出value,大部分情况下,我们都会讲这种配置文件存放到springIOC容器中

3、我们可以通过配置别名来代替SQL标签的resultType返回值

<!-- 设置单个/多个别名 -->
<typeAliases>
    <!-- 单个别名 (忽略大小写)-->
    <!--<typeAlias type="com.xingwei.entity.Student" alias="student"/> -->
    <!-- 批量定义别名 -->
    <package name="com.xingwei.entity"/>
</typeAliases>

4、日志 Log4j

可以通过日志信息,详细的阅读mybatis执行情况(观察mybatis实际执行的sql语句以及sql中的参数 和返回结果)

如果不指定 Mybatis就会根据以下顺序 寻找日志

SL4J-> Apache Commons Logging -> Log4j 2 ->Log4 j -> JDK logging

  • Log4j: log4j.jar (mybatis.zip中包含此jar包)

1、开启日志:conf.xml

<settings>
	<!-- 开启日志  并指定的-->
	<setting name="logImpl" value="LOG4J"/>
</settings>

2、编写配置日志输出文件 log4j.properties

log4j.rootLogger=DEBUG, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

日志级别:DEBUG<INFO<WARN<ERROR,如果设置为INFO 则只显示info以上级别的信息

5、关于mybatis的延迟加载

延迟加载的好处:我们需要什么的时候才去加载什么,大大提高 数据库性能,因为查询单表要比关联查询多张表速度要快。

<settings>
  <setting name="cacheEnable" value="false"/>    #开启缓存
    <!-- 开启延迟加载 -->
    <setting name="lazyLoadingEnable" value="true"/>
    <!-- 关闭立即加载 -->
    <setting name="aggressiveLadyLodding" value="false"/>
</settings>

举例:

如果不采用延迟加载(立即加载),查询时会将一对多 都查询,班级、班级中的所有学生。
如果想要 暂时只查询1的一方 而多的一方 先不查询而是在需要的时候再查询 ----->延迟加载

延迟加载步骤 先查班级 按需查询学生

  • 开启延迟加载conf.xml配置<settings></settings>

  • 配置mapper.xml

  • 写两个mapper

1、班级mapper

<!-- 建立一对多联系  带延迟加载	 -->
<select id="queryClassAndStudents" resultMap="student_card_lazyLoad_map">
  <!--111111 先查班级 -->
  select c.* from studentclass c 
</select>

<resultMap type="studentClass" id="student_card_lazyLoad_map">
  <id property="classId" column="classid"/>
  <result property="className" column="classname"/>
  <!-- 22222再查班级对应的学生 -->
  <collection property="students" ofType="Student" select="com.xingwei.mapper.StudentMapper.queryStudentsByClassId" column="classid">

  </collection>
</resultMap>			

2、学生mapper

<!-- namespace+id select属性:com.xingwei.mapper.StudentMapper.queryStudentsByClassId -->
	<!-- 一对多 ,延迟加载需要的  :查询班级中的所有学生 -->
	<select id="queryStudentsByClassId" parameterType="int"  resultType="Student">
		select * from student where classId = #{classid}	
	</select>
做的不好,多多指教
原文地址:https://www.cnblogs.com/xingStudy/p/14197251.html