最新Spring集成MyBatis详细教程(一)–ccw
小五游侠 2015/7/22 16:34:02
1. 如果你还没有spring的jar包,请先前往spring官网下载spring,附上下载地址 http://maven.springframework.org/release/org/springframework/spring/
在前往Mybatis的github地址下载MyBatis,下载地址为:https://github.com/mybatis/mybatis-3/releases
有需要也可以下载源代码,集成之后的jar包大致如下(别忘了 mybatis-spring.jar这个包):
由于这个项目在之前已经集成struts2,所以下面均已struts2开发方式来测试使用MyBatis.
2. 在spring配置文件中配置mybatis,在applicationContext.xml添加以下代码:(只供参考,具体配置还得已自己项目为准)
<?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:jee="http://www.springframework.org/schema/jee"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.0.xsd http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">
<!-- define the SqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="configLocation" value="classpath:mappings.xml" />
</bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate">
<constructor-arg index="0" ref="sqlSessionFactory" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.immortal.**.mybatis.dao" />
<property name="sqlSessionFactory" ref="sqlSessionFactory"></property>
</bean>
<!-- 事务管理器配置,单数据源事务 -->
<bean id="transactionManager_mybatis" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<aop:config>
<aop:pointcut expression="execution(* com.immortal..service.*.*(..))" id="txAop_mybatis" />
<aop:advisor advice-ref="txAdvice_mybatis" pointcut-ref="txAop_mybatis" />
</aop:config>
<tx:advice id="txAdvice_mybatis" transaction-manager="transactionManager_mybatis">
<tx:attributes>
<!-- 让所有的方法都加入事务管理,为了提高效率,可以把一些查询之类的方法设置为只读的事务 -->
<tx:method name="*" propagation="REQUIRED" read-only="true"/>
<!-- 添加 -->
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="submit*" propagation="REQUIRED" />
<!-- 更新 -->
<tx:method name="change*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<!-- 删除 -->
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="del*" propagation="REQUIRED" />
<!-- 移动 -->
<tx:method name="move*" propagation="REQUIRED" />
<!-- 复制 -->
<tx:method name="copy*" propagation="REQUIRED" />
<!-- 导入 -->
<tx:method name="import*" propagation="REQUIRED" />
<!-- 停止与激活 -->
<tx:method name="stop*" propagation="REQUIRED" />
<tx:method name="active*" propagation="REQUIRED" />
<!-- 执行 -->
<tx:method name="db*" propagation="REQUIRED" />
<tx:method name="execute*" propagation="REQUIRED" />
<!-- 发布 -->
<tx:method name="deploy*" propagation="REQUIRED" />
<!-- 取消 -->
<tx:method name="cancel*" propagation="REQUIRED" />
<!-- 批量操作 -->
<tx:method name="batch*" propagation="REQUIRED" />
<!-- 初始化操作 -->
<tx:method name="init*" propagation="REQUIRED" />
<!-- 同步操作 -->
<tx:method name="sync*" propagation="REQUIRED" />
<!-- 开始操作 -->
<tx:method name="start*" propagation="REQUIRED" />
<!-- 结束操作 -->
<tx:method name="end*" propagation="REQUIRED" />
<!-- 处理操作 -->
<tx:method name="process*" propagation="REQUIRED" />
<!-- 往下流转操作 -->
<tx:method name="next*" propagation="REQUIRED" />
<!-- 发送消息操作 -->
<tx:method name="send*" propagation="REQUIRED" />
<tx:method name="notify*" propagation="REQUIRED" />
</tx:attributes>
</tx:advice>
</beans>
如果你项目集成有hibernate,需配置两个数据源(需要注意mybatis貌似不能再properties文件读取数据,需要重新修改):
<!-- 加载数据库属性配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 数据库连接池c3p0配置 hibernate -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="jdbcUrl" value="${db.url}"></property>
<property name="driverClass" value="${db.driverClassName}"></property>
<property name="user" value="${db.username}"></property>
<property name="password" value="${db.password}"></property>
<property name="maxPoolSize" value="40"></property>
<property name="minPoolSize" value="1"></property>
<property name="initialPoolSize" value="1"></property>
<property name="maxIdleTime" value="20"></property>
</bean>
<!-- 数据库连接池c3p0配置 mybatis -->
<bean id="dataSource1" class="com.mchange.v2.c3p0.ComboPooledDataSource"
destroy-method="close">
<property name="jdbcUrl" value="jdbc:mysql://172.16.143.75:3306/test?seUnicode=tru;characterEncoding=UTF-8;zeroDateTimeBehavior=convertToNull"></property>
<property name="driverClass" value="com.mysql.jdbc.Driver"></property>
<property name="user" value="root"></property>
<property name="password" value="951489"></property>
<property name="maxPoolSize" value="40"></property>
<property name="minPoolSize" value="1"></property>
<property name="initialPoolSize" value="1"></property>
<property name="maxIdleTime" value="20"></property>
</bean>
在配置mybatis的配置文件,mappings.xml:
<?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="lazyLoadingEnabled" value="true" />
<setting name="cacheEnabled" value="false"/>
</settings>
<mappers>
<mapper resource="com/immortal/mybatis/dao/AdminDao.xml"/>
</mappers>
</configuration>
3. 基本环境到目前为止就搭建好了,剩下就写相关的代码了,首先是实体类:
/**
* Copyright (c) 2015
*
* Licensed under the CCW License, Version 1.0 (the "License");
*/
package com.immortal.main.admin.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.ForeignKey;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.hibernate.annotations.NotFound;
import org.hibernate.annotations.NotFoundAction;
import com.immortal.entity.Volunteerinfo;
import com.immortal.framework.entity.MyAdminEntity;
import com.immortal.framework.entity.MyUserEntity;
/**
* description :
*
* @version 1.0
* @author chencw
* @createtime : 2015年7月1日 下午2:37:30
*
* 修改历史:
* 修改人 修改时间 修改内容
* --------------- ------------------- -----------------------------------
* chencw2015年7月1日 下午2:37:30
*
*/
@Entity
@Table(name="fr_admin")
public class AdminEntity extends MyAdminEntity implements Serializable{
/**
* serialVersionUID
*/
private static final long serialVersionUID = 2015536289382768255L;
private String name;
private String password;
/**
* 是否锁定 0没有 1已锁定
*/
private Integer isLock;
/**
* 权限
*/
private String authority;
@Column(name="name",length=25,nullable=true)
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
@Column(name="password",length=55,nullable=true)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Column(name="isLock",length=2,nullable=true)
public Integer getIsLock() {
return isLock;
}
public void setIsLock(Integer isLock) {
this.isLock = isLock;
}
@Column(name="authority",length=5,nullable=true)
public String getAuthority() {
return authority;
}
public void setAuthority(String authority) {
this.authority = authority;
}
}
接口文件,AdminDao.java:
/**
* Copyright (c) 2015
*
* Licensed under the CCW License, Version 1.0 (the "License");
*/
package com.immortal.mybatis.dao;
import com.immortal.main.admin.entity.AdminEntity;
/**
* description :
*
* @version 1.0
* @author chencw
* @createtime : 2015年7月22日 下午5:37:04
*
* 修改历史: 修改人 修改时间 修改内容 --------------- -------------------
* ----------------------------------- chencw 2015年7月22日 下午5:37:04
*
*/
public interface AdminDao {
public AdminEntity getUser(AdminEntity a);
public void addAdminEntity(AdminEntity a);
public void updateAdminEntity(AdminEntity a);
public void deleteAdminEntity(int aid);
}
相对应上Dao的mybatis的xml文件,AdminDao.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="com.immortal.mybatis.dao">
<select id="getAdminEntity" parameterType="com.immortal.main.admin.entity.AdminEntity" resultType="com.immortal.main.admin.entity.AdminEntity">
SELECT * FROM fr_admin WHERE name=#{name} AND password=#{password}
</select>
<insert id="addAdminEntity" parameterType="com.immortal.main.admin.entity.AdminEntity" flushCache="true">
INSERT INTO fr_admin (name,password) VALUES (#{name},#{password})
</insert>
<update id="updateAdminEntity" parameterType="com.immortal.main.admin.entity.AdminEntity">
UPDATE fr_admin SET name=#{name} WHERE name=#{name}
</update>
<delete id="deleteAdminEntity" parameterType="int">
DELETE FROM fr_admin WHERE name=#{name}
</delete>
</mapper>
编写测试代码(部分):
@Resource
AdminDao adminDao;
public String testMybatis() {
AdminEntity adminEntity = new AdminEntity();
adminEntity.setName("ccw");
adminEntity.setPassword("ccw");
adminDao.addAdminEntity(adminEntity);
System.out.println("添加成功");
AdminEntity adminEntity2 = adminDao.getAdminEntityByName("ccw");
System.out.println("查找:"+adminEntity2.getName()+" 成功");
return SUCCESS;
}
最后部署运行:
恭喜你,集成成功了!!
版权声明:本文为博主原创文章,未经博主允许不得转载。