文章目录
Mybatis基础(七)
日志(Log4j)
- 配置jar包:
- log4j-1.2.17.jar
- 开启日志:配置conf.xml
<settings>
<!-- 开启日志,并指定所使用的是什么日志 -->
<setting name="logImpl" value="LOG4J"/>
<!-- 其他日志有:SLF4J、Log4j 2等等 -->
</settings>
- 编写配置日志输出文件:
- 建立一个文件: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
日志级别, 输出设备(stdout为控制台)
日志显示方式
日志显示方式为平铺方式
日志显示方式为平铺方式的格式
延迟加载
如果查询结果信息有多部份,我们只需要使用其中一部分(另一部分不需要),使用延迟加载会将及时加载部分加载出来,延迟加载部分先不进行加载(提高系统速度)。如果不适用延迟加载则会将所有的信息查出来,系统会很慢。
例如:在Mybatis一对多关联查询中,我们只需要一的信息不需要多的信息(也就是需要拥有外键类的属性,而不需要引用表变成的类属性)
按照建表建立实体类规则,一对多建实体类为:将一个类A作为==多个==属性放入另一个类B中。这样这两个类就建立起关系了。
例如:B类为StudentClass类,A类为Student类。
StudentClass拥有属性:classId、className、(List<Student>) students。
Student拥有属性:stuNo、stuName。
需要的是StudentClass中的属性classId、className,而不需要students。
配置延迟加载
- 在mapper.xml文件中修改resultMap中的信息进行配置:(以一对一为例,一对多相同)
将一个类A作为属性放入另一个类B中。这样这两个类就建立起关系了。
B类为Student类,A类为StudentCard类。
Studnet类中拥有stuNo、stuName、card字段。
StudentCard类中拥有cardId、cardInfo字段。
原mapper文件:
<select id="" parameterType="" resultMap="student_card_map">
select s.*, c.* from student s
inner join studentCard c
on s.sid = c.cid
</select>
<resultMap type="Student" id="student_card_map">
<id property="stuNo" column="stuNo"/>
<reslut property="stuName" column="stuName"/>
<!--学生证属性,学生证类型的。javaType指定属性的类型。-->
<association proerty="card" javaType="StudentCard">
<!--StudentCard类中还有属性-->
<id property="cardId" column="cardId"/>
<id property="cardInfo" column="cardInfo"/>
</association>
</resultMap>
现mapper文件:
延迟加载不能再被延迟属性标签中写其类的属性,而必须新建一个mapper文件用于,,,并且再延迟属性标签中添加元素select、column
<select id="" parameterType="int" resultMap="student_card_map">
select * from student
</select>
<resultMap type="Student" id="student_card_map">
<id property="stuNo" column="stuNo"/>
<reslut property="stuName" column="stuName"/>
<!-- 加一个select属性用于引用外部xml文件;一个column用于表示外键是哪个(将两个查询关联起来) -->
<association proerty="card" javaType="StudentCard" select="StudentCardMapper.selectCardById" column="sid">
<!--
延迟加载不在这列写关联类的属性,写了就是及时加载了
<id property="cardId" column="cardId"/>
<id property="cardInfo" column="cardInfo"/>
-->
</association>
</resultMap>
studentCardMapper.xml:注意增加了mapper文件要修改conf文件中的映射
<mapper namespace="StudentCardMapper">
<select id="selectCardById" parameterType="int" resultType="studentCard">
<!-- 写column就是为这里的#{id}服务的 -->
select * from studentCard where cid = #{id}
</select>
</mapper>
加载延后的数据:
// 使用外键类(StudentClass)的get关联属性方法(getCard)
StudentClass student;
.......;
// 加载延迟加载内容
StudentCard c = student.getCard();
- 在conf.xml文件中配置settings
<settings>
<!--开启延迟加载-->
<setting name="lazyLoadingEnabled" value="true"/>
<!--关闭立即加载-->
<setting name="aggressiveLazyLoading" value="false"/>
</settings>