Maven搭建SpringMVC+Mybatis项目详解

前言

         最近比较闲,复习搭建一下项目,这次主要使用Spring+SpringMVC+Mybatis。项目持久层使用Mybatis3,控制层使用SpringMVC4.1,使用Spring4.1管理控制器,数据库连接池使用druid数据源,该项数据库暂使用MySQL。

1、 数据库表结构以及maven项目结构

         数据表非常的简单(不是重点),如下:

         

       创建maven项目,详细见上一篇maven创建(http://blog.csdn.net/fengshizty/article/details/43019561),创建Maven Project时,将Filter选择为org.apache.maven.archetypes。填写完相关项目坐标信息后项目结构如下:

        

     注:若无src/main/java,src/test/java,src/test/resources时,创建这个几个Source Folder。


 2、修改pom.xml添加对应的包依赖

     这儿将全部使用的Maven依赖贴出了,对应什么作用上面都有解释,如下:

     pom.xml


	4.0.0
	org.andy.sm
	springmvc_mybatis_demo
	war
	0.0.1-SNAPSHOT

	springmvc_mybatis_demo Maven Webapp
	http://maven.apache.org

	
		UTF-8
		4.1.4.RELEASE
		2.5.0
	

	

		
			junit
			junit
			4.12
			test
		

		
		
			org.springframework
			spring-core
			${spring.version}
		

		
			org.springframework
			spring-beans
			${spring.version}
		

		
			org.springframework
			spring-context
			${spring.version}
		

		
			org.springframework
			spring-tx
			${spring.version}
		

		
			org.springframework
			spring-web
			${spring.version}
		

		
			org.springframework
			spring-webmvc
			${spring.version}
		

		
			org.springframework
			spring-jdbc
			${spring.version}
		

		
			org.springframework
			spring-test
			${spring.version}
			test
		

		
		
			org.mybatis
			mybatis
			3.2.8
		

		
		
			org.mybatis
			mybatis-spring
			1.2.2
		

		
		
			mysql
			mysql-connector-java
			5.1.34
		

		
		
			com.alibaba
			druid
			1.0.12
		

		
			org.aspectj
			aspectjweaver
			1.8.4
		

		
		
			log4j
			log4j
			1.2.17
		

		
		
			javax.servlet
			servlet-api
			3.0-alpha-1
		

		
			javax.servlet
			jstl
			1.2
		

		
		
			org.codehaus.jackson
			jackson-mapper-asl
			1.9.13
		

		
			com.alibaba
			fastjson
			1.2.3
		

		
			com.fasterxml.jackson.core
			jackson-annotations
			${jackson.version}
		

		
			com.fasterxml.jackson.core
			jackson-core
			${jackson.version}
		

		
			com.fasterxml.jackson.core
			jackson-databind
			${jackson.version}
		
		
		
			commons-io
			commons-io
			2.4
		

		
			commons-fileupload
			commons-fileupload
			1.2.2
		


	


	
		springmvc_mybatis_demo
		
			
			
				org.apache.maven.plugins
				maven-surefire-plugin
				2.4.2
				
					true
				
			

			
				org.apache.maven.plugins
				maven-war-plugin
				2.3
				
					src/main/webapp/WEB-INF/web.xml
				
			

			
			
				org.apache.maven.plugins
				maven-javadoc-plugin
				2.9.1
				
					target/javadoc
					target/javadoc
					UTF-8
					UTF-8
					UTF-8
					private
				
			

			
			
				org.codehaus.cargo
				cargo-maven2-plugin
				1.0
				
					
						tomcat6x
						D:\WebServer\apache-tomcat-6.0.39
					
					
						existing
						D:\WebServer\apache-tomcat-6.0.39
					
				
			

		

	

3、使用Generator自动生成Mybatis相关表信息

      自动生成表的Model,Mapping,Dao文件,先关使用见文章 http://blog.csdn.net/fengshizty/article/details/43086833 

并将其导入到项目的src/main/java包中。

      其中生成的Model中UserInfo如下:

UserInfo.java(其中List courseInfos手动添加的)

package org.andy.shop.model;

import java.util.List;

public class UserInfo {
	private Integer id;

	private String uname;

	private Integer unumber;

	private List courseInfos;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUname() {
		return uname;
	}

	public void setUname(String uname) {
		this.uname = uname == null ? null : uname.trim();
	}

	public Integer getUnumber() {
		return unumber;
	}

	public void setUnumber(Integer unumber) {
		this.unumber = unumber;
	}

	public List getCourseInfos() {
		return courseInfos;
	}

}

   Dao包中的UserInfoMapper.java

  

package org.andy.shop.dao;

import java.util.List;

import org.andy.shop.model.UserInfo;

public interface UserInfoMapper {
    int deleteByPrimaryKey(Integer id);

    int insert(UserInfo record);

    int insertSelective(UserInfo record);

    UserInfo selectByPrimaryKey(Integer id);

    int updateByPrimaryKeySelective(UserInfo record);

    int updateByPrimaryKey(UserInfo record);
    
    List selectAll();
}

mapping 中的配置文件UserInfoMapper.xml




	
		
		
		
	
	
		id, uname, unumber
	
	
	
		delete from
		user_info
		where id = #{id,jdbcType=INTEGER}
	
	
		insert into user_info (id,
		uname, unumber
		)
		values (#{id,jdbcType=INTEGER},
		#{uname,jdbcType=VARCHAR},
		#{unumber,jdbcType=INTEGER}
		)
	
	
		insert into user_info
		
			
				id,
			
			
				uname,
			
			
				unumber,
			
		
		
			
				#{id,jdbcType=INTEGER},
			
			
				#{uname,jdbcType=VARCHAR},
			
			
				#{unumber,jdbcType=INTEGER},
			
		
	
	
		update user_info
		
			
				uname = #{uname,jdbcType=VARCHAR},
			
			
				unumber = #{unumber,jdbcType=INTEGER},
			
		
		where id = #{id,jdbcType=INTEGER}
	
	
		update user_info
		set uname = #{uname,jdbcType=VARCHAR},
		unumber =
		#{unumber,jdbcType=INTEGER}
		where id = #{id,jdbcType=INTEGER}
	

	
		
			
			
			
		


	
	


4、引入Spring并配置相关属性

     在src/main/resources创建spring的配置文件,这里创建了spring.xml,信息如下:

   




	
	

	
	


5、引入Mybatis并配置数据连接池等信息

   5.1、数据连接池druid配置信息 

   配置连接池配置信息在config.properties中,如下:

 

#mysql version database druid setting
validationQuery=SELECT 1
jdbc.url=jdbc:mysql://localhost:3306/shop?useUnicode=true&characterEncoding=utf-8
jdbc.username=root
jdbc.password=12345

  5.2、配置Mybatis相关信息

    以下是mybatis的配置信息:spring-mybatis.xml(ps:名字可随便起)




	
	
		
		
		

		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
		
	

	
	
		
		
		
	

	
		
		
	

	
	
		
	

	
	

	
	
		
			
			
			

			
			
			

		
	
	
	
		
		
	


主要配置数据连接池,事务管理, mybatis关联映射等,事务采用aop的声明式事务。


6、引入日志

     在src/main/resources中添加log4j日志配置信息:

   log4j.properties

### set log levels ###
log4j.rootLogger = INFO , C , D , E 

### console ###
log4j.appender.C = org.apache.log4j.ConsoleAppender
log4j.appender.C.Target = System.out
log4j.appender.C.layout = org.apache.log4j.PatternLayout
log4j.appender.C.layout.ConversionPattern = [springmvc_mybatis_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n

### log file ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = ../logs/springmvc-mybatis-demo.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = INFO 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = [springmvc_mybatis_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n

### exception ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File = ../logs/springmvc-mybatis-demo_error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = [sspringmvc_mybatis_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n

7、创建Service

    在src/main/java中创建相关的org.andy.shop.service包和org.andy.shop.service.Impl包。

    UserService接口:

 

package org.andy.shop.service;

import java.util.List;

import org.andy.shop.model.UserInfo;

/**  
 * 创建时间:2015-1-27 下午5:15:03  
 * @author andy  
 * @version 2.2  
 */

public interface UserService {

	UserInfo getUserById(int id);
	
	List getUsers();
	
	int insert(UserInfo userInfo);
}
   UserServiceImpl实现Service:

package org.andy.shop.service.impl;

import java.util.List;

import org.andy.shop.dao.UserInfoMapper;
import org.andy.shop.model.UserInfo;
import org.andy.shop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * 创建时间:2015-1-27 下午5:22:59
 * 
 * @author andy
 * @version 2.2
 */
@Service("userService")
public class UserServiceImpl implements UserService {

	@Autowired
	private UserInfoMapper userInfoMapper;

	@Override
	public UserInfo getUserById(int id) {
		return userInfoMapper.selectByPrimaryKey(id);
	}

	@Override
	public List getUsers() {
		return userInfoMapper.selectAll();
	}

	@Override
	public int insert(UserInfo userInfo) {
		
		int result = userInfoMapper.insert(userInfo);
		
		System.out.println(result);
		return result;
	}

}

8、测试Spring和Mybatis配置

   在src/test/java中写测试类,检测是否能够读出数据,若能读出则证明Spring+Mybatis整合成功。

TestUserService测试类:

package org.andy.shop.service;

import java.util.List;

import org.andy.shop.model.UserInfo;
import org.apache.log4j.Logger;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import com.alibaba.fastjson.JSON;

/**
 * 创建时间:2015-1-27 下午10:45:38
 * 
 * @author andy
 * @version 2.2
 */
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = { "classpath:spring.xml",
		"classpath:spring-mybatis.xml" })
public class TestUserService {

	private static final Logger LOGGER = Logger
			.getLogger(TestUserService.class);

	@Autowired
	private UserService userService;

	
	@Test
	public void testQueryById1() {
		UserInfo userInfo = userService.getUserById(1);
		LOGGER.info(JSON.toJSON(userInfo));
	}

	@Test
	public void testQueryAll() {
		List userInfos = userService.getUsers();
		LOGGER.info(JSON.toJSON(userInfos));
	}

	@Test
	public void testInsert() {
		UserInfo userInfo = new UserInfo();
		userInfo.setUname("xiaoming");
		userInfo.setUnumber(4);
		int result = userService.insert(userInfo);
		System.out.println(result);
	}
}

若是测试成功,那证明已经成功了一半了。

9、引入SpringMVC

   9.1 配置SpringMVC配置信息

    SpringMVC的配置信息主要包括控制层Controller的bean管理,视图层和控制层配置等等,下面是spring-mvc.xml信息:

 




	
	

	
	
		
			
				text/html;charset=UTF-8
			
		
	

	
	
		
			
				
				
			
		
	

	
	
		
		
		
	

	
	
		
			UTF-8
		
		
			
			32505856
		
		
			4096
		
	


  自动扫描org.andy.shop.controller报下还有@Controller的控制层,注入为bean。

 9.2、Web容器web.xml配置

    web容器配置启动加载的配置文件,设置SpringMVC拦截的请求(此处拦截.htmls结尾的url请求)




	springmvc_mybatis_demo

	
		contextConfigLocation
		classpath:spring.xml,classpath:spring-mybatis.xml
	

	
		encodingFilter
		org.springframework.web.filter.CharacterEncodingFilter
		
			encoding
			utf-8
		
		
			forceEncoding
			true
		
	
	
		encodingFilter
		/*
	

	
		org.springframework.web.context.ContextLoaderListener
	

	
	
		org.springframework.web.util.IntrospectorCleanupListener
	

	
		spring mvc servlet
		rest
		org.springframework.web.servlet.DispatcherServlet
		
			contextConfigLocation
			
				classpath:spring-mvc.xml
			
		
		1
	
	
		rest
		*.htmls
	

	
	
		30
	

	
		index.jsp
	



  9.3、Controller控制层

    在org.andy.shop.controller创建控制层,如UserController.java

 

package org.andy.shop.controller;

import java.util.List;

import org.andy.shop.model.UserInfo;
import org.andy.shop.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

/**  
 * 创建时间:2015-1-28 下午1:17:27  
 * @author andy  
 * @version 2.2  
 */
@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired
	private UserService userService;
	
	@RequestMapping("/showInfo/{userId}")
	public String showUserInfo(ModelMap modelMap, @PathVariable int userId){
		UserInfo userInfo = userService.getUserById(userId);
		modelMap.addAttribute("userInfo", userInfo);
		return "/user/showInfo";
	}
	
	@RequestMapping("/showInfos")
	public @ResponseBody Object showUserInfos(){
		List userInfos = userService.getUsers();
		return userInfos;
	}
}

9.4、视图层

  在WEB-INF创建视图总目录views(为了安全起见一般都在WEB-INF下创建),创建/user/showInfo.jsp视图文件。

 

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>





userInfo



     姓名: ${userInfo.uname}



 9.5、项目总目录结构

   到此为demo以及基本创建完成总目录如下:

     

10、项目测试

    将项目编译,Maven build...输入clean compile package,部署到Tomcat服务器,启动项目。

   测试1:测试第一个url,  http://localhost:8080/springmvc_mybatis_demo/user/showInfo/1.htmls

     


   测试2:测试第二个json数据返回的url,  http://localhost:8080/springmvc_mybatis_demo/user/showInfos.htmls

    

ok,数据正常显示,SpringMVC+Mybatis搭建成功。


点击打开链接

你可能感兴趣的:(Spring,inaction)