可以参考我之前的一篇博文maven快速入门
1、搭建web工程
mvn archetype:generate -DgroupId=com.yuanmeng.springdemo -DartifactId=spring-mybatis -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
2、pom配置
<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.0modelVersion> <groupId>com.yuanmeng.springdemogroupId> <artifactId>spring-mybatisartifactId> <packaging>warpackaging> <version>1.0-SNAPSHOTversion> <name>spring Maven Webappname> <url>http://maven.apache.orgurl> <properties> <project.build.sourceEncoding>UTF-8project.build.sourceEncoding> <spring.version>4.1.4.RELEASEspring.version> <jackson.version>2.5.0jackson.version> properties> <dependencies> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-coreartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-beansartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-contextartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-txartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-webmvcartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-jdbcartifactId> <version>${spring.version}version> dependency> <dependency> <groupId>org.springframeworkgroupId> <artifactId>spring-testartifactId> <version>${spring.version}version> <scope>testscope> dependency> <dependency> <groupId>org.mybatisgroupId> <artifactId>mybatisartifactId> <version>3.2.8version> dependency> <dependency> <groupId>org.mybatisgroupId> <artifactId>mybatis-springartifactId> <version>1.2.2version> dependency> <dependency> <groupId>mysqlgroupId> <artifactId>mysql-connector-javaartifactId> <version>5.1.34version> dependency> <dependency> <groupId>com.alibabagroupId> <artifactId>druidartifactId> <version>1.0.12version> dependency> <dependency> <groupId>org.aspectjgroupId> <artifactId>aspectjweaverartifactId> <version>1.8.4version> dependency> <dependency> <groupId>log4jgroupId> <artifactId>log4jartifactId> <version>1.2.17version> dependency> <dependency> <groupId>javax.servletgroupId> <artifactId>servlet-apiartifactId> <version>3.0-alpha-1version> dependency> <dependency> <groupId>javax.servletgroupId> <artifactId>jstlartifactId> <version>1.2version> dependency> <dependency> <groupId>com.alibabagroupId> <artifactId>fastjsonartifactId> <version>1.2.3version> dependency> <dependency> <groupId>junitgroupId> <artifactId>junitartifactId> <version>4.12version> <scope>testscope> dependency> dependencies> <build> <finalName>spring-mybatisfinalName> build> project>
3、切换到工程根目录下,执行 mvn eclipse:eclipse。将maven工程转为eclipse工程,然后在eclipse导入工程
二、创建表
登录 mysql -uroot -p use testdb 创建表 create table user_info( id int(16) not null primary key auto_increment, name varchar(32) not null, password varchar(32) not null );
三、自动生成dao、do、mapper xml配置
可以参考我之前的一篇博文mybatis-generator-core自动生成do、mapping、dao 代码
四、代码结构
dao
public interface UserInfoMapper { int deleteByPrimaryKey(Long id); int insert(UserInfo record); int insertSelective(UserInfo record); UserInfo selectByPrimaryKey(Integer id); int updateByPrimaryKeySelective(UserInfo record); int updateByPrimaryKey(UserInfo record); }
do
public class UserInfo { private int id; private String name; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name == null ? null : name.trim(); } public String getPassword() { return password; } public void setPassword(String password) { this.password = password == null ? null : password.trim(); } }
service
public interface UserService { UserInfo getUserInfoById(int id); } @Service("userService") public class UserServiceImpl implements UserService { @Resource(name="userInfoMapper") private UserInfoMapper userInfoMapper; @Override public UserInfo getUserInfoById(int id) { return userInfoMapper.selectByPrimaryKey(id); } }
五、文件配置
userInfoMapper.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.yuanmeng.springdemo.dao.UserInfoMapper" > <resultMap id="BaseResultMap" type="com.yuanmeng.springdemo.model.UserInfo" > <id column="id" property="id" jdbcType="INTEGER" /> <result column="name" property="name" jdbcType="VARCHAR" /> <result column="password" property="password" jdbcType="VARCHAR" /> resultMap> <sql id="Base_Column_List" > id, name, password sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer" > select <include refid="Base_Column_List" /> from user_info where id = #{id,jdbcType=INTEGER} select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer" > delete from user_info where id = #{id,jdbcType=INTEGER} delete> <insert id="insert" parameterType="com.yuanmeng.springdemo.model.UserInfo" > insert into user_info (id, name, password ) values (#{id,jdbcType=INTEGER}, #{name,jdbcType=VARCHAR}, #{password,jdbcType=VARCHAR} ) insert> <insert id="insertSelective" parameterType="com.yuanmeng.springdemo.model.UserInfo" > insert into user_info <trim prefix="(" suffix=")" suffixOverrides="," > <if test="id != null" > id, if> <if test="name != null" > name, if> <if test="password != null" > password, 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="password != null" > #{password,jdbcType=VARCHAR}, if> trim> insert> <update id="updateByPrimaryKeySelective" parameterType="com.yuanmeng.springdemo.model.UserInfo" > update user_info <set > <if test="name != null" > name = #{name,jdbcType=VARCHAR}, if> <if test="password != null" > password = #{password,jdbcType=VARCHAR}, if> set> where id = #{id,jdbcType=INTEGER} update> <update id="updateByPrimaryKey" parameterType="com.yuanmeng.springdemo.model.UserInfo" > update user_info set name = #{name,jdbcType=VARCHAR}, password = #{password,jdbcType=VARCHAR} where id = #{id,jdbcType=INTEGER} update> mapper>
config.properties
validationQuery=SELECT 1 jdbc.url=jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=utf-8 jdbc.username=root jdbc.password=root
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" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.1.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.1.xsd"> <context:property-placeholder location="classpath:config.properties" /> <context:component-scan base-package="com.yuanmeng.springdemo.service" /> beans>
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: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 "> <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" /> <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" /> <property name="removeAbandoned" value="true" /> <property name="removeAbandonedTimeout" value="1800" /> <property name="logAbandoned" value="true" /> <property name="filters" value="mergeStat" /> bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="mapperLocations" value="classpath:com/yuanmeng/springdemo/mapping/*.xml" /> bean> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.yuanmeng.springdemo.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> bean> <bean id="druid-stat-interceptor" class="com.alibaba.druid.support.spring.stat.DruidStatInterceptor"> bean> <bean id="druid-stat-pointcut" class="org.springframework.aop.support.JdkRegexpMethodPointcut" scope="prototype"> <property name="patterns"> <list> <value>com.yuanmeng.springdemo.service.*value> list> property> bean> <aop:config> <aop:advisor advice-ref="druid-stat-interceptor" pointcut-ref="druid-stat-pointcut" /> aop:config> beans>
六、test
方法一 : 使用Spring提供的Junit测试框架进行单元测试
@RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-mybatis.xml" }) public class TestUserService { private static final Logger LOGGER = Logger.getLogger(TestUserService.class); @Resource(name="userService") private UserService userService; @Test public void testGetUserInfoById() { UserInfo userInfo = userService.getUserInfoById(1); LOGGER.info(JSON.toJSON(userInfo)); } }
方法二 : 使用Junit测试框架进行单元测试
public class TestUserService2 { private static final Logger LOGGER = Logger.getLogger(TestUserService2.class); private UserService userService; @Before public void init() { @SuppressWarnings("resource") ApplicationContext ac = new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-mybatis.xml"}); userService = (UserService) ac.getBean("userService"); } @Test public void testGetUserInfoById() { UserInfo userInfo = userService.getUserInfoById(1); LOGGER.info(JSON.toJSON(userInfo)); } }