velocity mybatis spring 在maven的整合开发(四)

原创
2014/07/04 10:57
阅读数 236

Spring整合Mybatis配置文件

spring-mybatis.xml。该配置文件的locate定义在WEB-IN/web.xml中。

本文重点:Spring自动扫描方式生成bean

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
	xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:util="http://www.springframework.org/schema/util"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
            http://www.springframework.org/schema/beans/spring-beans-4.1.xsd    
            http://www.springframework.org/schema/context 
            http://www.springframework.org/schema/context/spring-context-4.1.xsd    
            http://www.springframework.org/schema/mvc 
            http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd    
            http://www.springframework.org/schema/util 
            http://www.springframework.org/schema/util/spring-util-4.1.xsd">

	<context:component-scan
		base-package="ct.service,ct.controllers" />
	<context:annotation-config />

	<!-- 数据源定义 -->
	<context:property-placeholder location="classpath:jdbc.properties" />
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
		p:driverClass="${jdbc.driverClassName}" p:jdbcUrl="${jdbc.url}"
		p:user="${jdbc.username}" p:password="${jdbc.password}" />

	<!-- sqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
		p:dataSource-ref="dataSource" p:typeAliasesPackage="ct.bean" />

	<!-- 配置要扫描的xxxMapper.xml -->
	<!-- 查 找 类 路 径 下 的 映 射 器 并 自 动 将 它 们 创 建 成 MapperFactoryBean -->
	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
		p:basePackage="ct.dao.mybatis" p:sqlSessionFactoryBeanName="sqlSessionFactory" />

	<!-- 配置事务管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="dataSource" />
	</bean>

</beans>


配置解释

1、spring的bean自动扫描

component-scan:自动扫描的包路径,多个包用逗号隔开。配置了这一项,Spring将会自动扫描这个包和子包的java文件。@Component @Controller@Service等这些注解的类,则把这些类注册为bean。


package ct.bean;

public class User {
    private int id;
    private String userName;
    private String password;
    private String description;
    private int status;
    
    
    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 getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getDescription() {
        return description;
    }
    public void setDescription(String description) {
        this.description = description;
    }
    public int getStatus() {
        return status;
    }
    public void setStatus(int status) {
        this.status = status;
    }
}


2、mybatis的mapper自动扫描

SqlSessionFactoryBean

MapperScannerConfigurer是spring和mybatis整合的mybatis-spring jar包中提供的一个类。它将会查找类路径下的映射器并自动将它们创建成MapperFactoryBean。

basePackage里配置mybatisDao所在目录。xml文件默认在source的同级目录下。

例如java文件在src/java/下的ct.dao.mybatis.IUserMapper.java,则xml配置文件在src/source/下的ct.dao.mybatis.IUserMapper.xml

如果xml要灵活配置,使用mapperLocations属性定义

mapper.java

package ct.dao.mybatis;
import java.util.List;
import org.mybatis.spring.annotation.MapperScan;
import ct.bean.User;

@MapperScan
public interface IUserMapper {

	int createUser(User user);

	List<User> findAll();

	void update(User user);

	int delete(int id);
}


mapper.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="ct.dao.mybatis.IUserMapper">

	<insert id="createUser" keyProperty="id" useGeneratedKeys="true">
		insert
		into
		c_user(userName,password,description,status)
		values(#{userName},#{password},#{description},#{status})
	</insert>
	
	<sql id="user_col_list">
		p.id as u_id, p.userName as
		u_userName, p.password as u_password,p.description as u_description,p.status as u_status
	</sql>

	<resultMap type="ct.bean.User"
		id="UserMap">
		<result column="u_id" property="id" />
		<result column="u_userName" property="userName" />
		<result column="u_password" property="password" />
		<result column="u_description" property="description" />
		<result column="u_status" property="status" />
	</resultMap>

	<select id="findAll" resultMap="UserMap">
		select
		<include refid="user_col_list" />
		from c_user p
		
	</select>

	<update id="update">
		update c_user set
		userName=#{userName},
		password = #{password},
		description=#{description},
		status=#{status}
		where id = #{id}
	</update>

	<delete id="delete">
		delete from c_user
		where id = #{id}
	</delete>
</mapper>


3、jdbc参数化

<context:property-placeholder location="classpath:jdbc.properties" />在这个配置中,我们通过classpath引用了jdbc的属性文件。mybatis的数据源连接参数,都通过属性文件引入的参数配置

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://124.126.126.101/cdninfo
jdbc.username=cdn
jdbc.password=cdn


测试类

import java.security.SecureRandom;
import java.util.Random;


import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.testng.AssertJUnit;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;


import ct.bean.User;
import ct.service.IUserService;


public class CTServiceTest{
    
    private ApplicationContext context;
    private IUserService userService;
    
    @BeforeMethod
    public void setUp(){
        context = new ClassPathXmlApplicationContext("spring-mybatis.xml");
        userService = context.getBean(IUserService.class);
    }
    
    @AfterMethod
    public void tearDown(){
    	//userService.clear();
    }
    
    @Test
    public void testUserMaintain()
    {
        AssertJUnit.assertNotNull(userService);
        User user = new User();
        user.setUserName("testUser");
        user.setPassword("testPasswd");
        user.setDescription("description");
        userService.saveUser(user);
    }
}

使用testNG运行测试类。如果不报错,代表测试通过。

测试通过代表:1、找得到spring-mybatis的配置文件;2、可以扫描到bean和map;3、连接到数据库并且执行创建user通过;

PASSED: testTestProjectMaintain

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
===============================================


===============================================
Default suite
Total tests run: 1, Failures: 0, Skips: 0
===============================================
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部