`
need_faith
  • 浏览: 80917 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

【原创】Mybatis学习笔记(一)——Spring集成Mybatis

阅读更多

Mybatis学习笔记(一)

                               ——Spring集成Mybatis

 

环境和组件
  • eclipse-jee-indigo-SR2-win32-x86_64
  • Spring 3.12
  • mybatis-3.2.2
  • mybatis-spring-1.2.0
  • mysql-connector-java-5.1.23
  • log4j-1.2.17
  • cglib-nodep-2.2.3
  • 操作系统win7 64bit
  • java version "1.6.0_29"
  • MySQL 5.6

 

  • web项目构建

web项目文件结构

 

  • 应用上下文配置文件在web.xml中配置

 

<!-- spring框架 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<!-- 上下文配置 -->
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>
			/WEB-INF/applicationContext.xml,
			/WEB-INF/config/**/*.xml
		</param-value>
	</context-param>

 

 

 

  • 数据源配置

 

<!-- 属性文件 -->
	<context:property-placeholder location="/WEB-INF/properties/**/*.properties" />

	<!-- 数据源 -->
	<bean id="dataSource"
		class="org.springframework.jdbc.datasource.DriverManagerDataSource"
		scope="singleton">
		<property name="driverClassName" value="${jdbc.driverClassName}" />
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />
	</bean>

 

 

  •  Mybatis会话工厂bean(SqlSessionFactoryBean)在applicationContext.xml中的配置

 

<!-- mybatis会话工厂 -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<!-- 数据源 -->
		<property name="dataSource" ref="dataSource" />
		<!-- 配置文件 -->
		<property name="configLocation" value="/WEB-INF/mybatis-config.xml" />
	</bean>

	<!-- mybatis数据映射配置文件扫描器配置 -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.lxl" />
		<!-- 只有声明了com.lxl.core.SqlMapper注解的接口才可以被扫描 -->
		<property name="annotationClass" value="com.lxl.core.SqlMapper"/>
	</bean>

 

 

  •  @SqlMapper是为了让Mybatis扫描识别的一个简单注解
/**
 * mybatis sql映射注解,用于mybatis自动扫描,只有此声明此注解的Mapper才会识别
 * 
 * @author LXL
 * 
 */
@Target({ TYPE })
@Retention(RUNTIME)
public @interface SqlMapper {
}

 (我尝试过使用MapperScannerConfigurer的指定包路径basePackage来扫描SqlMapper的方式,不过,我喜欢web应用分层调用时,使用Spring的@Service、@Resource注解自动装配,在使用包路径配置Mybatis对SqlMapper的扫描时,@Service、@Resource注解不能按照类型自动装配了,必须对@Service指定id,使用@Resource是声明name,例如:@Service(value = "UserDomain")和 @Resource(name = "UserDomain"),增加了代码量,大家可以尝试一下,是否遇到和我一样的问题)

 

 

  •  对dao层接口增加@SqlMapper注解声明
/**
 * 用户持久层接口
 * 
 * @author LXL
 * 
 */
@SqlMapper
public interface IUserDao {
        /**
	 * 新增
	 * 
	 * @param data
	 * @return
	 */
	public User insert(User data);

	/**
	 * 删除
	 * 
	 * @param pks
	 */
	public void delete(String[] pks);

	/**
	 * 更新
	 * 
	 * @param data
	 * @return
	 */
	public void update(User data);

	/**
	 * 详单
	 * 
	 * @param data
	 * @return
	 */
	public User detail(User data);

	/**
	 * 查询
	 * 
	 * @param filter
	 * @return
	 */
	public List<User> query(UserQueryFilter filter);
}
  • mapper配置文件

 

<?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.lxl.authority.user.dao.IUserDao">

	<sql id="TABLE">
		pub_user
	</sql>

	<sql id="COLUMNS">
		user_id, user_code, user_name, password, group_id, is_use
	</sql>

	<sql id="ORDER">
		<if test="order != null">
			order by #{order}
		</if>
		<if test="!isAsc">
			desc
		</if>
	</sql>

	<resultMap id="DATA" type="com.lxl.authority.user.model.User">
		<result property="isUse" column="is_use" />
	</resultMap>



	<insert id="insert" parameterType="com.lxl.authority.user.model.User">
		insert into
		<include refid="TABLE" />
		(
		<include refid="COLUMNS" />
		)
		values
		(#{userId}, #{userCode},#{userName}, #{password},
		#{groupId}, #{isUse})
	</insert>

	<delete id="delete" parameterType="java.lang.String">
		delete from
		<include refid="TABLE" />
		where 1=1
		and id in
		<foreach item="item" index="index" collection="array" open="("
			separator="," close=")">
			#{item}
		</foreach>
	</delete>

	<update id="update" parameterType="com.lxl.authority.user.model.User">
		update
		<include refid="TABLE" />
		set
		user_code = #{userCode},
		user_name = #{userName},
		password =
		#{password},
		group_id = #{groupId},
		where
		user_id = #{userId}
	</update>

	<select id="detail" parameterType="com.lxl.authority.user.model.User"
		resultMap="DATA">
		select *
		from
		<include refid="TABLE" />
		where
		user_id = #{user_id}
	</select>

	<select id="query" parameterType="com.lxl.authority.user.controller.UserQueryFilter"
		resultMap="DATA">
		select *
		from
		<include refid="TABLE" />
		where 1=1

		<if test="userId != null">
			and id in
			<foreach item="item" index="index" collection="id" open="("
				separator="," close=")">
				#{item}
			</foreach>
		</if>

		<if test="userCode != null">
			and code in
			<foreach item="item" index="index" collection="code" open="("
				separator="," close=")">
				#{item}
			</foreach>
		</if>

		<if test="userName != null">
			and alias in
			<foreach item="item" index="index" collection="alias" open="("
				separator="," close=")">
				#{item}
			</foreach>
		</if>

		<if test="isUse != null">
			and is_use = #{isUse}
		</if>

		<!-- 排序 -->
		<include refid="ORDER" />
	</select>


</mapper>

 

 

经过以上步骤,spring已经完成mybatis的集成,可以尝试使用mybatis了

为了增加mybaits的配置,我们在applicationContext.xml中已经配置了mybatis的配置文件/WEB-INF/mybatis-config.xml

 

  • mybatis配置的一个可用例子

 

<?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>
	<settings>
		<!-- 全局映射器启用缓存 -->
		<setting name="cacheEnabled" value="false" />
		<!-- 查询时,关闭关联对象即时加载以提高性能 -->
		<setting name="lazyLoadingEnabled" value="true" />
		<!-- 设置关联对象加载的形态,此处为按需加载字段(加载字段由SQL指 定),不会加载关联表的所有字段,以提高性能 -->
		<setting name="aggressiveLazyLoading" value="false" />
		<!-- 对于未知的SQL查询,允许返回不同的结果集以达到通用的效果 -->
		<setting name="multipleResultSetsEnabled" value="true" />
		<!-- 允许使用列标签代替列名 -->
		<setting name="useColumnLabel" value="true" />
		<!-- 允许使用自定义的主键值(比如由程序生成的UUID 32位编码作为键值),数据表的PK生成策略将被覆盖 -->
		<setting name="useGeneratedKeys" value="true" />
		<!-- 给予被嵌套的resultMap以字段-属性的映射支持 -->
		<setting name="autoMappingBehavior" value="FULL" />
		<!-- 对于批量更新操作缓存SQL以提高性能 -->
		<setting name="defaultExecutorType" value="BATCH" />
		<!-- 数据库超过25000秒仍未响应则超时 -->
		<setting name="defaultStatementTimeout" value="25000" />
	</settings>
	<!-- 全局别名设置,在映射文件中只需写别名,而不必写出整个类路径 -->
	<typeAliases>
		<!-- 别名声明写这里 -->
	</typeAliases>
	<!-- 非注解的sql映射文件配置,如果使用mybatis注解,该mapper无需配置,但是如果mybatis注解中包含@resultMap注解,则mapper必须配置,给resultMap注解使用 -->
	<mappers>
		<!-- 显式指定mapper配置文件写这里 采用与SqlMapper同名,并且放在同一个包下,可以自动配置,所以这里不写了 -->
	</mappers>
</configuration>  

 

 以上是我在spring中集成mybaits的基本过程,如有不对地方,请多指教

 

 

 注:本博客文章均已注明原创和转载,如转载本博客文章,请注明原文出处或征求原作者同意。

 

 

  • 大小: 18.3 KB
3
2
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics