一、开发环境-自行配置这里就不多说了,重要部分开始
Eclipse:eclipse-jee-luna-SR1a-win32;
JDK:jdk-1.7.0_80-windows-64.exe;
MySql:MySQL版本是-8.0.11;
二、创建Maven项目
1.创建父项目
NEW->PROJECT->MAVEN->Maven Project,点击next>进入下一步,可以看到New Maven Project界面,
点击Next >进入下一步,进入Select an Archetype界面,在Filter:输入simple,选择org.apache.maven.archetypes,
点击next>,进入Enter a group id for the artifact界面,
填写好Group Id和Artifact Id,我这里在ssm分组下创建了一个parent项目。点击Finish。
2.创建子项目
选中parent项目,右键,选择new->project->maven->maven Module,点击Next,进入Enter a module name界面,
填写Module Name,点击next>,进入Select an Archetype界面,
在Filter输入start,选择maven-archetype-quickstart,点击next>,进入Specify Archetype parameters界面,
修改Package,点击Finish。就会创建parent项目下的一个子项目dao。
打开parent项目的pom.xml
可以看到有个
接着我们按照上述方法继续创建子项目service和model。
创建web子项目时,在进入Select an Archetype界面,在Filter填写web,选择org.apache.maven.archetypes.
点击next>,修改package,最后点击Finish。
这样,我们的父项目和所有子项目就已经创建完了。如下图:
右键web子项目(其他子项目操作相同),build path->configure build path,打开Java Build Path,点击Libraies页,
如图,删除JRE System Lirary[J2SE-1.5],重新选择你自己的jdk;
三、添加Springmvc+MyBatis依赖的jar包
在父类的pom.xml中添加SpringMvc+MyBatis所有依赖包
4.0.0
ssm
parent
0.0.1-SNAPSHOT
pom
http://maven.apache.org
website
scp://webhost.company.com/www/website
UTF-8
4.0.2.RELEASE
3.2.6
1.7.7
1.2.17
dao
service
model
web
junit
junit
4.11
test
org.springframework
spring-core
${spring.version}
org.springframework
spring-web
${spring.version}
org.springframework
spring-oxm
${spring.version}
org.springframework
spring-tx
${spring.version}
org.springframework
spring-jdbc
${spring.version}
org.springframework
spring-webmvc
${spring.version}
org.springframework
spring-aop
${spring.version}
org.springframework
spring-context-support
${spring.version}
org.springframework
spring-test
${spring.version}
org.mybatis
mybatis
${mybatis.version}
org.mybatis
mybatis-spring
1.2.2
javax
javaee-api
7.0
provided
javax
javaee-api
mysql
mysql-connector-java
5.1.46
commons-dbcp
commons-dbcp
1.2.2
jstl
jstl
1.2
log4j
log4j
${log4j.version}
com.alibaba
fastjson
1.1.41
org.slf4j
slf4j-api
${slf4j.version}
org.slf4j
slf4j-log4j12
${slf4j.version}
org.codehaus.jackson
jackson-mapper-asl
1.9.13
commons-fileupload
commons-fileupload
1.3.1
commons-io
commons-io
2.4
commons-codec
commons-codec
1.9
org.mybatis.generator
mybatis-generator-core
1.3.5
com.fasterxml.jackson.dataformat
jackson-dataformat-xml
2.3.2
com.fasterxml.jackson.core
jackson-databind
2.3.2
com.fasterxml.jackson.core
jackson-annotations
2.3.2
com.fasterxml.jackson.core
jackson-core
2.3.2
四,自动生成代码
1.创建数据库和表
/*
Navicat MySQL Data Transfer
Source Server : mysql
Source Server Version : 80011
Source Host : 127.0.0.1:3306
Source Database : alsyuan
Target Server Type : MYSQL
Target Server Version : 80011
File Encoding : 65001
Date: 2018-12-12 17:01:44
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for t_user
-- ----------------------------
DROP TABLE IF EXISTS `t_user`;
CREATE TABLE `t_user` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
`phone` varchar(20) DEFAULT NULL,
`email` varchar(20) DEFAULT NULL,
`qq` varchar(20) DEFAULT NULL,
`birth` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=69 DEFAULT CHARSET=utf8 COMMENT='用户表';
2.利用mybatis-generator-core-1.3.5.jar自动创建代码
1.在本地创建一个文件夹(我在D盘创建了一个generator文件夹);
2.在generator文件夹下创建一个src文件夹,
3.添加2个jar包mybatis-generator-core-1.3.5.jar和mysql-connector-java-5.1.30.jar
4.在创建一个generatorConfig.xml
5创建一个start.bat
set current_path="%cd%"
java -jar mybatis-generator-core-1.3.5.jar -configfile generatorConfig.xml -overwrite
pause
exit
整体目录结构如下:
然后运行start.bat(双击),则自动生成了dao,mapping,model代码
五、添加子项目之间的依赖
1.给web子项目添加service子项目的依赖
打开web项目的pom.xml
给
完整web/pom.xml如下:
4.0.0
parent
ssm
0.0.1-SNAPSHOT
web
war
UTF-8
1.7
1.7
ssm
service
0.0.1-SNAPSHOT
web
org.apache.tomcat.maven
tomcat7-maven-plugin
2.2
2.给service子项目添加dao子项目的依赖
打开service项目的pom.xml
给
完整service/pom.xml如下:
4.0.0
parent
ssm
0.0.1-SNAPSHOT
service
service
http://maven.apache.org
UTF-8
1.7
1.7
ssm
dao
0.0.1-SNAPSHOT
3.给dao子项目添加model子项目的依赖
打开dao项目的pom.xml
给
完整dao/pom.xml如下:
4.0.0
parent
ssm
0.0.1-SNAPSHOT
dao
dao
http://maven.apache.org
UTF-8
1.7
1.7
ssm
model
0.0.1-SNAPSHOT
整个项目依赖关系添加完毕:web依赖service,service依赖dao,dao依赖model,parent是父项目
六、添加代码
1.model子项目创建com.gwx.model包,将上面第四节自动生成model目录下的代码复制到com.gwx.model包下;
2.dao子项目src/main/java下创建com.gwx.dao和在src/main/resources下创建mapping包,将上面第四节自动生成dao目录下的的代码复制到
com.gwx.dao包下,将mapping目录下自动生成的代码复制到mapping包下;
3.service子项目创建com.gwx.service包和com.gwx.service.impl包,在com.gwx.service包下创建接口IUserService
public interface IUserService {
List queryUserList();
int deleteByPrimaryKey(Integer id);
int insert(User record);
int insertSelective(User record);
User selectByPrimaryKey(Integer id);
int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
}
在com.gwx.service.impl包下创建UserServiceImpl
@Service("userService")
public class UserServiceImpl implements IUserService{
@Resource
private UserMapper userDao;
public List queryUserList(){
return this.userDao.queryUserList();
}
@Override
public int deleteByPrimaryKey(Integer id) {
return this.userDao.deleteByPrimaryKey(id);
}
@Override
public int insert(User record) {
return this.userDao.insert(record);
}
@Override
public int insertSelective(User record) {
return this.userDao.insertSelective(record);
}
@Override
public User selectByPrimaryKey(Integer id) {
return this.userDao.selectByPrimaryKey(id);
}
@Override
public int updateByPrimaryKeySelective(User record) {
return this.userDao.updateByPrimaryKeySelective(record);
}
@Override
public int updateByPrimaryKey(User record) {
return this.userDao.updateByPrimaryKey(record);
}
}
七、Spring与MyBatis的整合
1.在子项目web项目中的resources目录下创建jdbc.properties
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/alsyuan?useUnicode=true&characterEncoding=UTF-8
username=root
password=root
#定义初始连接数
initialSize=0
#定义最大连接数
maxActive=20
#定义最大空闲
maxIdle=20
#定义最小空闲
minIdle=1
#定义最长等待时间
maxWait=60000
2.Log4j的配置(可有可无)
在你需要查看日志的子项目的resources目录下创建log4j.properties
#定义LOG输出级别
log4j.rootLogger=INFO,Console,File
#定义日志输出目的地为控制台
log4j.appender.Console=org.apache.log4j.ConsoleAppender
log4j.appender.Console.Target=System.out
#可以灵活地指定日志输出格式,下面一行是指定具体的格式
log4j.appender.Console.layout = org.apache.log4j.PatternLayout
log4j.appender.Console.layout.ConversionPattern=[%c] - %m%n
#文件大小到达指定尺寸的时候产生一个新的文件
log4j.appender.File = org.apache.log4j.RollingFileAppender
#指定输出目录
log4j.appender.File.File = log4j/web/log.log
#定义文件最大大小
log4j.appender.File.MaxFileSize = 10MB
#输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志
log4j.appender.File.Threshold = ALL
log4j.appender.File.layout = org.apache.log4j.PatternLayout
log4j.appender.File.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
3.在子项目dao层的resources目录下创建spring-mybatis.xml
4.Junit测试
先将parent/pom.xml,model/pom.xml,dao/pom.xml,service/pom.xml中的
删除;将web/pom.xml
中的修改为
再右键web项目->properties->Java Compiler->修改为和你当前jdk版本一致;(我本地的jdk版本为1.8)如图
在web项目中的src/main/java包下创建com/gwx/test包,创建TestMyBatis.java
@RunWith(SpringJUnit4ClassRunner.class) // 表示继承了SpringJUnit4ClassRunner类
@ContextConfiguration(locations={"classpath:spring-mybatis.xml"})
public class TestMyBatis {
@Resource
private IUserService userService;
@Test
public void test1() {
List list = userService.queryUserList();
for (int i = 0; i < list.size(); i++) {
User user = list.get(i);
System.out.println(user.toString());
}
}
@Test
public void test2() {
int key = userService.deleteByPrimaryKey(10);
System.out.println(key);
}
@Test
public void test3() {
User record=new User();
record.setId(5);
record.setName("simple");
record.setPhone("55555");
record.setEmail("[email protected]");
record.setQq("5555555555");
record.setBirth(new Date());
int insert = userService.insert(record);
System.out.println(insert);
}
@Test
public void test4() {
User record=new User();
record.setId(6);
record.setName("simple");
record.setPhone("55555");
record.setEmail("[email protected]");
record.setQq("5555555555");
record.setBirth(new Date());
int selective = userService.insertSelective(record);
System.out.println(selective);
}
@Test
public void test5() {
User user = userService.selectByPrimaryKey(1);
System.out.println(user.toString());
}
@Test
public void test6() {
User record=new User();
record.setId(68);
record.setName("shasha");
int selective = userService.updateByPrimaryKeySelective(record);
System.out.println(selective);
}
@Test
public void test7() {
User record=new User();
record.setId(68);
record.setName("shasha");
int key = userService.updateByPrimaryKey(record);
System.out.println(key);
}
}
运行。控制台出现'张三'则表示整合成功!
八、SpringMVC整合
在web子项目的resources下创建spring-mvc.xml
text/plain;charset=UTF-8
application/json;charset=UTF-8
application/json;charset=UTF-8
application/xml;charset=UTF-8
text/html;charset=UTF-8
text/plain;charset=UTF-8
text/xml;charset=UTF-8
text/javascript;charset=UTF-8
再配置web.xml
Archetype Created Web Application
contextConfigLocation
classpath:spring-mybatis.xml
encodingFilter
org.springframework.web.filter.CharacterEncodingFilter
true
encoding
UTF-8
encodingFilter
/*
org.springframework.web.context.ContextLoaderListener
org.springframework.web.util.IntrospectorCleanupListener
SpringMVC
org.springframework.web.servlet.DispatcherServlet
contextConfigLocation
classpath:spring-mvc.xml
1
true
SpringMVC
/
/login.html
在web子项目的 Java Resources下创建package com.gwx.controller,在com.gwx.controller下面创建UserController.java
@Controller
@RequestMapping("/user")
public class UserController {
@Resource
private IUserService userService;
@RequestMapping("/queryUserList")
public String queryUserList(HttpServletRequest request, Model model) {
List user=this.userService.queryUserList();
model.addAttribute("user", user);
return "user";
}
@RequestMapping("/deleteByPrimaryKey")
public String deleteByPrimaryKey(HttpServletRequest request, Model model,Integer id) {
int key = this.userService.deleteByPrimaryKey(id);
model.addAttribute("key", key);
return "user";
}
@RequestMapping("/insert")
public String insert(HttpServletRequest request, Model model,User record) {
int insert = userService.insert(record);
model.addAttribute("insert", insert);
return "user";
}
@RequestMapping("/insertSelective")
public String insertSelective(HttpServletRequest request, Model model,User record) {
int selective = userService.insertSelective(record);
model.addAttribute("selective", selective);
return "user";
}
//http://localhost:8080/web/user/showUser?id=1
@RequestMapping("/showUser")
public String toIndex(HttpServletRequest request, Model model,Integer id) {
User user = this.userService.selectByPrimaryKey(id);
model.addAttribute("user", user);
return "user";
}
@RequestMapping("/updateByPrimaryKeySelective")
public String updateByPrimaryKeySelective(HttpServletRequest request, Model model) {
User record=new User();
int selective = userService.updateByPrimaryKeySelective(record);
model.addAttribute("selective",selective);
return "user";
}
@RequestMapping("/updateByPrimaryKey")
public String updateByPrimaryKey(HttpServletRequest request, Model model,User record) {
int key = userService.updateByPrimaryKey(record);
model.addAttribute("key",key);
return "user";
}
//http://localhost:8080/web/user/showJson?id=1
@RequestMapping("/showJson")
@ResponseBody
public String showJson(int id) {
User user = this.userService.selectByPrimaryKey(id);
String jSon = JacksonUtil.toJSon(user);
return jSon;
}
}
在model子项目下创建package com.gwx.util,在com.gwx.util下面创建JacksonUtil.java和httpModel.java
public class HttpModel implements Serializable{
private static final long serialVersionUID = 1L;
private int code = 0;
private Object object;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
}
public final class JacksonUtil {
public static ObjectMapper objectMapper;
/**
* 使用泛型方法,把json字符串转换为相应的JavaBean对象。
* (1)转换为普通JavaBean:readValue(json,Student.class)
* (2)转换为List,如List,将第二个参数传递为Student
* [].class.然后使用Arrays.asList();方法把得到的数组转换为特定类型的List
* @param jsonStr
* @param valueType
* @return
*/
public static T readValue(String jsonStr, Class valueType) {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
}
try {
return objectMapper.readValue(jsonStr, valueType);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* json数组转List
* @param jsonStr
* @param valueTypeRef
* @return
*/
public static T readValue(String jsonStr, TypeReference valueTypeRef) {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
}
try {
return objectMapper.readValue(jsonStr, valueTypeRef);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 把JavaBean转换为json字符串
* @param object
* @return
*/
public static String toJSon(Object object) {
if (objectMapper == null) {
objectMapper = new ObjectMapper();
}
try {
return objectMapper.writeValueAsString(object);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
/**
* 生成手机令牌
* @return
*/
public final static String generateToken() {
return UUID.randomUUID().toString().replace("-", "");
}
public static String toHttpJson(int code, Object object) {
HttpModel model = new HttpModel();
model.setCode(code);
model.setObject(object);
return JacksonUtil.toJSon(model);
}
}
在web项目的src/main/webapp/WEB-INF下创建jsp文件夹,然后创建user.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
Insert title here
${user.name}
此时,springmvc和json都已经整合完成!
开始运行web项目—>右键web->Run as->Run configurations->
左侧选择Maven Build
右侧在Name出填写你的name
在Main页的Base directory出选择web项目,在Goals出输入 tomcat7:run
在JRE页选择你自己的jdk
然后切换到Main页,点击Run。
如果没有报错或者异常,应该就没问题了!
然后springmvc测试
在浏览器上输入网址http://localhost:8080/web/user/showUser?id=1就会返回到user.jsp页面。如图:
json测试:输入网址http://localhost:8080/web/user/showJson?id=1返回结果:
OK!
九、总结
用到MyBatis逆向工程generator生成dao,mapper,model主要减少开发时间,提高开发效率
dao层方法跟mapper属性要一致
mysql版本jar遇到报错:### Cause: java.sql.SQLException: Could not retrieve transation read-only status server
以上就是最近整合的springmvc+mybatis+json的Maven管理一整套项目!是我亲自一步步搭建成功!
转载注明出处:https://mp.csdn.net/postedit/84975778