MyBatis很方便,Dao层定义好接口,都不需要实现,直接都在xml中配置就能动态代理实现。
项目搭建参考 MyBatis入门
1. 创建核心配置,这边的数据源使用变量配置
<?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>
<properties resource="jdbc.properties"></properties>
<typeAliases>
<typeAlias type="com.hhm.domain.User" alias="user"></typeAlias>
</typeAliases>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com\hhm\mapper\UserMapper.xml"></mapper>
</mappers>
</configuration>
2. 创建测试接口
package com.hhm.Dao;
import com.google.protobuf.Internal;
import com.hhm.domain.User;
import java.util.List;
public interface UserMapper {
List<User> findAll();
User findOneById(int id);
List<User> findByCondition(User user);
List<User> findByIds(List<Integer> ids);
}
3. 创建sql语句配置文件 UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.hhm.Dao.UserMapper">
<!--sql语句抽取-->
<sql id="selectUser">SELECT * FROM user</sql>
<select id="findAll" resultType="user">
SELECT * FROM user
</select>
<select id="findOneById" parameterType="int" resultType="user">
SELECT * FROM user WHERE id = #{id}
</select>
<select id="findByCondition" parameterType="user" resultType="user">
SELECT * FROM user
<where>
<if test="id!=0">
and id = #{id}
</if>
<if test="username!=null">
and username=#{username}
</if>
<if test="password!=null">
and password=#{password}
</if>
</where>
</select>
<select id="findByIds" parameterType="list" resultType="user">
<include refid="selectUser"></include>
<where>
<foreach collection="list" open="id in(" close=")" separator="," item="id">
#{id}
</foreach>
</where>
</select>
</mapper>
这边的命名空间需要与接口的包名一致
namespace="com.hhm.Dao.UserMapper"
id需要与方法名一致
id="findByIds"
这边用到了 if 条件,可以根据条件的满足与否,对其动态增减 where的条件
这边用到了 foreach 用法一目了然,原始sql语句是这样 select * from user where id in(1,2,3)
foreach中 open="id in(" close=")" 表示动态参数 1,2,3 的开始部分,即左边。
close=")" 表示 动态参数 1,2,3 的关闭部门,即右边。
separator="," 表示动态参数是用什么进行分隔的
item="id" 表示循环的参数,可自定义
4. 为了监控语句方便,加入日志配置 log4j.properties 放在resources下
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file mylog.log ###
log4j.appender.file=org.apache.log4j.FileAppender
log4j.appender.file.File=c:/mylog.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug, stdout
启用了日志,我们在控制台就很清楚的看见了执行的语句,参数是1和3
5. 创建测试类
package com.hhm.test;
import com.hhm.Dao.UserMapper;
import com.hhm.domain.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.junit.Test;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
public class MyBatisTest {
@Test
public void test1() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
// 1.测试查询列表
// List<User> userList = userMapper.findAll();
// System.out.println(userList);
// 2.测试查询单个
// User user = userMapper.findOneById(2);
// System.out.println(user);
// 3.测试根据条件查询列表
// User user = new User();
// user.setId(2);
// user.setUsername("lisi");
// List<User> userList = userMapper.findByCondition(user);
// System.out.println(userList);
//4.根据in条件查询多个
List<Integer> lsIds = new ArrayList<Integer>();
lsIds.add(1);
lsIds.add(3);
List<User> userList = userMapper.findByIds(lsIds);
System.out.println(userList);
sqlSession.close();
}
}
6. 后续如果需要新的实现,加一下接口,配置文件配置一下sql语句即可