一.Mybatis

项目目录:

log4j.properties文件负责打印日志的配置

# Global logging configuration
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

SQLMapConfig.xml文件配置,主要配置mybatis的数据库连接配置,以及指定扫描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>
<!-- 和spring整合后 environments配置将废除-->
<environments default="development">
<environment id="development">
<!-- 使用jdbc事务管理,事务控制由mybatis-->
<transactionManager type="JDBC" />
<!-- 数据库连接池,由mybatis管理-->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/mybatis001?characterEncoding=utf-8" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments>

<mappers>
     <!--扫描mapper包下的所有mapper-->
<package name="mapper"/>
</mappers>

</configuration>

UserObjectMapper.java和UserObjectMapper.xml文件分别用于定义调用方法的接口和配置调用方法对应的sql语句。文件名必须相同,切在同一个文件夹下,才能使用后续SQLSession.getMapper方法构建出UserObjectMapper的实例,进行接口内方法的调用。

UserObjectMapper.java内容:

package mapper;

import pojo.User;
import pojo.UserQueryVo;

import java.io.IOException;
import java.util.List;

/**
* Created by 01467835 on 2017/9/22.
*/
public interface UserObjectMapper{


public List<User> findUserList(UserQueryVo userQueryVo) throws IOException;

public List<User> findUserListById(UserQueryVo userQueryVo) throws IOException;


}

UserObjectMapper.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="mapper.UserObjectMapper">

<sql id="query_user_where">
<if test="user!=null">
<if test="user.sex!=null and user.sex!=''">
AND user.sex = #{user.sex}
</if>
<if test="user.address!=null and user.address!=''">
AND user.address LIKE '%${user.address}%'
</if>
</if>
</sql>

<sql id="query_id_where">
<if test="ids!=null">
<foreach collection="ids" item="user_id" open="AND (" close=")" separator="or">
id=#{user_id}
</foreach>
</if>
AND user.sex = sex.sex_id
</sql>

<resultMap id="UserSexResultMap" type="pojo.User">
<id column="id" property="id"/>
<result column="username" property="username"/>
<result column="birthday" property="birthday"/>
<result column="address" property="address"/>

<association property="sexName" javaType="pojo.Sex">
<id column="sex_id" property="sexId"/>
<result column="sex_name" property="sexName"/>
</association>
</resultMap>


<select id="findUserList" parameterType="pojo.UserQueryVo" resultType="pojo.User">
SELECT * from USER
<where>
<include refid="query_user_where"></include>
</where>
</select>
<select id="findUserListById" parameterType="pojo.UserQueryVo" resultMap="UserSexResultMap">
SELECT * FROM USER,SEX
<where>
<include refid="query_id_where"></include>
</where>
</select>


</mapper>
mapper中的返回方式有resultType和resultMap两种,前者直接返回数据类型,后者可以定义一个ResultMap进行更多的逻辑设计。包括if的分支逻辑,foreach的循环逻辑,association的一对一关联查询,collection的一对多关联查询等等。

MaybatisTest.java测试文件,主要用户指定配置文件,创建SQLSessionFactory,编写测试用例等,内容如下
package MybatisTest;

import mapper.UserObjectMapper;
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.Before;
import org.junit.Test;
import pojo.User;
import pojo.UserQueryVo;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

/**
* Created by 01467835 on 2017/9/22.
*/
public class MybatisTest {

private SqlSessionFactory sqlSessionFactory;

@Before
public void setup() throws IOException{
String resource = "SqlMapConfig.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
}

@Test
public void findUserList() throws IOException{
SqlSession sqlSession = sqlSessionFactory.openSession();
UserObjectMapper userObjectMapper = sqlSession.getMapper(UserObjectMapper.class);
UserQueryVo userQueryVo = new UserQueryVo();

User user = new User();
user.setSex(1);
user.setAddress("2");
userQueryVo.setUser(user);

List<Integer> ids = new ArrayList<>();
ids.add(1);
ids.add(3);
userQueryVo.setIds(ids);

List<User> userList = userObjectMapper.findUserListById(userQueryVo);
System.out.println(userList);
}

}pojo中主要是一些实体类,sex,User,UserQureyVo等,其中UserQueryVo中主要存储补充到查询语句中的条件信息。内容如下:
UserQueryVo.java的内容:
package pojo;

import java.util.List;

/**
* Created by 01467835 on 2017/9/22.
*/
public class UserQueryVo {
private User user;
private List<Integer> ids; //如果你要查询某些id对用的用户信息,可以将id存在这个list下,传入到UserObjectMapper.java中进行对应的查询

public List<Integer> getIds() {
return ids;
}

public void setIds(List<Integer> ids) {
this.ids = ids;
}

public User getUser() {
return user;
}

public void setUser(User user) {
this.user = user;
}
}



二、Mybatis和Spring整合
spring中提供了dataSource的方式连接数据库,废除了SqlMapConfig中的environment的方式,增加了spring的配置文件applicationContext.xml,内容如下:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:util="http://www.springframework.org/schema/util"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">


<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties" />

<!-- 数据源,使用dbcp -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="10" />
<property name="maxIdle" value="5" />
</bean>

<!-- sqlSessinFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 加载mybatis的配置文件 -->
<property name="configLocation" value="mybatis/SqlMapConfig.xml" />
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>

<!-- 逐个进行mapper接口的配置-->
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
<property name="mapperInterface" value="com.haier.ssm.mapper.UsersMapper"/>
<property name="sqlSessionFactory" ref="sqlSessionFactory"/>
</bean>

<!-- 此方法在jdk8与spring3使用时会报错,切换到JDK7可以以使用包扫描功能
<bean id="userMapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.haier.ssm.mapper"/>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>
-->
</beans>

SQLMapConfig.xml中只需要声明一下扫描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>
<mappers>
<package name="com.haier.ssm.mapper"/>
</mappers>
</configuration>

在test文件中调用spring整合mybatis之后的方法,内容如下
package com.haier.ssm.test;

import com.haier.ssm.dao.UserDao;
import com.haier.ssm.mapper.UsersMapper;
import com.haier.ssm.po.User;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

/**
* Created by 01467835 on 2017/9/25.
*/
public class UserDaoImplTest {
private ApplicationContext applicationContext;

@Before
public void setup() throws Exception{
applicationContext = new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
}

@Test
public void testFindUserById() throws Exception{
UsersMapper userMapper = (UsersMapper)applicationContext.getBean("userMapper");
User user = userMapper.findUserById(1);
System.out.println(user);
}
}