设为首页 收藏本站
查看: 1147|回复: 0

[经验分享] 最新Spring集成MyBatis详细教程(一)--ccw

[复制链接]

尚未签到

发表于 2016-11-27 07:52:38 | 显示全部楼层 |阅读模式
最新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这个包):
DSC0000.png

  由于这个项目在之前已经集成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;
}

  最后部署运行:
DSC0001.png

  恭喜你,集成成功了!!



<script type="text/javascript">
$(function () {
$('pre.prettyprint code').each(function () {
var lines = $(this).text().split('\n').length;
var $numbering = $('<ul/>').addClass('pre-numbering').hide();
$(this).addClass('has-numbering').parent().append($numbering);
for (i = 1; i <= lines; i++) {
$numbering.append($('<li/>').text(i));
};
$numbering.fadeIn(1700);
});
});
</script>         
版权声明:本文为博主原创文章,未经博主允许不得转载。

运维网声明 1、欢迎大家加入本站运维交流群:群②:261659950 群⑤:202807635 群⑦870801961 群⑧679858003
2、本站所有主题由该帖子作者发表,该帖子作者与运维网享有帖子相关版权
3、所有作品的著作权均归原作者享有,请您和我们一样尊重他人的著作权等合法权益。如果您对作品感到满意,请购买正版
4、禁止制作、复制、发布和传播具有反动、淫秽、色情、暴力、凶杀等内容的信息,一经发现立即删除。若您因此触犯法律,一切后果自负,我们对此不承担任何责任
5、所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其内容的准确性、可靠性、正当性、安全性、合法性等负责,亦不承担任何法律责任
6、所有作品仅供您个人学习、研究或欣赏,不得用于商业或者其他用途,否则,一切后果均由您自己承担,我们对此不承担任何法律责任
7、如涉及侵犯版权等问题,请您及时通知我们,我们将立即采取措施予以解决
8、联系人Email:admin@iyunv.com 网址:www.yunweiku.com

所有资源均系网友上传或者通过网络收集,我们仅提供一个展示、介绍、观摩学习的平台,我们不对其承担任何法律责任,如涉及侵犯版权等问题,请您及时通知我们,我们将立即处理,联系人Email:kefu@iyunv.com,QQ:1061981298 本贴地址:https://www.yunweiku.com/thread-305939-1-1.html 上篇帖子: mybatis 和 spring 整合事务管理 下篇帖子: Mybatis系列之实战篇(中)
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

扫码加入运维网微信交流群X

扫码加入运维网微信交流群

扫描二维码加入运维网微信交流群,最新一手资源尽在官方微信交流群!快快加入我们吧...

扫描微信二维码查看详情

客服E-mail:kefu@iyunv.com 客服QQ:1061981298


QQ群⑦:运维网交流群⑦ QQ群⑧:运维网交流群⑧ k8s群:运维网kubernetes交流群


提醒:禁止发布任何违反国家法律、法规的言论与图片等内容;本站内容均来自个人观点与网络等信息,非本站认同之观点.


本站大部分资源是网友从网上搜集分享而来,其版权均归原作者及其网站所有,我们尊重他人的合法权益,如有内容侵犯您的合法权益,请及时与我们联系进行核实删除!



合作伙伴: 青云cloud

快速回复 返回顶部 返回列表