毕业开始工作了,在学校时候学的C++,工作需要Java,无奈还要学各种框架前两天看了看书,从网上学习了一下,搭建了这个框架,用于自己学习。也可以用于Spring+mybatis的集成
搭建框架最烦人的地方就是无数的包依赖以及配置文件的编写,下面即是项目的具体框架以及依赖的包(PS:也许不是全部依赖,懒人可以直接把Spring\libs下的所有相关jar都加载进来),这些包基本都可以在Maven仓库中找到:http://search.maven.org/
一、创建数据库并插入数据
本框架是用的mysql数据库,如果使用其他数据库需更改的文件是spring.xml中的数据源配置,以及dbconfig.properties中的键值对,以及相应的connector.jar文件
create table t_user( user_id varchar(32) primary key, user_name varchar(30) not null, user_birthday Date, user_salary double ) INSERT INTO t_user1 values('041bbae5f3f84c38938980c4b3f03a29','adiaixin','2015-4-25',15000)
二、创建项目目录,以及文件
1.com.wangyin.domain.User.java
此类为实体类,用于与数据映射的返回类型
package com.wangyin.domain; import java.io.Serializable; import java.util.Date; public class User implements Serializable{ private static final long serialVersionUID = -2434681656774470695L; private String userId; private String userName; private Date userBirthday; private Double userSalary; public String getUserId() { return userId; } public void setUserId(String userId) { this.userId = userId == null ? null : userId.trim(); } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } public Date getUserBirthday() { return userBirthday; } public void setUserBirthday(Date date) { this.userBirthday = date; } public Double getUserSalary() { return userSalary; } public void setUserSalary(Double userSalary) { this.userSalary = userSalary; } }
2.com.wangyin.dao.UserMapper.java
此类为mybatis映射接口,其方法名称与UserMapper.xml文件中的select,insert等bean的id相同,只要调用该接口的方法,mybatis就会自动查询数据库并返回结果
package com.wangyin.dao; import java.util.List; import com.wangyin.domain.User; public interface UserMapper { int insert(User record); User selectByPrimaryKey(String userId); List<User> selectAllUsers(); }
3.com.wangyin.service.IUserService.java
此类是服务层的接口
package com.wangyin.service; import java.util.List; import com.wangyin.domain.User; public interface IUserService { void addUser(User user); User getUserById(String userId); List<User> getAllUsers(); }
4.com.wangyin.service.UserServiceImpl.java
该类为服务实现类
package com.wangyin.service.impl; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Propagation; import org.springframework.transaction.annotation.Transactional; import com.wangyin.dao.UserMapper; import com.wangyin.domain.User; import com.wangyin.service.IUserService; @Service("userService") public class UserServiceImpl implements IUserService{ @Autowired private UserMapper userMapper; public UserMapper getUserMapper() { return userMapper; } public void setUserMapper(UserMapper userMapper) { this.userMapper = userMapper; } public void addUser(User user) { // TODO Auto-generated method stub userMapper.insert(user); } @Transactional(propagation=Propagation.REQUIRED,readOnly=true) public User getUserById(String userId) { // TODO Auto-generated method stub return userMapper.selectByPrimaryKey(userId); } public List<User> getAllUsers() { // TODO Auto-generated method stub System.out.println("服务调用"); return userMapper.selectAllUsers(); } }
5.com.wangyin.test.SpringMybatisTest.java
此类用于测试Spring与Mybatis的集成,通过集成junit中的TestCase类,来进行方法测试。
package com.wangyin.test; import java.util.Date; import java.util.List; import java.util.UUID; import junit.framework.TestCase; import org.springframework.context.ApplicationContext; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.wangyin.domain.User; import com.wangyin.service.IUserService; public class SpringMybatisTest extends TestCase{ private static IUserService userService; private static ApplicationContext act; static{ act = new ClassPathXmlApplicationContext(new String[]{"resources/spring.xml","resources/spring-mybatis.xml"}); userService = (IUserService)act.getBean("userService"); } public void testSelectAll(){ List<User> users = userService.getAllUsers(); for(User user : users){ System.out.println(user.getUserId()); } } public void testSelectById(){ User user = userService.getUserById("48186cefca4e413c803645014ff644b0"); System.out.println(user.getUserBirthday().toLocaleString()); } public void testAdd(){ User user = new User(); user.setUserId(UUID.randomUUID().toString().replaceAll("-", "")); user.setUserBirthday(new Date()); user.setUserName("wudi"); user.setUserSalary(15000D); userService.addUser(user); } }
6.com.wangyin.test.DubboProvider.java
Dubbo服务的提供者
package com.wangyin.test; import java.io.IOException; import org.springframework.context.support.ClassPathXmlApplicationContext; public class DubboProvider { public static void main(String[] args) throws IOException{ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext( new String[]{"classpath:resources/dubbo-provider.xml", "classpath:resources/spring.xml", "classpath:resources/spring-mybatis.xml"}); context.start(); System.in.read(); /*com.alibaba.dubbo.container.Main.main(args);*/ } }
7.com.wangyin.test.DubboConsumer.java
package com.wangyin.test; import java.util.List; import org.springframework.context.support.ClassPathXmlApplicationContext; import com.wangyin.domain.User; import com.wangyin.service.IUserService; public class DubboConsumer { public static void main(String args[]){ ClassPathXmlApplicationContext context = new ClassPathXmlApplicationContext("classpath:resources/dubbo-consumer.xml"); context.start(); IUserService demoService = (IUserService)context.getBean("userService"); // 获取远程服务代理 List<User> users = demoService.getAllUsers(); // 执行远程方法 for(User user : users){ System.out.println(user.getUserId()); } } }
8.resources/spring.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:context="http://www.springframework.org/schema/context" 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.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 加载dbconfig.properties文件,用于下边的数据库配置 --> <context:property-placeholder location="classpath:resources/dbconfig.properties"/> <!-- 将service及其子目录下标有@Component、@Service等注解的类自动装配 --> <context:component-scan base-package="com.wangyin.service"/> <!-- 数据源配置 --> <bean name="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" > <property name="driverClassName" value="${driverClassName}"></property> <property name="url" value="${jdbc_url}" /> <property name="username" value="${jdbc_username}" /> <property name="password" value="${jdbc_password}" /> </bean> </beans>
9.resources/dbconfig.properties
driverClassName=com.mysql.jdbc.Driver validationQuery=SELECT 1 jdbc_url=jdbc:mysql://localhost:3306/spring4_mybatis3 jdbc_username=root [email protected]#456
10.resources/spring-mybatis.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:context="http://www.springframework.org/schema/context" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- ========================================针对myBatis的配置项============================== 转载的--> <!-- 配置sqlSessionFactory --> <!-- 实例化sqlSessionFactory时需要使用上述配置好的数据源以及SQL映射文件 --> <!-- 自动扫描com/wangyin/mapping/目录下的所有SQL映射的xml文件, 省掉Configuration.xml里的手工配置 value="classpath:com/wangyin/mapping/*.xml"指的是classpath(类路径)下com.wangyin.mapping包中的所有xml文件 UserMapper.xml位于com.wangyin.mapping包下,这样UserMapper.xml就可以被自动扫描 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations" value="classpath:com/wangyin/mappers/*.xml" /> </bean> <!-- 配置扫描器 --> <bean id="daoScan" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 扫描com.wangyin.dao这个包以及它的子包下的所有映射接口类 --> <property name="basePackage" value="com.wangyin.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> </beans>
11resources/dubbo-provider.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:dubbo="http://code.alibabatech.com/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"> <!-- 提供方应用信息,用于计算依赖关系 --> <dubbo:application name="hello-world-app" /> <!-- 使用multicast广播注册中心暴露服务地址 --> <dubbo:registry address="multicast://224.5.6.7:1234" /> <!-- 用dubbo协议在20880端口暴露服务 --> <dubbo:protocol name="dubbo" port="20880" /> <!-- 声明需要暴露的服务接口 --> <dubbo:service interface="com.wangyin.service.IUserService" ref="userService" /> <!-- 和本地bean一样实现服务 --> <bean id="userService" class="com.wangyin.service.impl.UserServiceImpl" /> </beans>
12.resources/dubbo-consumer.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:dubbo="http://code.alibabatech.com/schema/dubbo" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd"> <!-- 消费方应用名,用于计算依赖关系,不是匹配条件,不要与提供方一样 --> <dubbo:application name="consumer-of-helloworld-app" /> <!-- 使用multicast广播注册中心暴露发现服务地址 --> <dubbo:registry address="multicast://224.5.6.7:1234" /> <!-- 生成远程服务代理,可以和本地bean一样使用demoService --> <dubbo:reference id="userService" interface="com.wangyin.service.IUserService" /> </beans>
13.com.wangyin.mappers.UserMapper.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.wangyin.dao.UserMapper" > <resultMap id="BaseResultMap" type="com.wangyin.domain.User" > <id column="user_id" property="userId" jdbcType="CHAR" /> <result column="user_name" property="userName" jdbcType="VARCHAR" /> <result column="user_birthday" property="userBirthday" jdbcType="DATE" /> <result column="user_salary" property="userSalary" jdbcType="DOUBLE" /> </resultMap> <sql id="Base_Column_List" > user_id, user_name, user_birthday, user_salary </sql> <select id="selectAllUsers" resultMap="BaseResultMap"> select * from t_user </select> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.String" > select <include refid="Base_Column_List" /> from t_user where user_id = #{userId,jdbcType=CHAR} </select> <insert id="insert" parameterType="com.wangyin.domain.User" > insert into t_user (user_id, user_name, user_birthday, user_salary) values (#{userId,jdbcType=CHAR}, #{userName,jdbcType=VARCHAR}, #{userBirthday,jdbcType=DATE}, #{userSalary,jdbcType=DOUBLE}) </insert> </mapper>
三、运行方式
1.Spring Mybatis 集成测试
分别右键点击SpringMybatisTest.java下的方法run as ->JUnit Test即可得到运行结果。
2.Dubbo服务的发布与调用
首先运行DubboProvider.java,然后运行DubboConsumer.java,即可得到调用结果
源代码及Jar包集合(赚点分嘿嘿):
http://download.csdn.net/detail/adiaixin123456/8631193