博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SpringMvc+Spring+Mybatis+Maven整合
阅读量:5843 次
发布时间:2019-06-18

本文共 13491 字,大约阅读时间需要 44 分钟。

一、建立数据库表,使用generator自动生成相关代码;

/*SQLyog Ultimate v11.24 (32 bit)MySQL - 5.1.62-community : Database - mydb**********************************************************************//*!40101 SET NAMES utf8 */;/*!40101 SET SQL_MODE=''*/;/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;CREATE DATABASE /*!32312 IF NOT EXISTS*/`mydb` /*!40100 DEFAULT CHARACTER SET gbk */;USE `mydb`;/*Table structure for table `photo` */DROP TABLE IF EXISTS `photo`;CREATE TABLE `photo` (  `pid` int(11) NOT NULL AUTO_INCREMENT,  `pname` varchar(50) NOT NULL,  `fname` varchar(50) NOT NULL,  `uname` varchar(50) NOT NULL,  `fdate` date DEFAULT NULL,  `tid` int(11) NOT NULL,  PRIMARY KEY (`pid`),  KEY `fk_tid` (`tid`),  CONSTRAINT `fk_tid` FOREIGN KEY (`tid`) REFERENCES `type` (`tid`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=gbk;/*Data for the table `photo` */insert  into `photo`(`pid`,`pname`,`fname`,`uname`,`fdate`,`tid`) values (1,'花好月圆','test.jpg','张飞','2016-07-19',1),(2,'奋斗奋斗','aa.jpg','房交会的积分','2016-07-19',12);/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;

generator工具下载:http://download.csdn.net/detail/s0009527/9883125

二、创建maven工程,并将生成的代码copy入工程中;

三、先整合Spring+Mybatis,在pom文件中引入相关的jar包;()

       需要在中央仓库中找到如下几个包导入,spring-core、mybatis、mybatis-spring、junit、mysql-connector-java(MySQL驱动包)、druid(配置数据源的jar包).......;

org.springframework
spring-jdbc
3.2.0.RELEASE
org.springframework
spring-context
3.2.0.RELEASE
org.springframework
spring-core
3.2.0.RELEASE
org.mybatis
mybatis
3.1.1
org.mybatis
mybatis-spring
1.1.1
mysql
mysql-connector-java
5.1.21
junit
junit
4.11
test
com.alibaba
druid
0.2.9
org.aspectj
aspectjweaver
1.7.1
org.codehaus.jackson
jackson-mapper-asl
1.9.11
commons-fileupload
commons-fileupload
1.2.2
javax.servlet
servlet-api
3.0-alpha-1
log4j
log4j
1.2.17
com.alibaba
fastjson
1.1.26
org.springframework
spring-tx
3.2.0.RELEASE

四、添加并修改配置文件(spring.xml、spring-mybatis.xml)

 

config.properties文件

#hibernate.dialect=org.hibernate.dialect.OracleDialect#driverClassName=oracle.jdbc.driver.OracleDriver#validationQuery=SELECT 1 FROM DUAL#jdbc_url=jdbc:oracle:thin:@localhost:1521:orcl#jdbc_username=sypro#jdbc_password=syprohibernate.dialect=org.hibernate.dialect.MySQLDialectdriverClassName=com.mysql.jdbc.DrivervalidationQuery=SELECT 1jdbc_url=jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNulljdbc_username=rootjdbc_password=android#hibernate.dialect=org.hibernate.dialect.SQLServerDialect#driverClassName=net.sourceforge.jtds.jdbc.Driver#validationQuery=SELECT 1#jdbc_url=jdbc:jtds:sqlserver://127.0.0.1:1433/sy#jdbc_username=sa#jdbc_password=123456#hibernate.dialect=org.hibernate.dialect.DerbyDialect#driverClassName=org.apache.derby.jdbc.EmbeddedDriver#validationQuery=SELECT 1#jdbc_url=jdbc:derby:sy;create=true#jdbc_username=sypro#jdbc_password=sypro#jndiName=java:comp/env/dataSourceNamehibernate.hbm2ddl.auto=updatehibernate.show_sql=falsehibernate.format_sql=truesessionInfoName=sessionInfouploadFieldName=filedatauploadFileMaxSize=20971520uploadFileExts=txt,rar,zip,doc,docx,xls,xlsx,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,miduploadDirectory=attached

log4j.properties文件

log4j.rootLogger=DEBUG,Console,Filelog4j.appender.Console=org.apache.log4j.ConsoleAppenderlog4j.appender.Console.Target=System.outlog4j.appender.Console.layout=org.apache.log4j.PatternLayoutlog4j.appender.Console.layout.ConversionPattern=[%c]%m%nlog4j.appender.File=org.apache.log4j.RollingFileAppender log4j.appender.File.File=mybatis.loglog4j.appender.File.MaxFileSize=10MBlog4j.appender.File.Threshold=ALLlog4j.appender.File.layout=org.apache.log4j.PatternLayoutlog4j.appender.File.layout.ConversionPattern=[%p][%d{yyyy-MM-dd HH\:mm\:ss,SSS}][%c]%m%n

spring.xml文件

spring-mybatis.xml文件

sy.service.*

web.xml文件

mybatis
contextConfigLocation
classpath:spring.xml,classpath:spring-mybatis.xml
字符集过滤器
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
字符集编码
encoding
UTF-8
encodingFilter
/*
spring监听器
org.springframework.web.context.ContextLoaderListener
org.springframework.web.util.IntrospectorCleanupListener
spring mvc servlet
springMvc
org.springframework.web.servlet.DispatcherServlet
spring mvc 配置文件
contextConfigLocation
classpath:spring-mvc.xml
1
springMvc
*.do
/index.jsp
15

五、测试Spring+Mybatis是否整合成功;

package sy.service;import sy.model.Photo;public interface PhotoServiceI {    public Photo getPhotoById(Integer id);}
package sy.service;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import sy.dao.PhotoMapper;import sy.model.Photo;@Service("PhotoServiceImp")public class PhotoServiceImp implements PhotoServiceI {    private PhotoMapper photo;    public PhotoMapper getPhoto() {        return photo;    }    @Autowired    public void setPhoto(PhotoMapper photo) {        this.photo = photo;    }    @Override    public Photo getPhotoById(Integer id) {        return  photo.selectByPrimaryKey(Integer.valueOf(id));                    }}

Junit的测试方法;

import org.junit.*;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;import sy.model.Photo;import sy.service.PhotoServiceI;public class testPhoto {    PhotoServiceI pi;    ApplicationContext ac;    @Before    public void before(){        ac=new ClassPathXmlApplicationContext(new String[]{"spring.xml","spring-mybatis.xml"});        pi= (PhotoServiceI)ac.getBean("PhotoServiceImp");    }        @Test    public void getPhoto(){        Photo photo = pi.getPhotoById(2);        System.out.println(photo.getPname());    }}

spring的测试方法:

①:添加spring-test的jar包

org.springframework
spring-test
3.2.0.RELEASE

②: 要么在测试类的上面添加@RunWith(SpringJUnit4ClassRunner.class)要么让测试类继承自SpringJUnit4ClassRunner;

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 sy.model.Photo;import sy.service.PhotoServiceI;@RunWith(SpringJUnit4ClassRunner.class)@ContextConfiguration(locations = { "classpath:spring.xml", "classpath:spring-mybatis.xml" })public class testPhoto {    PhotoServiceI pi;        public PhotoServiceI getPi() {        return pi;    }    @Autowired    public void setPi(PhotoServiceI pi) {        this.pi = pi;    }        @Test    public void getPhoto(){        Photo photo = pi.getPhotoById(2);        System.out.println(photo.getPname());    }}

六、整合SpringMvc+Spring+Mybatis,在pom文件中导入SpringMVC相关的jar包;

org.springframework
spring-webmvc
3.2.0.RELEASE

七、添加并修改 spring-mvc.xml 文件;

spring-mvc.xml文件

text/html;charset=UTF-8
UTF-8
32505856
4096

八、添加controller并进行测试;

import javax.servlet.http.HttpServletRequest;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.RequestMapping;import sy.model.Photo;import sy.service.PhotoServiceI;@Controller@RequestMapping("PhotoController")public class PhotoController {    PhotoServiceI pi;    public PhotoServiceI getPi() {        return pi;    }    @Autowired    public void setPi(PhotoServiceI pi) {        this.pi = pi;    }    @RequestMapping("getPhoto/{id}")    public String getPhoto(@PathVariable Integer id,HttpServletRequest request){                Photo photo = pi.getPhotoById(id);        request.setAttribute("photo", photo);                return "getPhoto";    }}

http://localhost:8080/XXX/PhotoController/getPhoto/1.do

 

注意事项:

①:测试时出现问题,一般在业务逻辑没问题的情况下,应该都是-----》jar包没导全、同一类型的jar包的版本不对应(尽量让版本统一)、jar包的maven加载顺序问题(将同一类型的jar包放到一起,高版本的放在前面,低版本的放在后面,那么即使后面的jar是低版本的,也会加载和前面jar版本一致的高版本的jar,主要是mybatis-spring依赖的jar包的问题,classloader);

 

②:maven发布到Tomcat之前一定要让其编译下,用run as--> maven  Install一下,然后发布到Tomcat

转载于:https://www.cnblogs.com/YLQBL/p/7083944.html

你可能感兴趣的文章
富文本编辑器提交内容 报错
查看>>
css3学习 理论之弹性盒模型
查看>>
h5做的时钟
查看>>
Oracle SQL: TO_CHAR and TO_NUMBER 笔记
查看>>
Unity3D--学习太空射击游戏制作(二)
查看>>
axios 中断请求
查看>>
Spring的注解配置与XML配置之间的比较
查看>>
2014手机分析图
查看>>
Linux PID 1 和 Systemd
查看>>
一元多项式相加
查看>>
commandLink/commandButton/ajax backing bean action/listener method not invoked (转)
查看>>
js计算时间差,包括计算,天,时,分,秒
查看>>
使用rsync在windows(服务端)与linux(客户端)之间同步
查看>>
软件工作的大环境
查看>>
vs2013中,自定义mvc 添加视图脚手架
查看>>
移动端Web开发调试之Chrome远程调试(Remote Debugging)
查看>>
Eclipse插件开发中的选择监听机制(Selection Provider-Listener)
查看>>
Java类加载过程及static详解
查看>>
background-color和background-image相关细节
查看>>
如何学好C#
查看>>