本系列目录 http://www.jianshu.com/p/22f3b28d974c
假设读者有能力用Maven构建WEB项目。
1. 下图是Eclipse下项目的项目结构
2. pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.albert</groupId>
<artifactId>AlbertBlog</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>AlbertBlog Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<!-- base setting -->
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.build.locales>zh_CN</project.build.locales>
<project.build.jdk>1.7</project.build.jdk>
<!-- lib versions -->
<junit.version>4.12</junit.version>
<spring.version>4.0.2.RELEASE</spring.version>
<quartz.version>2.2.1</quartz.version>
<log4j.version>1.2.14</log4j.version>
<mysql.connector.version>5.1.21</mysql.connector.version>
<aspectj.version>1.6.2</aspectj.version>
<json.version>20140107</json.version>
<jedis.version>2.6.0</jedis.version>
<commons.logging.version>1.1.3</commons.logging.version>
<commons.lang.version>2.6</commons.lang.version>
<mybatis.version>3.2.6</mybatis.version>
<javassist.version>3.18.0-GA</javassist.version>
<druid.version>1.0.5</druid.version>
<jackson-version>2.3.0</jackson-version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-orm</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.4.0.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- Quartz framework -->
<dependency>
<groupId>org.quartz-scheduler</groupId>
<artifactId>quartz</artifactId>
<version>${quartz.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>${mysql.connector.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>${aspectj.version}</version>
</dependency>
<dependency>
<groupId>org.json</groupId>
<artifactId>json</artifactId>
<version>${json.version}</version>
</dependency>
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>${jedis.version}</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>${commons.logging.version}</version>
</dependency>
<dependency>
<groupId>commons-lang</groupId>
<artifactId>commons-lang</artifactId>
<version>${commons.lang.version}</version>
</dependency>
<!-- mybatis核心包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
</dependency>
<!-- mybatis/spring包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.2.2</version>
</dependency>
<dependency>
<groupId>org.javassist</groupId>
<artifactId>javassist</artifactId>
<version>${javassist.version}</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>${druid.version}</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>jcl-over-slf4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.0</version>
</dependency>
<!-- json jackson -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-core-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.9.13</version>
</dependency>
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.9</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.2</version>
</dependency>
<!--spring websocket库 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-websocket</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-messaging</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>${jackson-version}</version>
</dependency>
</dependencies>
<build>
<finalName>AlbertBlog</finalName>
</build>
</project>
pom.xml在接下来的开发中会根据需要添加依赖包。
3. applicationContext.xml
此文件中配置datasource,sessionFactory,连接池,事务
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:p="http://www.springframework.org/schema/p"
xmlns:util="http://www.springframework.org/schema/util" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
xmlns:cache="http://www.springframework.org/schema/cache"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/jdbc
http://www.springframework.org/schema/jdbc/spring-jdbc.xsd
http://www.springframework.org/schema/cache
http://www.springframework.org/schema/cache/spring-cache.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd">
<!-- 自动扫描 ,将带有注解的类 纳入spring容器管理 -->
<context:component-scan base-package="com.albert"></context:component-scan>
<!-- 引入配置文件 -->
<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
<property name="locations">
<list>
<value>classpath*:application.properties</value>
</list>
</property>
</bean>
<!-- dataSource 配置 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="${ds.initialSize}"/>
<property name="minIdle" value="${ds.minIdle}"/>
<property name="maxActive" value="${ds.maxActive}"/>
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="${ds.maxWait}"/>
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="${ds.timeBetweenEvictionRunsMillis}"/>
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="${ds.minEvictableIdleTimeMillis}"/>
<property name="validationQuery" value="SELECT 'x'"/>
<property name="testWhileIdle" value="true"/>
<property name="testOnBorrow" value="false"/>
<property name="testOnReturn" value="false"/>
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="false"/>
<property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>
<!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat"/>
</bean>
<!-- mybatis文件配置,扫描所有mapper文件 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean" p:dataSource-ref="dataSource"
p:configLocation="classpath:mybatis-config.xml"
p:mapperLocations="classpath:com/albert/dao/*.xml"/>
<!-- spring与mybatis整合配置,扫描所有dao -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer" p:basePackage="com.albert.dao"
p:sqlSessionFactoryBeanName="sqlSessionFactory"/>
<!-- 对dataSource 数据源进行事务管理 -->
<!-- 配置事务容器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager" p:dataSource-ref="dataSource"/>
<!-- 事务管理 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 对insert,update,delete 开头的方法进行事务管理,只要有异常就回滚 -->
<tx:method name="insert" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
<tx:method name="update*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
<tx:method name="delete*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
<tx:method name="execute*" propagation="REQUIRED" rollback-for="java.lang.Throwable"/>
<!-- select,count开头的方法,开启只读,提高数据库访问性能 -->
<tx:method name="select*" read-only="true"/>
<tx:method name="count*" read-only="true"/>
<!-- 对其他方法 使用默认的事务管理 -->
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- 事务 aop 配置 -->
<aop:config>
<aop:pointcut id="serviceMethods" expression="execution(* com.albert.service..*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="serviceMethods"/>
</aop:config>
<!-- 开启AOP监听 只对当前配置文件有效 -->
<aop:aspectj-autoproxy expose-proxy="true" />
<!-- 启用对事务注解的支持 -->
<tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
4. 配置mybatis-conf.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>
<!-- 实体类,简称 -设置别名 -->
<typeAliases>
<typeAlias alias="Users" type="com.albert.domain.table.Users" />
</typeAliases>
</configuration>
5. DAO层
至此,项目配置部分基本完毕,接下来我们添加实体以及DAO层的mapper。在com.albert.domain.table包下面添加实体User.java,dao层添加相应的UserMapper.java,UserMapper.xml.(这里手动添加是为了更好的学习。接下来的模块会使用mybatis-generater自动生成modal,dao,mapper
)
`
UserMapper.java
/**
*
*/
package com.albert.dao;
import java.util.List;
import com.albert.domain.table.Users;
/**
* @ClassName: UserMapper
* @Description:
* @author albert
* @date 2017年3月6日 下午7:30:41
*
*/
public interface UserMapper {
void save(Users user);
void update(Users user);
void delete(Integer id);
Users findById(Integer id);
List<Users> findAll();
}
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.albert.dao.UserMapper">
<!--这里的id一定要与上面接口里方法一一对应-->
<insert id="save" parameterType="Users">
insert into t_users(uid,username,password) values(#{uid},#{username},#{password})
</insert>
<update id="update" parameterType="Users">
update t_users set username=#{username},password=#{password} where uid=#{uid}
</update>
<delete id="delete" parameterType="Integer">
delete from t_users where uid=#{uid}
</delete>
<select id="findById" parameterType="int" resultType="Users">
select uid uid,username userame,password password from t_users where uid=#{uid}
</select>
<select id="findAll" resultType="Users">
select uid uid,username username,password password from t_users
</select>
</mapper>
6. DAO层测试(Junit)
TestSupport.java 是个抽象类,其他测试代码必须继承它
package com.albert;
import org.junit.AfterClass;
import org.junit.BeforeClass;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.AbstractJUnit4SpringContextTests;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
/**
*
* @ClassName: TestSupport
* @Description: junit 测试
* @author albert
* @date 2017年3月6日 下午11:11:17
*
*/
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath*:applicationContext.xml"})
public abstract class TestSupport extends AbstractJUnit4SpringContextTests {
@BeforeClass
public static void start() {
System.out.println("测试前置处理");
}
@AfterClass
public static void end() {
System.out.println("测试后置处理");
}
/**
* 输出记录
*/
protected void log() {
logger.info("测试");
}
}
下面是JUNIT测试代码
package com.albert.test;
import javax.annotation.Resource;
import org.junit.Test;
import com.albert.TestSupport;
import com.albert.dao.UserMapper;
import com.albert.domain.table.Users;
import com.albert.service.UserService;
/**
* @ClassName: DaoTest
* @Description: 测试DAO层
* @author albert
* @date 2017年3月6日 下午7:50:36
*
*/
public class DaoTest extends TestSupport{
@Resource
private UserMapper userMapper;
@Test
public void test(){
Users u = userMapper.findById(1);
System.out.println(u);
}
}
运行上面的测试代码,控制台打印了查到的结果
[INFO ] 2017-03-07 00:28:54 org.springframework.test.context.TestContextManager.retrieveTestExecutionListeners(TestContextManager.java:234): Could not instantiate TestExecutionListener class [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their dependencies) available.
测试前置处理
[INFO ] 2017-03-07 00:28:54 org.springframework.beans.factory.xml.XmlBeanDefinitionReader.loadBeanDefinitions(XmlBeanDefinitionReader.java:316): Loading XML bean definitions from URL [file:/Users/albert/Documents/workspace/AlbertBlog/target/classes/applicationContext.xml]
[INFO ] 2017-03-07 00:28:54 org.springframework.context.support.AbstractApplicationContext.prepareRefresh(AbstractApplicationContext.java:513): Refreshing org.springframework.context.support.GenericApplicationContext@3a7109eb: startup date [Tue Mar 07 00:28:54 CST 2017]; root of context hierarchy
[INFO ] 2017-03-07 00:28:54 org.springframework.core.io.support.PropertiesLoaderSupport.loadProperties(PropertiesLoaderSupport.java:172): Loading properties file from URL [file:/Users/albert/Documents/workspace/AlbertBlog/target/classes/application.properties]
[INFO ] 2017-03-07 00:28:55 com.alibaba.druid.pool.DruidDataSource.init(DruidDataSource.java:638): {dataSource-1} inited
Users [uid=1, username=null, password=a66abb5684c45962d887564f08346e8d]
测试后置处理
[INFO ] 2017-03-07 00:28:56 org.springframework.context.support.AbstractApplicationContext.doClose(AbstractApplicationContext.java:873): Closing org.springframework.context.support.GenericApplicationContext@3a7109eb: startup date [Tue Mar 07 00:28:54 CST 2017]; root of context hierarchy
[INFO ] 2017-03-07 00:28:56 com.alibaba.druid.pool.DruidDataSource.close(DruidDataSource.java:1288): {dataSource-1} closed
Service层测试
/**
*
*/
package com.albert.test;
import javax.annotation.Resource;
import org.junit.Test;
import com.albert.TestSupport;
import com.albert.domain.table.Users;
import com.albert.service.UserService;
/**
* @ClassName: ServiceTest
* @Description: Service层测试
* @author albert
* @date 2017年3月7日 下午8:58:52
*
*/
public class ServiceTest extends TestSupport {
@Resource
private UserService service;
@Test
public void test(){
Users users = service.findById(1);
logger.info("结果:"+users);
}
}
程序运行后同样打印,
结果:Users [uid=1, username=null, password=a66abb5684c45962d887564f08346e8d]
-
数据库脚本下载地址:albertblog.sql