第四章:Dubbo整合maven+spring+springmvc+mybatis之mybatis集成

来源:互联网 发布:阿里云是什么 编辑:程序博客网 时间:2024/05/24 02:12

接上三篇博文,继续。。。

1、ivan-dubbo-server增加spring-mybatis.xml配置文件(注意:在dubbo与mybatis全注解集成时,配置spring事务无法发布服务,目前没有找到解决方案,见配置文件最后aop的配置注解):

[html] view plain copy
 print?
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xsi:schemaLocation="  
  6.         http://www.springframework.org/schema/beans   
  7.         http://www.springframework.org/schema/beans/spring-beans-4.1.xsd   
  8.         http://www.springframework.org/schema/tx   
  9.         http://www.springframework.org/schema/tx/spring-tx-4.1.xsd  
  10.         http://www.springframework.org/schema/aop   
  11.         http://www.springframework.org/schema/aop/spring-aop-4.1.xsd  
  12.         ">  
  13.   
  14.     <!-- <context:property-placeholder location="classpath:jdbc.properties"/> -->  
  15.     <!-- 配置数据源 使用的是Druid数据源 -->  
  16.     <bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"  
  17.         init-method="init" destroy-method="close">  
  18.         <property name="url" value="${jdbc.url}" />  
  19.         <property name="username" value="${jdbc.username}" />  
  20.         <property name="password" value="${jdbc.password}" />  
  21.   
  22.         <!-- 初始化连接大小 -->  
  23.         <property name="initialSize" value="0" />  
  24.         <!-- 连接池最大使用连接数量 -->  
  25.         <property name="maxActive" value="20" />  
  26.   
  27.         <!-- 连接池最小空闲 -->  
  28.         <property name="minIdle" value="0" />  
  29.         <!-- 获取连接最大等待时间 -->  
  30.         <property name="maxWait" value="60000" />  
  31.         <property name="poolPreparedStatements" value="true" />  
  32.         <property name="maxPoolPreparedStatementPerConnectionSize"  
  33.             value="33" />  
  34.         <!-- 用来检测有效sql -->  
  35.         <property name="validationQuery" value="${validationQuery}" />  
  36.         <property name="testOnBorrow" value="false" />  
  37.         <property name="testOnReturn" value="false" />  
  38.         <property name="testWhileIdle" value="true" />  
  39.         <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->  
  40.         <property name="timeBetweenEvictionRunsMillis" value="60000" />  
  41.         <!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->  
  42.         <property name="minEvictableIdleTimeMillis" value="25200000" />  
  43.         <!-- 打开removeAbandoned功能 -->  
  44.         <property name="removeAbandoned" value="true" />  
  45.         <!-- 1800秒,也就是30分钟 -->  
  46.         <property name="removeAbandonedTimeout" value="1800" />  
  47.         <!-- 关闭abanded连接时输出错误日志 -->  
  48.         <property name="logAbandoned" value="true" />  
  49.         <!-- 监控数据库 -->  
  50.         <property name="filters" value="mergeStat" />  
  51.     </bean>  
  52.   
  53.     <!-- myBatis文件 -->  
  54.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  55.         <property name="dataSource" ref="dataSource" />  
  56.         <!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->  
  57.         <property name="mapperLocations" value="classpath:com/ivan/**/mapping/*.xml" />  
  58.     </bean>  
  59.   
  60.     <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">  
  61.         <property name="basePackage" value="com.ivan.*.dao" />  
  62.         <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />  
  63.     </bean>  
  64.   
  65.     <!-- 配置事务管理器 -->  
  66.     <bean id="transactionManager"  
  67.         class="org.springframework.jdbc.datasource.DataSourceTransactionManager">  
  68.         <property name="dataSource" ref="dataSource" />  
  69.     </bean>  
  70.   
  71.     <!-- 注解方式配置事物 -->  
  72.     <!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->  
  73.   
  74.     <!-- 拦截器方式配置事物 -->  
  75.     <tx:advice id="transactionAdvice" transaction-manager="transactionManager">  
  76.         <tx:attributes>  
  77.             <tx:method name="insert*" propagation="REQUIRED" />  
  78.             <tx:method name="update*" propagation="REQUIRED" />  
  79.             <tx:method name="delete*" propagation="REQUIRED" />  
  80.   
  81.             <tx:method name="get*" propagation="SUPPORTS" read-only="true" />  
  82.             <tx:method name="find*" propagation="SUPPORTS" read-only="true" />  
  83.             <tx:method name="select*" propagation="SUPPORTS" read-only="true" />  
  84.   
  85.         </tx:attributes>  
  86.     </tx:advice>  
  87.     <!--   
  88. <span style="font-family:FangSong_GB2312;">             </span>Spring aop事务管理  
  89. <span style="font-family:FangSong_GB2312;">             此处配置正确无法发布提供者服务,目前没找到解决方案</span>  
  90.   
  91.          -->  
  92.     <!-- <aop:config>  
  93.         <aop:pointcut id="transactionPointcut"  expression="execution(* com.ivan..service.impl.*Impl.*(..))" />  
  94.         <aop:advisor advice-ref="transactionAdvice" pointcut-ref="transactionPointcut"/>  
  95.     </aop:config> -->  
  96.   
  97. </beans>  

2、ivan-dubbo-server工程增加jdbc.properties配置文件,根据自身配置修改,注意此配置文件的引用在spring-registry,xml中:

[html] view plain copy
 print?
  1. #mysql version database druid setting  
  2. validationQuery=SELECT 1  
  3. jdbc.url=jdbc:mysql://localhost:3306/ivan?useUnicode=true&characterEncoding=utf-8  
  4. jdbc.username=root  
  5. jdbc.password=  

3、ivan-dubbo-server工程中的spring-registry,xml引入本地配置文件jdbc.properties :

[html] view plain copy
 print?
  1. <bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
  2.         <property name="locations">  
  3.             <list>  
  4.                 <value>classpath:zookeeper.properties</value>  
  5.                 <value>classpath:jdbc.properties</value>  
  6.             </list>  
  7.         </property>  
  8.     </bean>  

4、在ivan-dubbo-server工程中创建dao接口UserMapper,此处我是采用generator自动生成的dao、mapping、entity,关于generator的配置详解请点击这里

[java] view plain copy
 print?
  1. import java.util.List;  
  2.   
  3. import com.ivan.entity.User;  
  4.   
  5. public interface UserMapper {  
  6.     int deleteByPrimaryKey(Integer id);  
  7.   
  8.     int insert(User record);  
  9.   
  10.     int insertSelective(User record);  
  11.   
  12.     User selectByPrimaryKey(Integer id);  
  13.   
  14.     int updateByPrimaryKeySelective(User record);  
  15.   
  16.     int updateByPrimaryKey(User record);  
  17.   
  18.     List<User> selectAll();  
  19. }  

5、在ivan-dubbo-server工程中创建实体映射文件UserMapping.xml,注意修改自己的包名

[html] view plain copy
 print?
  1. <?xml version="1.0" encoding="UTF-8" ?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >  
  3. <mapper namespace="com.ivan.dubbo.dao.UserMapper" >  
  4.   <resultMap id="BaseResultMap" type="com.ivan.entity.User" >  
  5.     <id column="id" property="id" jdbcType="INTEGER" />  
  6.     <result column="name" property="name" jdbcType="VARCHAR" />  
  7.     <result column="age" property="age" jdbcType="INTEGER" />  
  8.   </resultMap>  
  9.   <sql id="Base_Column_List" >  
  10.     id, name, age  
  11.   </sql>  
  12.     
  13.   <select id="selectAll" resultMap="BaseResultMap">  
  14.     select  
  15.     <include refid="Base_Column_List" />  
  16.     from user  
  17.   </select>  
  18.     
  19.   <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >  
  20.     select   
  21.     <include refid="Base_Column_List" />  
  22.     from user  
  23.     where id = #{id,jdbcType=INTEGER}  
  24.   </select>  
  25.   <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >  
  26.     delete from user  
  27.     where id = #{id,jdbcType=INTEGER}  
  28.   </delete>  
  29.   <insert id="insert" parameterType="com.ivan.entity.User" >  
  30.     insert into user (id, name, age  
  31.       )  
  32.     values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}  
  33.       )  
  34.   </insert>  
  35.   <insert id="insertSelective" parameterType="com.ivan.entity.User" >  
  36.     insert into user  
  37.     <trim prefix="(" suffix=")" suffixOverrides="," >  
  38.       <if test="id != null" >  
  39.         id,  
  40.       </if>  
  41.       <if test="name != null" >  
  42.         name,  
  43.       </if>  
  44.       <if test="age != null" >  
  45.         age,  
  46.       </if>  
  47.     </trim>  
  48.     <trim prefix="values (" suffix=")" suffixOverrides="," >  
  49.       <if test="id != null" >  
  50.         #{id,jdbcType=INTEGER},  
  51.       </if>  
  52.       <if test="name != null" >  
  53.         #{name,jdbcType=VARCHAR},  
  54.       </if>  
  55.       <if test="age != null" >  
  56.         #{age,jdbcType=INTEGER},  
  57.       </if>  
  58.     </trim>  
  59.   </insert>  
  60.   <update id="updateByPrimaryKeySelective" parameterType="com.ivan.entity.User" >  
  61.     update user  
  62.     <set >  
  63.       <if test="name != null" >  
  64.         name = #{name,jdbcType=VARCHAR},  
  65.       </if>  
  66.       <if test="age != null" >  
  67.         age = #{age,jdbcType=INTEGER},  
  68.       </if>  
  69.     </set>  
  70.     where id = #{id,jdbcType=INTEGER}  
  71.   </update>  
  72.   <update id="updateByPrimaryKey" parameterType="com.ivan.entity.User" >  
  73.     update user  
  74.     set name = #{name,jdbcType=VARCHAR},  
  75.       age = #{age,jdbcType=INTEGER}  
  76.     where id = #{id,jdbcType=INTEGER}  
  77.   </update>  
  78. </mapper>  

6、在ivan-entity中创建实体User ,需要注意的是使用generator生成实体,不会实现Serializable,需要手动加入,否则dubbo调用时会报错

[java] view plain copy
 print?
  1. import java.io.Serializable;  
  2.   
  3. @SuppressWarnings("serial")  
  4. public class User implements Serializable{  
  5.     private Integer id;  
  6.   
  7.     private String name;  
  8.   
  9.     private Integer age;  
  10.       
  11.     public User(){};  
  12.       
  13.     public User(Integer id,String name,Integer age){  
  14.         this.id = id;  
  15.         this.name = name;  
  16.         this.age = age;  
  17.     }  
  18.   
  19.     public Integer getId() {  
  20.         return id;  
  21.     }  
  22.   
  23.     public void setId(Integer id) {  
  24.         this.id = id;  
  25.     }  
  26.   
  27.     public String getName() {  
  28.         return name;  
  29.     }  
  30.   
  31.     public void setName(String name) {  
  32.         this.name = name == null ? null : name.trim();  
  33.     }  
  34.   
  35.     public Integer getAge() {  
  36.         return age;  
  37.     }  
  38.   
  39.     public void setAge(Integer age) {  
  40.         this.age = age;  
  41.     }  
  42. }  

7、在ivan-api工程中修改原有接口类UserService,可以直接把dao接口UserMapper中的方法完全拷贝过来就行

[java] view plain copy
 print?
  1. import java.util.List;  
  2.   
  3. import com.ivan.entity.User;  
  4.   
  5. public interface UserService {  
  6.   
  7.     int deleteByPrimaryKey(Integer id);  
  8.   
  9.     int insert(User record);  
  10.   
  11.     int insertSelective(User record);  
  12.   
  13.     User selectByPrimaryKey(Integer id);  
  14.   
  15.     int updateByPrimaryKeySelective(User record);  
  16.   
  17.     int updateByPrimaryKey(User record);  
  18.       
  19.     //自定义  
  20.     List<User> getUsers();  
  21. }  

8、在ivan-dubbo-server工程实现UserService接口,并使用@Autowired自动注入dao接口UserMapper

[java] view plain copy
 print?
  1. import java.util.List;  
  2.   
  3. import org.slf4j.Logger;  
  4. import org.slf4j.LoggerFactory;  
  5. import org.springframework.beans.factory.annotation.Autowired;  
  6.   
  7. import com.alibaba.dubbo.common.json.JSON;  
  8. import com.alibaba.dubbo.config.annotation.Service;  
  9. import com.ivan.api.dubbo.UserService;  
  10. import com.ivan.dubbo.dao.UserMapper;  
  11. import com.ivan.entity.User;  
  12.   
  13. @Service  
  14. public class UserServiceImpl implements UserService {  
  15.   
  16.     private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);  
  17.       
  18.     @Autowired  
  19.     private UserMapper userMapper;  
  20.       
  21.     public int insert(User record){  
  22.         return userMapper.insert(record);  
  23.     }  
  24.   
  25.       public int insertSelective(User record){  
  26.         return userMapper.insertSelective(record);  
  27.     }  
  28.     //需要自己定义Mapper文件中的方法  
  29.     public List<User> getUsers() {  
  30.         logger.info("开始查询所有用户信息");  
  31.           
  32.         logger.info("查询结束");  
  33.         return userMapper.selectAll();  
  34.     }  
  35.   
  36.     public int deleteByPrimaryKey(Integer id) {  
  37.         return userMapper.deleteByPrimaryKey(id);  
  38.     }  
  39.   
  40.     public User selectByPrimaryKey(Integer id) {  
  41.         return userMapper.selectByPrimaryKey(id);  
  42.     }  
  43.   
  44.     public int updateByPrimaryKeySelective(User record) {  
  45.         return userMapper.updateByPrimaryKeySelective(record);  
  46.     }  
  47.   
  48.     public int updateByPrimaryKey(User record) {  
  49.         return userMapper.updateByPrimaryKey(record);  
  50.     }  
  51.   
  52. }  


9、ivan-dubbo-server启动类ServerMain中增加加载spring-mybatis.xml的代码

[java] view plain copy
 print?
  1. import java.io.IOException;  
  2.   
  3. import org.springframework.context.support.ClassPathXmlApplicationContext;  
  4.   
  5. public class ServerMain {  
  6.       
  7.     public static void main(String[] args) throws IOException {  
  8.         ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(  
  9.                 new String[] { "spring-registry.xml","spring-mybatis.xml"});  
  10.         context.start();  
  11.   
  12.         System.in.read(); // 按任意键退出  
  13.     }  
  14. }  

到这里后台就准备完毕了,启动ivan-dubbo-server工程中的main函数ServerMain,来启动后台。


10、在前台工程ivan-dubbo-web中修改controller类UserController

[java] view plain copy
 print?
  1. import java.util.List;  
  2.   
  3. import org.slf4j.Logger;  
  4. import org.slf4j.LoggerFactory;  
  5. import org.springframework.stereotype.Controller;  
  6. import org.springframework.web.bind.annotation.RequestMapping;  
  7. import org.springframework.web.bind.annotation.ResponseBody;  
  8.   
  9. import com.alibaba.dubbo.config.annotation.Reference;  
  10. import com.ivan.api.dubbo.UserService;  
  11. import com.ivan.entity.User;  
  12.   
  13. /** 
  14.  * @author ivan 
  15.  * 
  16.  */  
  17. @Controller  
  18. @RequestMapping("/user")  
  19. public class UserController {  
  20.       
  21.     @SuppressWarnings("unused")  
  22.     private static final Logger logger = LoggerFactory.getLogger(UserController.class);  
  23.       
  24.     @Reference  
  25.     private UserService userService;  
  26.     /** 
  27.      * 主页面跳转 
  28.      * @return index.jsp 
  29.      */  
  30.     @RequestMapping("/")  
  31.     public String goIndex(){  
  32.         return "index";  
  33.     }  
  34.     /** 
  35.      * 新增user 
  36.      */  
  37.     @RequestMapping("/insert")  
  38.     @ResponseBody  
  39.     public List<User> insert(){  
  40.         User user = new User(1,"jack",18);  
  41.         userService.insert(user);  
  42.         return getUsers();  
  43.     }  
  44.     /** 
  45.      * 按条件新增user 
  46.      */  
  47.     @RequestMapping("/insertSelective")  
  48.     @ResponseBody  
  49.     public List<User> insertSelective(){  
  50.         User user = new User(2,"ivan",25);  
  51.         userService.insertSelective(user);  
  52.         return getUsers();  
  53.     }  
  54.       
  55.     /** 
  56.      * 查询所有用户 
  57.      */  
  58.     @RequestMapping("/list")  
  59.     @ResponseBody  
  60.     public List<User> getUsers(){  
  61.         return userService.getUsers();  
  62.     }  
  63.       
  64.     /** 
  65.      *根据id获取user 
  66.      *@param 用户id 
  67.      */  
  68.     @RequestMapping("/one")  
  69.     @ResponseBody  
  70.     public User getUserById(String id){  
  71.         return userService.selectByPrimaryKey(Integer.valueOf(id));  
  72.     }  
  73.       
  74.     /** 
  75.      *根据id删除user 
  76.      *@param 用户id 
  77.      */  
  78.     @RequestMapping("/delete")  
  79.     @ResponseBody  
  80.     public List<User> deleteUserById(String id){  
  81.         userService.deleteByPrimaryKey(Integer.valueOf(id));  
  82.         return getUsers();  
  83.     }  
  84.       
  85.     /** 
  86.      *根据id更新user 
  87.      *@param 用户id 
  88.      */  
  89.     @RequestMapping("/updateById")  
  90.     @ResponseBody  
  91.     public User updateUserById(String id){  
  92.         User user = new User(Integer.valueOf(id),"ivan",30);  
  93.         userService.updateByPrimaryKey(user);  
  94.         return userService.selectByPrimaryKey(Integer.valueOf(id));  
  95.     }  
  96. }  

启动tomcat,访问以下路径即可严重是否搭建成功:

1、http://127.0.0.1:8080/ivan-dubbo-web/user/insert/  向数据库中插入user:id:1 , name:jack , 年龄:18

2、http://127.0.0.1:8080/ivan-dubbo-web/user/insertSelective/  向数据库插入user: id:2 , name:ivan2 ,年龄:25

3、http://127.0.0.1:8080/ivan-dubbo-web/user/list/    查询数据中所有user 如按照顺序执行1、2步骤,浏览器应该返回 : [{"id":1,"name":"jack","age":18},{"id":2,"name":"ivan","age":25}]

4、http://127.0.0.1:8080/ivan-dubbo-web/user/one/?id=1 查询id为1的用户,浏览器返回:{"id":1,"name":"jack","age":18}

5、http://127.0.0.1:8080/ivan-dubbo-web/user/delete/?id=1 删除id为1的用户,浏览器返回删除后数据库中所有的用户

6、http://127.0.0.1:8080/ivan-dubbo-web/user/updateById/?id=1 更新id为1的用户,浏览器返回更新后所有数据库用户


附上数据表结构的sql

[sql] view plain copy
 print?
  1. /*  
  2. Navicat MySQL Data Transfer  
  3.   
  4. Source Server         : 127.0.0.1  
  5. Source Server Version : 50627  
  6. Source Host           : localhost:3306  
  7. Source Database       : ivan  
  8.   
  9. Target Server Type    : MYSQL  
  10. Target Server Version : 50627  
  11. File Encoding         : 65001  
  12.   
  13. Date: 2015-11-13 11:19:18  
  14. */  
  15.   
  16. SET FOREIGN_KEY_CHECKS=0;  
  17.   
  18. -- ----------------------------  
  19. -- Table structure for user  
  20. -- ----------------------------  
  21. DROP TABLE IF EXISTS `user`;  
  22. CREATE TABLE `user` (  
  23.   `id` int(11) NOT NULL,  
  24.   `namevarchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,  
  25.   `age` int(11) DEFAULT NULL,  
  26.   PRIMARY KEY (`id`)  
  27. ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;  

至此就整合完毕了,接下来研究点啥捏?

0 0
原创粉丝点击