第二章:MyBatis映射文件深入
一、Mybatis的Dao层实现
传统开发方式是手动对dao层进行实现,
而企业级开发的主流,采用的是Mybatis的代理开发方式实现dao层的开发。
Mapper接口开发方法只需要编写Mapper接口(类似于dao层接口),
由Mybatis框架根据接口定义创建接口的动态代理对象,代理对象的方法体同dao接口实现类的方法。
Mapper接口开发需要遵循以下规范:
- Mapper.xml文件中的namespace与mapper接口的全限定名相同
- Mapper接口方法名和Mapper.xml中定义的每个statement的id相同
- Mapper接口方法的输入参数类型和mapper.xml中定义的每个sql的parameterType的类型相同
- Mapper接口方法的输出参数类型和mapper.xml中定义的每个sql的resultType的类型相同
二、动态SQL
Mybaits的映射文件中,有时候业务逻辑复杂sql语句是动态变化的,就难以满足要求了:
1.环境搭建
package com.itcast.domain;
public class User {
private int id;
private String username;
private String password;
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassward() { return password; }
public void setPassward(String passward) { this.password = passward; }
@Override
public java.lang.String toString() {
return "User{" + "id=" + id + ", username=" + username + ", passward=" + password + '}';
}
}
package com.itcast.mapper;
import com.itcast.domain.User;
import java.util.List;
public interface UserMapper {
public List<User> findByCondition(User user);
}
<?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.itcast.mapper.UserMapper">
<select id="findByCondition" parameterType="com.itcast.domain.User" resultType="com.itcast.domain.User">
select * from user where id = #{id} and username = #{username} and password = #{password}
</select>
</mapper>
<?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"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test"/>
<property name="username" value="root"/>
<property name="password" value="20001201"/>
</dataSource>
</environment>
</environments>
<mappers>
<mapper resource="com.itcast.mapper/UserMapper.xml"></mapper>
</mappers>
</configuration>
### 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
package com.itcast.test;
import com.itcast.domain.User;
import com.itcast.mapper.UserMapper;
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.List;
public class MapperTest {
@Test
public void test1() throws IOException {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
UserMapper mapper = sqlSession.getMapper(UserMapper.class);
User condition = new User();
condition.setId(1);
condition.setUsername("zhangsan");
condition.setPassward("123");
List<User> userList = mapper.findByCondition(condition);
System.out.println(userList);
}
}
2.条件查询if
当部分查询条件缺失时,可以在UserMapper.xml文件中使用if 标签拼接sql语句,修改文件如下:
<?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.itcast.mapper.UserMapper">
<select id="findByCondition" parameterType="com.itcast.domain.User" resultType="com.itcast.domain.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>
</mapper>
当MapperTest中给出的查询条件变化时,sql可以进行动态查询:
3.复杂查询foreach
Mybatis提供了用于数组和集合循环遍历的<foreach>元素,实现复杂的查询操作,修改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.itcast.mapper.UserMapper">
<select id="findByCondition" parameterType="com.itcast.domain.User" resultType="com.itcast.domain.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="java.util.List" resultType="com.itcast.domain.User">
select * from user
<where>
<foreach collection="list" open="id in(" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>
</mapper>
package com.itcast.mapper;
import com.itcast.domain.User;
import java.util.List;
public interface UserMapper {
public List<User> findByCondition(User user);
public List<User> findByids(List<Integer> ids);
}
4.Sql片段抽取
Sql中可以将重复的sql提取出来,使用时用include应用即可最终达到sql重用的目的:
<?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.itcast.mapper.UserMapper">
<sql id="selectUser">select * from user</sql>
<select id="findByCondition" parameterType="com.itcast.domain.User" resultType="com.itcast.domain.User">
<include refid="selectUser"></include>
<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="java.util.List" resultType="com.itcast.domain.User">
<include refid="selectUser"></include>
<where>
<foreach collection="list" open="id in(" close=")" item="id" separator=",">
#{id}
</foreach>
</where>
</select>
</mapper>
|