MyBatis的log4j打印日志、动态SQL方式

MyBatis的进一步用法

mybatis-config.xml 里面的参数也可以是不固定的

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC"/>
      <dataSource type="POOLED">
        <property name="driver" value="com.mysql.jdbc.Driver"/>
        <property name="url" value="jdbc:mysql://${server}/xxx数据库?useUnicode=true&amp;characterEncoding=UTF-8"/>
        <property name="username" value="${username}"/>
        <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <mappers>
    <mapper resource="mybatis-mapper.xml"/>
    <mapper resource="mybatis-mapper-teacher.xml" />
  </mappers>
</configuration>

然后我们调用的时候可以设置,像map函数一样

public static void test3() throws Exception
	{
		//设定参数
		Properties props = new Properties();
		props.put("server", "127.0.0.1");
		props.put("username", "root");
		props.put("password", "12456");
		
		//创建SqlSessionFactory
		String resource = "mybatis-config.xml";
		InputStream stream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = 
				new SqlSessionFactoryBuilder().build(stream,props);
		
		// 使用 Map 接收
		try(SqlSession session = sqlSessionFactory.openSession()) {
			//查询,并转成 POJO列表
			List<Map> rows = session.selectList("af.test2.selectTeacher2"); 
			System.out.println("查得记录数: " + rows.size()); 
		}
	}

使用log4j打印日志

首先要有jar包,然后在src下有log4j.properties文件。文件配置如下:


# C,R is name of the following appenders
# 改这里就行了 X.Y.Z,改成mybatis-mapper.xml下自己需要使用的 namespace的名字
log4j.logger.X.Y.Z=DEBUG,C,R

log4j.appender.C=org.apache.log4j.ConsoleAppender
# Set the appender threshold to INFO
log4j.appender.C.Threshold=DEBUG
log4j.appender.C.layout=org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern=%-d{HH:mm:ss} %-5p [XYZ] %c %x - %m%n

# logging to file, rolling
# - change the log file's name and path, located in tomcat path
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.Threshold=DEBUG
log4j.appender.R.File=c:/mylogs/mybatis-example.log
log4j.appender.R.MaxFileSize=4000KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%-d{yyyy-MM-dd HH:mm:ss} %-5p %c %x - %m%n

也有可注解方式的Mapper方式

<!-- mapper-config.xml中mappers不在是 resources -->
<mappers>
    <mapper class="sql.StudentMapper"/>
    <mapper class="sql.TeacherMapper"/>
  </mappers>

创建个接口

package sql;

import org.apache.ibatis.annotations.Select;

import my.Student;

public interface StudentMapper
{
	@Select("SELECT * FROM student WHERE id = #{id}")
	Student getStudent(int id);
}

调用

public static void test3() throws Exception
	{	
		//创建SqlSessionFactory
		String resource = "mybatis-config.xml";
		InputStream stream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = 
				new SqlSessionFactoryBuilder().build(stream);
		
		// 使用 Map 接收
		try(SqlSession session = sqlSessionFactory.openSession()) {
			//查询,并转成 POJO列表
			StudentMapper mapper = session.getMapper(StudentMapper.class);
			Student stu = mapper.getStudent(20190003);
			if(stu != null)
			{
				System.out.println(stu.getName());
			}
		}
	}

注解方式只适用于简单的SQL语句

还有动态的SQL方式

<mapper namespace="af.test">
	<select id="getStudent2" resultType="my.Student">
		select * from student
		<where>
			<if test="start != null">
				id &gt;= #{start}
			</if>
			<if test="end != null">
				AND id &lt;= #{end}
			</if>
		</where>
	</select>
</mapper>

使用方式

public static void test3() throws Exception
	{
		//创建SqlSessionFactory
		String resource = "mybatis-config.xml";
		InputStream stream = Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = 
				new SqlSessionFactoryBuilder().build(stream);
		
		// 使用 Map 接收
		try(SqlSession session = sqlSessionFactory.openSession()) {
			Map<String, Object> map = new HashMap<>();
			map.put("start", 20190004);
			map.put("end", 20190006);
			
			// 第1种情况  select * from student where 1=1 and id>=20190003 and id<=20190006
			// 第2种情况  select * from student where 1=1 and id>=20190003
			// 第3种情况  select * from student where 1=1 and id<=20190006
			// 第4种情况  select * from student where 1=1 
			List<Student> stu = session.selectList("af.test.getStudent2", map);
			for(Student s : stu)
			{
				System.out.println("name:" + s.getName());
			}
		}
	}

更多方式请参考MyBatis官方文档
https://mybatis.org/mybatis-3/index.html

本文仅供自我参考,侵权立删

转载需注明转载出处

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值