接上三篇博文,继续。。。(2016.11.23更新)
1、ivan-dubbo-server增加spring-mybatis.xml配置文件(注意:在dubbo与mybatis全注解集成时,配置spring事务无法发布服务,目前没有找到解决方案,见配置文件最后aop的配置注解):
<?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:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.1.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.1.xsd
">
<!-- <context:property-placeholder location="classpath:jdbc.properties"/> -->
<!-- 配置数据源 使用的是Druid数据源 -->
<bean name="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 初始化连接大小 -->
<property name="initialSize" value="0" />
<!-- 连接池最大使用连接数量 -->
<property name="maxActive" value="20" />
<!-- 连接池最小空闲 -->
<property name="minIdle" value="0" />
<!-- 获取连接最大等待时间 -->
<property name="maxWait" value="60000" />
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize"
value="33" />
<!-- 用来检测有效sql -->
<property name="validationQuery" value="${validationQuery}" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="testWhileIdle" value="true" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="25200000" />
<!-- 打开removeAbandoned功能 -->
<property name="removeAbandoned" value="true" />
<!-- 1800秒,也就是30分钟 -->
<property name="removeAbandonedTimeout" value="1800" />
<!-- 关闭abanded连接时输出错误日志 -->
<property name="logAbandoned" value="true" />
<!-- 监控数据库 -->
<property name="filters" value="mergeStat" />
</bean>
<!-- myBatis文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 自动扫描entity目录, 省掉Configuration.xml里的手工配置 -->
<property name="mapperLocations" value="classpath:com/ivan/**/mapping/*.xml" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ivan.*.dao" />
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 注解方式配置事物 -->
<!-- <tx:annotation-driven transaction-manager="transactionManager" /> -->
<!-- 拦截器方式配置事物 -->
<tx:advice id="transactionAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
<tx:method name="select*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<!--
<span style="font-family:FangSong_GB2312;"> </span>Spring aop事务管理
<span style="font-family:FangSong_GB2312;"> 此处配置正确无法发布提供者服务,目前没找到解决方案</span>
-->
<!-- <aop:config>
<aop:pointcut id="transactionPointcut" expression="execution(* com.ivan..service.impl.*Impl.*(..))" />
<aop:advisor advice-ref="transactionAdvice" pointcut-ref="transactionPointcut"/>
</aop:config> -->
</beans>
2、ivan-dubbo-server工程增加jdbc.properties配置文件,根据自身配置修改,注意此配置文件的引用在spring-registry,xml中:
#mysql version database druid setting
validationQuery=SELECT 1
jdbc.url=jdbc:mysql://localhost:3306/ivan?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=
3、ivan-dubbo-server工程中的 spring-registry,xml引入本地配置文件 jdbc.properties :
<bean class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath:zookeeper.properties</value>
<value>classpath:jdbc.properties</value>
</list>
</property>
</bean>
4、在ivan-dubbo-server工程中创建dao接口UserMapper,此处我是采用generator自动生成的dao、mapping、entity,关于 generator的配置详解请点击 这里
import java.util.List;
import com.ivan.entity.User;
public interface UserMapper {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
List<User> selectAll();
}
5、在ivan-dubbo-server工程中创建实体映射文件UserMapping.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.ivan.dubbo.dao.UserMapper" >
<resultMap id="BaseResultMap" type="com.ivan.entity.User" >
<id column="id" property="id" jdbcType="INTEGER" />
<result column="name" property="name" jdbcType="VARCHAR" />
<result column="age" property="age" jdbcType="INTEGER" />
</resultMap>
<sql id="Base_Column_List" >
id, name, age
</sql>
<select id="selectAll" resultMap="BaseResultMap">
select
<include refid="Base_Column_List" />
from user
</select>
<select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" >
select
<include refid="Base_Column_List" />
from user
where id = #{id,jdbcType=INTEGER}
</select>
<delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" >
delete from user
where id = #{id,jdbcType=INTEGER}
</delete>
<insert id="insert" parameterType="com.ivan.entity.User" >
insert into user (id, name, age
)
values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{age,jdbcType=INTEGER}
)
</insert>
<insert id="insertSelective" parameterType="com.ivan.entity.User" >
insert into user
<trim prefix="(" suffix=")" suffixOverrides="," >
<if test="id != null" >
id,
</if>
<if test="name != null" >
name,
</if>
<if test="age != null" >
age,
</if>
</trim>
<trim prefix="values (" suffix=")" suffixOverrides="," >
<if test="id != null" >
#{id,jdbcType=INTEGER},
</if>
<if test="name != null" >
#{name,jdbcType=VARCHAR},
</if>
<if test="age != null" >
#{age,jdbcType=INTEGER},
</if>
</trim>
</insert>
<update id="updateByPrimaryKeySelective" parameterType="com.ivan.entity.User" >
update user
<set >
<if test="name != null" >
name = #{name,jdbcType=VARCHAR},
</if>
<if test="age != null" >
age = #{age,jdbcType=INTEGER},
</if>
</set>
where id = #{id,jdbcType=INTEGER}
</update>
<update id="updateByPrimaryKey" parameterType="com.ivan.entity.User" >
update user
set name = #{name,jdbcType=VARCHAR},
age = #{age,jdbcType=INTEGER}
where id = #{id,jdbcType=INTEGER}
</update>
</mapper>
6、在ivan-entity中创建实体User ,需要注意的是使用 generator生成实体,不会实现Serializable,需要手动加入,否则dubbo调用时会报错
import java.io.Serializable;
@SuppressWarnings("serial")
public class User implements Serializable{
private Integer id;
private String name;
private Integer age;
public User(){};
public User(Integer id,String name,Integer age){
this.id = id;
this.name = name;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
7、在ivan-api工程中修改原有接口类UserService,可以直接把dao接口UserMapper中的方法完全拷贝过来就行
import java.util.List;
import com.ivan.entity.User;
public interface UserService {
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
//自定义
List<User> getUsers();
}
8、在ivan-dubbo-server工程实现UserService接口,并使用@Autowired自动注入dao接口UserMapper
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.alibaba.dubbo.common.json.JSON;
import com.alibaba.dubbo.config.annotation.Service;
import com.ivan.api.dubbo.UserService;
import com.ivan.dubbo.dao.UserMapper;
import com.ivan.entity.User;
@Service
public class UserServiceImpl implements UserService {
private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);
@Autowired
private UserMapper userMapper;
public int insert(User record){
return userMapper.insert(record);
}
public int insertSelective(User record){
return userMapper.insertSelective(record);
}
//需要自己定义Mapper文件中的方法
public List<User> getUsers() {
logger.info("开始查询所有用户信息");
logger.info("查询结束");
return userMapper.selectAll();
}
public int deleteByPrimaryKey(Integer id) {
return userMapper.deleteByPrimaryKey(id);
}
public User selectByPrimaryKey(Integer id) {
return userMapper.selectByPrimaryKey(id);
}
public int updateByPrimaryKeySelective(User record) {
return userMapper.updateByPrimaryKeySelective(record);
}
public int updateByPrimaryKey(User record) {
return userMapper.updateByPrimaryKey(record);
}
}
9、ivan-dubbo-server启动类ServerMain中增加加载spring-mybatis.xml的代码
import java.io.IOException;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class ServerMain {
public static void main(String[] args) throws IOException {
ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext(
new String[] { "spring-registry.xml","spring-mybatis.xml"});
context.start();
System.in.read(); // 按任意键退出
}
}
到这里后台就准备完毕了,启动ivan-dubbo-server工程中的main函数ServerMain,来启动后台。
10、在前台工程ivan-dubbo-web中修改controller类UserController
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.alibaba.dubbo.config.annotation.Reference;
import com.ivan.api.dubbo.UserService;
import com.ivan.entity.User;
/**
* @author ivan
*
*/
@Controller
@RequestMapping("/user")
public class UserController {
@SuppressWarnings("unused")
private static final Logger logger = LoggerFactory.getLogger(UserController.class);
@Reference
private UserService userService;
/**
* 主页面跳转
* @return index.jsp
*/
@RequestMapping("/")
public String goIndex(){
return "index";
}
/**
* 新增user
*/
@RequestMapping("/insert")
@ResponseBody
public List<User> insert(){
User user = new User(1,"jack",18);
userService.insert(user);
return getUsers();
}
/**
* 按条件新增user
*/
@RequestMapping("/insertSelective")
@ResponseBody
public List<User> insertSelective(){
User user = new User(2,"ivan",25);
userService.insertSelective(user);
return getUsers();
}
/**
* 查询所有用户
*/
@RequestMapping("/list")
@ResponseBody
public List<User> getUsers(){
return userService.getUsers();
}
/**
*根据id获取user
*@param 用户id
*/
@RequestMapping("/one")
@ResponseBody
public User getUserById(String id){
return userService.selectByPrimaryKey(Integer.valueOf(id));
}
/**
*根据id删除user
*@param 用户id
*/
@RequestMapping("/delete")
@ResponseBody
public List<User> deleteUserById(String id){
userService.deleteByPrimaryKey(Integer.valueOf(id));
return getUsers();
}
/**
*根据id更新user
*@param 用户id
*/
@RequestMapping("/updateById")
@ResponseBody
public User updateUserById(String id){
User user = new User(Integer.valueOf(id),"ivan",30);
userService.updateByPrimaryKey(user);
return userService.selectByPrimaryKey(Integer.valueOf(id));
}
}
启动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
/*
Navicat MySQL Data Transfer
Source Server : 127.0.0.1
Source Server Version : 50627
Source Host : localhost:3306
Source Database : ivan
Target Server Type : MYSQL
Target Server Version : 50627
File Encoding : 65001
Date: 2015-11-13 11:19:18
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for user
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`id` int(11) NOT NULL,
`name` varchar(255) COLLATE utf8_unicode_ci DEFAULT NULL,
`age` int(11) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;
至此就整合完毕了,接下来研究点啥捏?