一、新建maven项目
建好的项目结构如下图:
还需要做以下配置:
勾选上这两项后,就会自动生成 “src/main/java” 和 “src/main/resources” 这两个目录
如上图,修改项目部署路径
选择项目部署时要发布的目录, src/test/java 目录不需要发布,因此remove掉。
配置完成后项目的结构如下图:
项目还在报错,这是因为现在是一个web项目,缺少servlet的jar包,在pom.xml 中加上servlet的依赖就不会报错了;
然后开始依赖配置,pom.xml配置如下:
<properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <spring.version>4.3.10.RELEASE</spring.version> </properties> <dependencies> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- 配置servlet --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!-- 配置spring --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <!-- 配置spring mvc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency> <!-- 配置spring 测试jar包 --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <!-- 配置数据库连接池 --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <!-- 配置mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.1</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency> <!-- 配置mysql --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.38</version> </dependency> <!-- @ResponseBody 依赖jackson --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.7.3</version> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.1.41</version> </dependency> </dependencies>
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" xmlns:util="http://www.springframework.org/schema/util" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa-1.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd"> <!-- 自动扫描 --> <context:component-scan base-package="com.ls.test" /> <!-- 引入配置文件 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:db.properties" /> </bean> <bean id="dbcp" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <property name="driverClassName" value="${driver}" /> <property name="url" value="${url}" /> <property name="username" value="${username}" /> <property name="password" value="${password}" /> </bean> <!-- spring和MyBatis完美整合,不需要mybatis的配置映射文件 --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dbcp" /> <!-- 自动扫描mapping.xml文件 --> <property name="mapperLocations" value="classpath:com/ls/test/mapping/*.xml"></property> </bean> <!-- DAO接口所在包名,Spring会自动查找其下的类 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.ls.test.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> <!-- (事务管理)transaction manager, use JtaTransactionManager for global tx --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dbcp" /> </bean> </beans>
db.properties 数据库配置
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/goddess
username=root
password=root123
开始编码工作:
实体类User:
package com.ls.test.entity; public class User { private Integer userId; private String userName; private String userPassword; private String userToken; private String userDesc; public Integer getUserId() { return userId; } public void setUserId(Integer userId) { this.userId = userId; } public String getUserName() { return userName; } public void setUserName(String userName) { this.userName = userName == null ? null : userName.trim(); } public String getUserPassword() { return userPassword; } public void setUserPassword(String userPassword) { this.userPassword = userPassword == null ? null : userPassword.trim(); } public String getUserToken() { return userToken; } public void setUserToken(String userToken) { this.userToken = userToken == null ? null : userToken.trim(); } public String getUserDesc() { return userDesc; } public void setUserDesc(String userDesc) { this.userDesc = userDesc == null ? null : userDesc.trim(); } }
数据库接口 DAO:
package com.ls.test.dao; import com.ls.test.entity.User; public interface UserMapper { int deleteByPrimaryKey(Integer userId); int insert(User record); int insertSelective(User record); User selectByPrimaryKey(Integer userId); int updateByPrimaryKeySelective(User record); int updateByPrimaryKey(User record); }
mybatis映射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.ls.test.dao.UserMapper"> <resultMap id="BaseResultMap" type="com.ls.test.entity.User"> <id column="user_id" property="userId" jdbcType="INTEGER" /> <result column="user_name" property="userName" jdbcType="VARCHAR" /> <result column="user_password" property="userPassword" jdbcType="VARCHAR" /> <result column="user_token" property="userToken" jdbcType="VARCHAR" /> <result column="user_desc" property="userDesc" jdbcType="VARCHAR" /> </resultMap> <sql id="Base_Column_List"> user_id, user_name, user_password, user_token, user_desc </sql> <select id="selectByPrimaryKey" resultMap="BaseResultMap" parameterType="java.lang.Integer"> select <include refid="Base_Column_List" /> from user where user_id = #{userId,jdbcType=INTEGER} </select> <delete id="deleteByPrimaryKey" parameterType="java.lang.Integer"> delete from user where user_id = #{userId,jdbcType=INTEGER} </delete> <insert id="insert" parameterType="com.ls.test.entity.User"> insert into user (user_id, user_name, user_password, user_token, user_desc) values (#{userId,jdbcType=INTEGER}, #{userName,jdbcType=VARCHAR}, #{userPassword,jdbcType=VARCHAR}, #{userToken,jdbcType=VARCHAR}, #{userDesc,jdbcType=VARCHAR}) </insert> <insert id="insertSelective" parameterType="com.ls.test.entity.User"> insert into user <trim prefix="(" suffix=")" suffixOverrides=","> <if test="userId != null"> user_id, </if> <if test="userName != null"> user_name, </if> <if test="userPassword != null"> user_password, </if> <if test="userToken != null"> user_token, </if> <if test="userDesc != null"> user_desc, </if> </trim> <trim prefix="values (" suffix=")" suffixOverrides=","> <if test="userId != null"> #{userId,jdbcType=INTEGER}, </if> <if test="userName != null"> #{userName,jdbcType=VARCHAR}, </if> <if test="userPassword != null"> #{userPassword,jdbcType=VARCHAR}, </if> <if test="userToken != null"> #{userToken,jdbcType=VARCHAR}, </if> <if test="userDesc != null"> #{userDesc,jdbcType=VARCHAR}, </if> </trim> </insert> <update id="updateByPrimaryKeySelective" parameterType="com.ls.test.entity.User"> update user <set> <if test="userName != null"> user_name = #{userName,jdbcType=VARCHAR}, </if> <if test="userPassword != null"> user_password = #{userPassword,jdbcType=VARCHAR}, </if> <if test="userToken != null"> user_token = #{userToken,jdbcType=VARCHAR}, </if> <if test="userDesc != null"> user_desc = #{userDesc,jdbcType=VARCHAR}, </if> </set> where user_id = #{userId,jdbcType=INTEGER} </update> <update id="updateByPrimaryKey" parameterType="com.ls.test.entity.User"> update user set user_name = #{userName,jdbcType=VARCHAR}, user_password = #{userPassword,jdbcType=VARCHAR}, user_token = #{userToken,jdbcType=VARCHAR}, user_desc = #{userDesc,jdbcType=VARCHAR} where user_id = #{userId,jdbcType=INTEGER} </update> </mapper>
服务层 UserService:
package com.ls.test.service; import com.ls.test.entity.User; public interface UserService { User findUserById(Integer userId); }
UserServiceImpl:
package com.ls.test.service.impl; import javax.annotation.Resource; import org.springframework.stereotype.Service; import com.ls.test.dao.UserMapper; import com.ls.test.entity.User; import com.ls.test.service.UserService; @Service public class UserServiceImpl implements UserService { @Resource private UserMapper userDao;//注入UserMapper @Override public User findUserById(Integer userId) { User user = userDao.selectByPrimaryKey(userId); return user; } }
控制层 controller
package com.ls.test.controller; import javax.annotation.Resource; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.ls.test.entity.User; import com.ls.test.service.UserService; @Controller public class UserController { @Resource private UserService us;//注入UserService @ResponseBody @RequestMapping("/user") public User execute(@RequestParam("userId") Integer userId){ User user = us.findUserById(userId); return user; } }
编写测试用例:
TestDao
package test; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.alibaba.fastjson.JSON; import com.ls.test.dao.UserMapper; import com.ls.test.entity.User; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring-mybatis.xml"}) public class TestDao { @Resource private UserMapper userDao; @Test public void testDao(){ User user = userDao.selectByPrimaryKey(1); System.out.println("testDao: "+JSON.toJSON(user)); } }
运行测试用例,得到这个下图结果,说明mybatis配置ok
TestService
package test; import javax.annotation.Resource; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.alibaba.fastjson.JSON; import com.ls.test.entity.User; import com.ls.test.service.UserService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring-mybatis.xml"}) public class TestService { @Resource private UserService us; @Test public void testUserService(){ User user = us.findUserById(1); System.out.println("testUserService: "+JSON.toJSON(user)); } }
运行测试用例,得到这个下图结果,说明spring和mybatis整合成功
TestController
package test; import javax.annotation.Resource; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import org.springframework.test.web.servlet.ResultActions; import org.springframework.test.web.servlet.request.MockMvcRequestBuilders; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import com.ls.test.controller.UserController; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(locations = {"classpath:spring-mybatis.xml"}) public class TestController { @Resource private UserController uc; private MockMvc mockMvc; @Before public void setup(){ mockMvc = MockMvcBuilders.standaloneSetup(uc).build(); } @Test public void testUserController() throws Exception{ ResultActions resultActions=mockMvc.perform(MockMvcRequestBuilders.post("/user").param("userId", "1")); MvcResult mvcRresult= resultActions.andReturn(); String result = mvcRresult.getResponse().getContentAsString(); System.out.println("testUserController :"+result); } }
运行测试用例,得到这个下图结果,说明spring、spring mvc和mybatis整合成功
实体类、dao、mybatis映射文件可以通过 mybatis-generator-core-1.3.2.jar 这个jar包自动生成,本文中样例就是同过这个jar包生成
最后附上项目最终的结构图: