您的位置:首页 > 编程语言 > Java开发

spring整合mybatis

2014-06-26 20:50 316 查看
前段时间学习了下mybatis觉得还是挺强大的,也写了些代码,但是一直没时间整理,今天特地抽空把资料整理出来了准备和大家分享,大部分的代码都是参照API写出来的。大家随便看看

1.整合mybatis需要的spring版本

目前只有3.0以后的spring才支持mybatis,像2.5的版本就不行了

2.配置数据库连接池

<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <!-- DataSource -->
<bean id="dataSource" destroy-method="close"
class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName"
value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://localhost:3306/exercise?useUnicode=true&characterEncoding=UTF-8" />
<property name="username" value="root" />
<property name="password" value="aykjsa" />
<property name="maxWait"  value="9000" > </property>
<property name="maxActive"  value="500"> </property>
<property name="maxIdle"  value="10"> </property>
</bean>
</beans>


3.数据库会话和事务管理的相关配置

<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> 
<!-- <context:annotation-config /> <context:component-scan base-package="com.utsmart.huiju.framework.aop"/>
<aop:aspectj-autoproxy proxy-target-class="true"/> -->

<!-- 数据源相关配置 -->
<import resource="LocalSet.xml" />
<import resource="module.xml" />
<import resource="action.xml" />

<!-- sqlSessionFactory相关配置 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="configLocation" value="classpath:configuration.xml"></property>
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 事务管理 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>

</beans>


4. 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>
<typeAliases>
<!--给实体类起一个别名 user -->
<!-- <typeAlias type="org.lxh.vo.HealthspecialytypeInfo" alias="HealthType"/>  -->
</typeAliases>
<mappers>
<!-- AreaInfo -->
<mapper resource="org/lxh/sqlmap/AreaInfo_sqlmap.xml"/>
</mappers>
</configuration>


5.日志的相关配置

log4j.rootLogger=ERROR, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d %5p (%c:%L) - %m%n
log4j.logger.java.sql.PreparedStatement=DEBUG


6.模块的相关配置

<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd"> <bean id="areaManager" class="org.lxh.impl.AreaManager">
<property name="sqlSession" ref="sqlSession"/>
</bean>
</beans>


到这里基本上就结束了,为了让大家看的更明白,我把AreaManager这个类的代码贴出来

package org.lxh.impl;
import java.util.*;
import org.apache.ibatis.session.SqlSession;
import org.lxh.dao.IAreaManager;
import org.lxh.info.AreaInfo;

public class AreaManager implements IAreaManager {

private SqlSession sqlSession;

public SqlSession getSqlSession() {
return sqlSession;
}

public void setSqlSession(SqlSession sqlSession) {
this.sqlSession = sqlSession;
}

/*
* 根据城市id查询区域信息
*/
public List<AreaInfo> findByCityId(int id) {
List<AreaInfo> all = new ArrayList<AreaInfo>();
try {
all = sqlSession.selectList("AreaInfo.findByCityId", id);
} catch (Exception e) {
e.printStackTrace();
}

return all;
}

/*
* 生成区域信息
*/
public void createAreaInfo(AreaInfo info) {
try {
sqlSession.insert("AreaInfo.createAreaInfo", info);
} catch (Exception e) {
e.printStackTrace();
}
}

/*
* 动态查询区域信息
*/
public List<AreaInfo> findByCondition(AreaInfo info) {

List<AreaInfo> all = new ArrayList<AreaInfo>();
try {

all = sqlSession.selectList("AreaInfo.findByCondition", info);

} catch (Exception e) {
e.printStackTrace();
}

return all;
}

}


领域模型如下:

package org.lxh.info;

public class AreaInfo {
private Integer id;
private String code;
private String name;
private Integer cityId;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public Integer getCityId() {
return cityId;
}

public void setCityId(Integer cityId) {
this.cityId = cityId;
}
}


下面是最为重要的映射文件:

<?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="AreaInfo">
<sql id="sqlwhere">
<!-- <where></where> -->
<trim prefix="WHERE" prefixOverrides="AND">
<if test="id != null">
id = #{id}
</if>
<if test="code != null">
code = #{code}
</if>
<if test="name!= null">
name like #{name}
</if>
<if test="cityId!= null">
cityId = #{cityId}
</if>
</trim>
</sql>
<resultMap id="resultMap" type="org.lxh.info.AreaInfo">
<result property="id" column="id" />
<result property="code" column="code" />
<result property="name" column="name" />
<result property="cityId" column="cityId" />
</resultMap>
<select id="findByCityId" parameterType="int" resultMap="resultMap">
select * from m_area where cityId=#{cityId}
</select>
<insert id="createAreaInfo" parameterType="org.lxh.info.AreaInfo">
insert into m_area(id,code,name,
cityId)values(#{id},#{code},#{name,jdbcType=VARCHAR},#{cityId})
</insert>
<delete id="deleteAreaInfo" parameterType="int">
delete from m_area where id=#{id}
</delete>
<select id="findByCondition" parameterType="org.lxh.info.AreaInfo"
resultMap="resultMap">
select * from m_area
<include refid="sqlwhere" />
</select>
</mapper>


7 单元测试代码

package org.lxh.junit;

import static org.junit.Assert.*;

import java.io.InputStream;
import java.util.*;

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 org.lxh.dao.AreaMapper;
import org.lxh.dao.IAreaManager;
import org.lxh.impl.AreaManager;
import org.lxh.info.AreaInfo;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class TestAll {

ApplicationContext context=new ClassPathXmlApplicationContext("applicationContext.xml");
@Test
public void testQuery() {
AreaManager m=(AreaManager)context.getBean("areaManager");
List<AreaInfo> all=m.findByCityId(5);
Iterator<AreaInfo> it=all.iterator();
while(it.hasNext()){
AreaInfo info=it.next();
System.out.println(info.getCode()+","+info.getName());
}
}
@Test
public void testInsert() {

AreaManager m=(AreaManager)context.getBean("areaManager");
AreaInfo area=new AreaInfo();
area.setCityId(5);
area.setCode("js2");
area.setName("金山2");
m.createAreaInfo(area);
}
@Test
public void testDel() {
String resource = "DataSource.xml";
InputStream inputStream;
try {
inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
SqlSession ses=sqlSessionFactory.openSession();
AreaMapper mapp=ses.getMapper(AreaMapper.class);
mapp.deleteAreaInfo(11);
ses.commit();
ses.close();
} catch (Exception e) {
e.printStackTrace();
}
}
@Test
public void testQueryByCondition() {
AreaManager m=(AreaManager)context.getBean("areaManager");
AreaInfo info=new AreaInfo();
info.setName("%行%");
List<AreaInfo> all=m.findByCondition(info);
Iterator<AreaInfo> it=all.iterator();
while(it.hasNext()){
AreaInfo ainfo=it.next();
System.out.println(ainfo.getCode()+","+ainfo.getName());
}
}
}




如果这篇文章看着比较吃力的话,建议看一下mybatis的API.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: