ssm(Spring+Springmvc+Mybatis)整合开发在java开发中是目前比较火的框架整合开发,在此用这三个框架整合开发了一个小项目,本项目已开源,源码已经发布到github仓库,大家可以结合源代码阅读本文,由于个人水平有限,如果有错误的地方,还请指出,大家相互学习,一起进步。
实现对数据库中的用户管理,如新增、删除、批量删除、修改、查询等
//创建数据库users
CREATE DATABASE users;
//切换至users数据库
USE users;
//创建用户类型表
CREATE TABLE `tbl_utype` (
`utype_id` int(11) NOT NULL AUTO_INCREMENT,
`utype_name` varchar(255) NOT NULL,
PRIMARY KEY (`utype_id`)
) ENGINE=InnoDB AUTO_INCREMENT=15 DEFAULT CHARSET=utf8;
//创建用户表
CREATE TABLE `tbl_user` (
`user_id` int(11) NOT NULL AUTO_INCREMENT,
`user_name` varchar(255) NOT NULL,
`gender` char(1) ,
`email` varchar(255) ,
`ut_id` int(11) ,
PRIMARY KEY (`user_id`),
KEY `ut_id` (`ut_id`),
CONSTRAINT `tbl_user_ibfk_1` FOREIGN KEY (`ut_id`) REFERENCES `tbl_utype` (`utype_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;
<spring.version>5.2.1.RELEASEspring.version>
<aspectj.version>1.9.2aspectj.version>
<slf4j.version>1.6.6slf4j.version>
<log4j.version>1.2.17log4j.version>
<mysql.version>5.1.6mysql.version>
<mybatis.version>3.4.5mybatis.version>
<aspectj.version>1.6.8aspectj.version>
<junit.version>4.12junit.version>
<dependency>
<groupId>org.hibernate.validatorgroupId>
<artifactId>hibernate-validatorartifactId>
<version>6.1.0.Finalversion>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.10.0version>
dependency>
<dependency>
<groupId>com.github.pagehelpergroupId>
<artifactId>pagehelperartifactId>
<version>5.1.10version>
dependency>
<dependency>
<groupId>org.mybatis.generatorgroupId>
<artifactId>mybatis-generator-coreartifactId>
<version>1.3.0version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-aopartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>${aspectj.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-testartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>${spring.version}version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>${mybatis.version}version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.0version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>${mysql.version}version>
dependency>
<dependency>
<groupId>c3p0groupId>
<artifactId>c3p0artifactId>
<version>0.9.1.2version>
<type>jartype>
<scope>compilescope>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>${junit.version}version>
<scope>compilescope>
dependency>
<generatorConfiguration>
<context id="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true" />
commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost/users"
userId="root"
password="Pankx0128">
jdbcConnection>
<javaTypeResolver >
<property name="forceBigDecimals" value="false" />
javaTypeResolver>
<javaModelGenerator
targetPackage="com.pankx.bean"
targetProject="./src/main/java">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
javaModelGenerator>
<sqlMapGenerator
targetPackage="mappers"
targetProject="./src/main/resources">
<property name="enableSubPackages" value="true" />
sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER"
targetPackage="com.pankx.dao"
targetProject="./src/main/java">
<property name="enableSubPackages" value="true" />
javaClientGenerator>
<table tableName="tbl_user" domainObjectName="User"/>
<table tableName="tbl_utype" domainObjectName="UType"/>
context>
generatorConfiguration>
2.编写执行逆向工程的测试类,并执行,此时项目目录会生成相应的文件,代码实现如下
public static void main(String[] arg) throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("mbg.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
<filter>
<filter-name>characterEncodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>UTF-8param-value>
init-param>
<init-param>
<param-name>forceRequestEncodingparam-name>
<param-value>trueparam-value>
init-param>
<init-param>
<param-name>forceResponseEncodingparam-name>
<param-value>trueparam-value>
init-param>
filter>
<filter-mapping>
<filter-name>characterEncodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<filter>
<filter-name>httpPutFormContentFilterfilter-name>
<filter-class>org.springframework.web.filter.HttpPutFormContentFilterfilter-class>
filter>
<filter-mapping>
<filter-name>httpPutFormContentFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationconfig.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd">
<context:component-scan base-package="com.pankx" >
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
bean>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
beans>
<context:component-scan base-package="com.pankx">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
context:component-scan>
<context:property-placeholder location="classpath:mysqlproperties.properties"/>
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
bean>
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor"/>
array>
property>
<property name="dataSource" ref="dataSource"/>
<property name="mapperLocations" value="classpath:mappers/*.xml"/>
bean>
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:advice id="transactionInterceptor" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="*"/>
<tx:method name="get*" read-only="true"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:advisor advice-ref="transactionInterceptor" pointcut="execution(* com.pankx.service.*.*(..))"/>
aop:config>
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.pankx.dao"/>
bean>
<div class="container">
<div class="row">
<div class="col-sm-12"><h1>用户列表h1>div>
div>
<div class="row">
<div class="col-sm-2">div>
<div class="col-sm-offset-10">
<button class="btn btn-primary">新增button>
<button class="btn btn-danger">删除button>
div>
div>
<div class="row">
<div class="col-sm-12">
<table class="table table-hover" id="user_table">
<thead>
<th>用户IDth>
<th>用户名th>
<th>姓别th>
<th>邮箱th>
<th>用户类型th>
<th>操作th>
thead>
<tbody>
<td>1td>
<td>test1td>
<td>男td>
<td>[email protected]td>
<td>普通用户td>
<td>
<button class="btn btn-primary">编辑button>
<button class="btn btn-danger">删除button>
td>
tbody>
table>
div>
div>
<div class="row">
<div class="col-sm-6">当前第1页,总1000页,总10000记录div>
<div class="col-sm-6">
<nav aria-label="Page navigation">
<ul class="pagination">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">«span>
a>
li>
<li><a href="#">1a>li>
<li><a href="#">2a>li>
<li><a href="#">3a>li>
<li><a href="#">4a>li>
<li><a href="#">5a>li>
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">»span>
a>
li>
ul>
nav>
div>
div>
div>
/**
* 查询所有用户信息,返回以json格式返回
* @param pn
* @return
*/
@RequestMapping(value = "/user",method = GET)
@ResponseBody
public Msg getusers(@RequestParam(value = "pn",defaultValue = "1") int pn){
//开始分页每页记录条数为5
PageHelper.startPage(pn,5);
//查询所有用户记录
List<User> list = userService.getUsers();
//封装查询结果
PageInfo pageInfo = new PageInfo(list,5);
Msg msg = Msg.success().add("pageinfo",pageInfo);
return msg;
}
<div class="container">
<div class="row">
<div class="col-sm-12"><h1>用户列表h1>div>
div>
<div class="row">
<div class="col-sm-2">div>
<div class="col-sm-offset-10">
<button class="btn btn-primary">新增button>
<button class="btn btn-danger">删除button>
div>
div>
<div class="row">
<div class="col-sm-12">
<table class="table table-hover" id="user_table">
<thead>
<th>用户IDth>
<th>用户名th>
<th>姓别th>
<th>邮箱th>
<th>用户类型th>
<th>操作th>
thead>
<tbody>tbody>
table>
div>
div>
<div class="row">
<div class="col-sm-6" id="page_msg">div>
<div class="col-sm-6">
<nav aria-label="Page navigation">
<ul class="pagination">
<li>
<a href="#" aria-label="Previous">
<span aria-hidden="true">«span>
a>
li>
<li><a href="#">1a>li>
<li><a href="#">2a>li>
<li><a href="#">3a>li>
<li><a href="#">4a>li>
<li><a href="#">5a>li>
<li>
<a href="#" aria-label="Next">
<span aria-hidden="true">»span>
a>
li>
ul>
nav>
div>
div>
div>
<script type="text/javascript">
//页面加载完成发送ajax请求到服务器获取数据
$(function(){
get_emps(1);
});
//发送ajax请求方法
function get_emps (pn){
$.ajax({
url:"${APP_PATH}/user",
data:"pn="+ pn,
type:"GET",
success:function(data){
console.log(data);
//解析数据到table
user_table(data);
//处理显示分布的信息
page_msg(data);
}
});
}
//解析数据到table
function user_table(data){
//清空tbody内容再添加
$("#user_table tbody").empty();
var users = data.reldata.pageinfo.list;
console.log(users);
//遍历返回的数据并解析显示到table
$.each(users,function(index,item){
//用户id单元格
var useridTd = $(" ").append(item.userId);
//用户名单元格
var userNameTd = $(" ").append(item.userName);
//用户姓别单元格
var genderTd = $(" ").append(item.gender=="M"?"男":"女");
//用户邮箱单元格
var emailTd = $(" ").append(item.email);
//用户类型单元格
var uTypeTd = $(" ").append(item.uType.utypeName);
//编辑按钮
var edit_btn = $("").addClass("btn btn-primary btn-sm").append("").addClass("glyphicon glyphicon-pencil").append("编辑");
//删除按钮
var del_btn = $("").addClass("btn btn-danger btn-sm").append("").addClass("glyphicon glyphicon-trash").append("删除");
var btnTd = $(" ").append(edit_btn).append(" ").append(del_btn);
$(" ").append(useridTd).append(userNameTd).append(genderTd).append(emailTd).append(uTypeTd).append(btnTd).appendTo($("#user_table tbody"));
});
}
//处理分页信息
function page_msg(data){
var pageInfo = data.reldata.pageinfo;
$("#page_msg").append("当前第"+pageInfo.pageNum+"页,总"+pageInfo.pages+"页,总"+pageInfo.total+"记录")
}
script>