前段時間學習了下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.