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&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 >= #{start}
</if>
<if test="end != null">
AND id <= #{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
本文仅供自我参考,侵权立删
转载需注明转载出处