Ssm 简单 crud 项目

160
Ssm 简单 crud 项目 . 工程搭建 1. 打开 intellij IDEA 创建工程,使用 maven webapp 模板创建 指定 maven 位置和 mavenhome 的位置

Transcript of Ssm 简单 crud 项目

Page 1: Ssm 简单 crud 项目

Ssm简单 crud项目一. 工程搭建

1. 打开 intellij IDEA 创建工程,使用 maven的 webapp模板创建

指定 maven 位置和 mavenhome 的位置

Page 2: Ssm 简单 crud 项目

点击 next,finish 后创建完成,点击右下角的 auto-import 自动导入依赖

2. 补全缺少的文件夹,在 main 下创建 java,resources,test 文件夹并指定为运行目录

Page 3: Ssm 简单 crud 项目

3. 接下来指定 web 目录,打开 project structure,新建 web 目录

Page 4: Ssm 简单 crud 项目

创建完成后再右侧右键点击 putintoroot

Page 5: Ssm 简单 crud 项目

完成后看到 webapp 上面有一个蓝点说明配置完成

4. 在 pom.xml 文件中导入依赖(将原来的位置替换为下面的代码即可),注意更改半角全角

<properties>

<project.build.sourceEncoding>UTF-8</project.build

.sourceEncoding>

<maven.compiler.source>1.8</maven.compiler.source>

Page 6: Ssm 简单 crud 项目

<maven.compiler.target>1.8</maven.compiler.target>

<!--设置版本号-->

<srping.version>4.0.2.RELEASE</srping.version>

<mybatis.version>3.2.8</mybatis.version>

<slf4j.version>1.7.12</slf4j.version>

<log4j.version>1.2.17</log4j.version>

<druid.version>1.0.9</druid.version>

</properties>

<dependencies>

<dependency>

<groupId>junit</groupId>

<artifactId>junit</artifactId>

<version>4.11</version>

</dependency>

<!-- spring框架包 -->

<dependency>

<groupId>org.aspectj</groupId>

<artifactId>aspectjweaver</artifactId>

<version>1.6.8</version>

</dependency>

Page 7: Ssm 简单 crud 项目

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-test</artifactId>

<version>${srping.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-core</artifactId>

<version>${srping.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-oxm</artifactId>

<version>${srping.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-tx</artifactId>

<version>${srping.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

Page 8: Ssm 简单 crud 项目

<artifactId>spring-jdbc</artifactId>

<version>${srping.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-aop</artifactId>

<version>${srping.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context</artifactId>

<version>${srping.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-context-support</artifactId>

<version>${srping.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-expression</artifactId>

Page 9: Ssm 简单 crud 项目

<version>${srping.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-orm</artifactId>

<version>${srping.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-web</artifactId>

<version>${srping.version}</version>

</dependency>

<dependency>

<groupId>org.springframework</groupId>

<artifactId>spring-webmvc</artifactId>

<version>${srping.version}</version>

</dependency>

<!-- spring框架包 -->

<!-- mybatis框架包 -->

<dependency>

<groupId>org.mybatis</groupId>

Page 10: Ssm 简单 crud 项目

<artifactId>mybatis</artifactId>

<version>${mybatis.version}</version>

</dependency>

<dependency>

<groupId>org.mybatis</groupId>

<artifactId>mybatis-spring</artifactId>

<version>1.2.2</version>

</dependency>

<dependency>

<groupId>com.github.pagehelper</groupId>

<artifactId>pagehelper</artifactId>

<version>5.1.2</version>

</dependency>

<!-- mybatis框架包 -->

<!-- 数据库驱动 -->

<dependency>

<groupId>mysql</groupId>

<artifactId>mysql-connector-java</artifactId>

<version>5.1.35</version>

</dependency>

Page 11: Ssm 简单 crud 项目

<!-- 导入 dbcp的 jar包,用来在

applicationContext.xml中配置数据库 -->

<dependency>

<groupId>commons-dbcp</groupId>

<artifactId>commons-dbcp</artifactId>

<version>1.4</version>

</dependency>

<!-- jstl标签类 -->

<dependency>

<groupId>jstl</groupId>

<artifactId>jstl</artifactId>

<version>1.2</version>

</dependency>

<!-- log -->

<dependency>

<groupId>log4j</groupId>

<artifactId>log4j</artifactId>

<version>${log4j.version}</version>

</dependency>

<dependency>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-api</artifactId>

Page 12: Ssm 简单 crud 项目

<version>${slf4j.version}</version>

</dependency>

<dependency>

<groupId>org.slf4j</groupId>

<artifactId>slf4j-log4j12</artifactId>

<version>${slf4j.version}</version>

</dependency>

<!-- 连接池 -->

<dependency>

<groupId>com.alibaba</groupId>

<artifactId>druid</artifactId>

<version>${druid.version}</version>

</dependency>

<!--文件上传组件-->

<dependency>

<groupId>commons-fileupload</groupId>

<artifactId>commons-fileupload</artifactId>

<version>1.3.1</version>

</dependency>

<dependency>

<groupId>commons-io</groupId>

Page 13: Ssm 简单 crud 项目

<artifactId>commons-io</artifactId>

<version>2.5</version>

</dependency>

<dependency>

<groupId>com.fasterxml.jackson.core</groupId>

<artifactId>jackson-databind</artifactId>

<version>2.8.5</version>

</dependency>

<dependency>

<groupId>com.fasterxml.jackson.core</groupId>

<artifactId>jackson-annotations</artifactId>

<version>2.8.5</version>

</dependency>

<dependency>

<groupId>org.ehcache</groupId>

<artifactId>ehcache</artifactId>

<version>3.3.1</version>

</dependency>

<dependency>

<groupId>org.mybatis.caches</groupId>

Page 14: Ssm 简单 crud 项目

<artifactId>mybatis-ehcache</artifactId>

<version>1.1.0</version>

</dependency>

<dependency>

<groupId>javax.servlet</groupId>

<artifactId>javax.servlet-api</artifactId>

<version>3.1.0</version>

<scope>provided</scope>

</dependency>

<dependency>

<groupId>org.projectlombok</groupId>

<artifactId>lombok</artifactId>

<version>1.18.2</version>

</dependency>

<dependency>

<groupId>javax.validation</groupId>

<artifactId>validation-api</artifactId>

<version>2.0.1.Final</version>

</dependency>

</dependencies>

二. SSM 配置文件配置

Page 15: Ssm 简单 crud 项目

1. 创建 spring的配置文件 applicationContext.xml在 resources目录下

<?xml version="1.0" encoding="UTF-8"?>

<beans

xmlns="http://www.springframework.org/schema/beans

"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instan

ce"

xmlns:context="http://www.springframework.org/sche

ma/context"

xmlns:aop="http://www.springframework.org/schema/a

op"

xmlns:tx="http://www.springframework.org/schema/tx

"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring

-beans.xsd

Page 16: Ssm 简单 crud 项目

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spri

ng-context.xsd

http://www.springframework.org/schema/aop

http://www.springframework.org/schema/aop/spring-a

op.xsd

http://www.springframework.org/schema/tx

http://www.springframework.org/schema/tx/spring-tx

.xsd">

<context:component-scan base-package="com">

<context:exclude-filter type="annotation"

expression="org.springframework.stereotype.Control

ler"/>

</context:component-scan>

<context:property-placeholder

Page 17: Ssm 简单 crud 项目

location="classpath:jdbc.properties"/>

<bean id="dataSource"

class="com.alibaba.druid.pool.DruidDataSource">

<property name="driverClassName"

value="${jdbc.driver}"/>

<property name="url" value="${jdbc.url}"/>

<property name="username"

value="${jdbc.username}"/>

<property name="password"

value="${jdbc.password}"/>

</bean>

<bean id="sqlSessionFactory"

class="org.mybatis.spring.SqlSessionFactoryBean">

<property name="dataSource"

ref="dataSource"/>

<property name="configLocation"

value="classpath:config.xml"/>

<property name="mapperLocations"

value="classpath:mapper/*.xml"/>

Page 18: Ssm 简单 crud 项目

</bean>

<bean

class="org.mybatis.spring.mapper.MapperScannerConf

igurer">

<property name="basePackage"

value="com.dao"/>

</bean>

<bean

class="org.mybatis.spring.SqlSessionTemplate"

id="sessionTemplate">

<constructor-arg name="sqlSessionFactory"

ref="sqlSessionFactory"/>

<constructor-arg name="executorType"

value="BATCH"/>

</bean>

<bean id="transactionManager"

class="org.springframework.jdbc.datasource.DataSou

rceTransactionManager">

<property name="dataSource"

Page 19: Ssm 简单 crud 项目

ref="dataSource"/>

</bean>

<tx:advice id="advice"

transaction-manager="transactionManager">

<tx:attributes>

<tx:method name="save*"

propagation="REQUIRED"/>

<tx:method name="update*"

propagation="REQUIRED"/>

<tx:method name="delete*"

propagation="REQUIRED"/>

<tx:method name="find*"

read-only="true"/>

<tx:method name="get*"

read-only="true"/>

<tx:method name="*"

propagation="REQUIRED"/>

</tx:attributes>

</tx:advice>

<aop:config>

Page 20: Ssm 简单 crud 项目

<aop:pointcut id="pointcut"

expression="execution(*

com.service.impl.*.*(..))"/>

<aop:advisor advice-ref="advice"

pointcut-ref="pointcut"/>

</aop:config>

</beans>

2. 创建 springmvc配置文件 springmvc-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans

xmlns="http://www.springframework.org/schema/beans

"

xmlns:mvc="http://www.springframework.org/schema/m

vc"

xmlns:context="http://www.springframework.org/sche

ma/context"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instan

Page 21: Ssm 简单 crud 项目

ce"

xsi:schemaLocation="

http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring

-beans.xsd

http://www.springframework.org/schema/mvc

http://www.springframework.org/schema/mvc/spring-m

vc.xsd

http://www.springframework.org/schema/context

http://www.springframework.org/schema/context/spri

ng-context.xsd">

<context:component-scan base-package="com">

<context:include-filter type="annotation"

expression="org.springframework.stereotype.Control

ler"/>

</context:component-scan>

Page 22: Ssm 简单 crud 项目

<bean id="internalResourceViewResolver"

class="org.springframework.web.servlet.view.Intern

alResourceViewResolver">

<property name="prefix" value="/WEB-INF/"/>

<property name="suffix" value=".jsp"/>

</bean>

<mvc:resources mapping="/css/**"

location="/WEB-INF/css/"/>

<mvc:resources mapping="/js/**"

location="/WEB-INF/js/"/>

<mvc:resources mapping="/fonts/**"

location="/WEB-INF/fonts/"/>

<mvc:annotation-driven/>

</beans>

3. 创建日志配置文件 log4j.properties

### set log levels ###

log4j.rootLogger = info , Console , D

#Console

log4j.appender.Console=org.apache.log4j.ConsoleApp

Page 23: Ssm 简单 crud 项目

ender

log4j.appender.Console.layout=org.apache.log4j.Pat

ternLayout

log4j.appender.Console.layout.ConversionPattern=%d

[%t] %-5p [%c] - %m%n

log4j.logger.java.sql.ResultSet=INFO

log4j.logger.org.apache=INFO

log4j.logger.java.sql.Connection=INFO

log4j.logger.java.sql.Statement=INFO

log4j.logger.java.sql.PreparedStatement=INFO

#output2file

log4j.appender.D =

org.apache.log4j.DailyRollingFileAppender

log4j.appender.D.File = D\:/logs/log.log

log4j.appender.D.Append = true

##

\u8F93\u51FAinfo\u7EA7\u522B\u4EE5\u4E0A\u7684\u65

E5\u5FD7

log4j.appender.D.Threshold = INFO

log4j.appender.D.layout =

org.apache.log4j.PatternLayout

log4j.appender.D.layout.ConversionPattern

Page 24: Ssm 简单 crud 项目

= %-d{yyyy-MM-dd HH\:mm\:ss} [ %t\:%r ] - [ %p ] %m%n

4. 创建 jdbc.properties 配置数据库

jdbc.driver=com.mysql.jdbc.Driver

jdbc.url=jdbc:mysql:///ssm?characterEncoding=utf8&

useSSL=false

jdbc.username=root

jdbc.password=32194878

initialSize=5

maxActive=20

maxIdle=20

minIdle=1

maxWait=10000

5. 在 resources下创建 config.xml文件用于配置mybatis扩展(这里使用了mybatis的分页插件)6. 在 resources 下创建 mapper 文件夹用于放置 mapper.xml 文件

<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE

configuration

PUBLIC "-//mybatis.org//DTD Config 3.0//EN"

"http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>

<settings>

<setting name="mapUnderscoreToCamelCase"

Page 25: Ssm 简单 crud 项目

value="true"/>

</settings>

<plugins>

<plugin

interceptor="com.github.pagehelper.PageInterceptor

">

</plugin>

</plugins>

</configuration>

7. 配置完成后,在 applicationContext.xml 中没有最开始报红(*.xml 与 impl 还没创建)即可

8. 在 web.xml文件中加入 spring配置监听与启动,同时配置使用 utf编码,与支持 restful风格,没有报红说明配置正确

<?xml version="1.0" encoding="UTF-8"?>

<web-app

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instan

ce"

xmlns="http://java.sun.com/xml/ns/javaee"

xsi:schemaLocation="http://java.sun.com/xml/ns/jav

aee

http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"

id="WebApp_ID" version="3.0">

Page 26: Ssm 简单 crud 项目

<!--使用 spring的监听器来监听 servletcontext

的创建来加载 spring的配置文件-->

<!--默认加载 WEB-INF 下的 applicationContext.xml文

件-->

<listener>

<listener-class>org.springframework.web.context.Co

ntextLoaderListener</listener-class>

</listener>

<context-param>

<param-name>contextConfigLocation</param-name>

<param-value>classpath:applicationContext.xml</par

am-value>

</context-param>

<servlet>

<servlet-name>dispatcherServlet</servlet-name>

<servlet-class>org.springframework.web.servlet.Dis

patcherServlet</servlet-class>

<init-param>

Page 27: Ssm 简单 crud 项目

<param-name>contextConfigLocation</param-name>

<param-value>classpath:springmvc-servlet.xml</para

m-value>

</init-param>

<load-on-startup>1</load-on-startup>

</servlet>

<servlet-mapping>

<servlet-name>dispatcherServlet</servlet-name>

<url-pattern>/</url-pattern>

</servlet-mapping>

<filter>

<filter-name>encodingFilter</filter-name>

<filter-class>org.springframework.web.filter.Chara

cterEncodingFilter</filter-class>

<init-param>

<param-name>encoding</param-name>

<param-value>utf-8</param-value>

</init-param>

</filter>

<filter-mapping>

Page 28: Ssm 简单 crud 项目

<filter-name>encodingFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

<filter>

<filter-name>hiddenHttpMethodFilter</filter-name>

<filter-class>org.springframework.web.filter.Hidde

nHttpMethodFilter</filter-class>

</filter>

<filter-mapping>

<filter-name>hiddenHttpMethodFilter</filter-name>

<url-pattern>/*</url-pattern>

</filter-mapping>

</web-app>

三. 数据库编写

1. 创建数据库 ssm,插入表 tbl-emp 与 tnl-dept(别问为啥 tnl,刚开始写的时候写错了后面都这

么用的就懒得改了 233)DROP TABLE IF EXISTS `tbl_emp`;CREATE TABLE `tbl_emp` (

`emp_id` int(11) NOT NULL AUTO_INCREMENT,`emp_name` varchar(255) NOT NULL,`gender` char(1) DEFAULT NULL,

Page 29: Ssm 简单 crud 项目

`email` varchar(255) DEFAULT NULL,`d_id` int(11) DEFAULT NULL,PRIMARY KEY (`emp_id`),KEY `fk_emp_dept` (`d_id`),CONSTRAINT `fk_emp_dept` FOREIGN KEY (`d_id`) REFERENCES `tnl_dept` (`dept_id`)

) ENGINE=InnoDB AUTO_INCREMENT=1132 DEFAULT CHARSET=utf8;

DROP TABLE IF EXISTS `tnl_dept`;CREATE TABLE `tnl_dept` (

`dept_id` int(11) NOT NULL AUTO_INCREMENT,`dept_name` varchar(255) NOT NULL,PRIMARY KEY (`dept_id`)

) ENGINE=InnoDB AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

INSERT INTO `tnl_dept` VALUES ('1', '开发部');INSERT INTO `tnl_dept` VALUES ('2', '测试部');INSERT INTO `tnl_dept` VALUES ('3', '运营部');INSERT INTO `tnl_dept` VALUES ('4', '营销部');INSERT INTO `tnl_dept` VALUES ('5', '管理部');

四. Domain编写

1. Java包下创建如下目录

2. Domain包下创建实体类Department,DepartmentExample.Employee,EmployeeExample,具体

类方法的说明在下面

package com.domain;

public class Department {

private Integer deptId;

Page 30: Ssm 简单 crud 项目

private String deptName;

public Integer getDeptId() {

return deptId;

}

public void setDeptId(Integer deptId) {

this.deptId = deptId;

}

public String getDeptName() {

return deptName;

}

public void setDeptName(String deptName) {

this.deptName = deptName == null ? null :

deptName.trim();

}

@Override

public String toString() {

Page 31: Ssm 简单 crud 项目

return "Department{" +

"deptId=" + deptId +

", deptName='" + deptName + '\'' +

'}';

}

}

package com.domain;

import java.util.ArrayList;

import java.util.List;

public class DepartmentExample {

protected String orderByClause;

protected boolean distinct;

protected List<Criteria> oredCriteria;

public DepartmentExample() {

oredCriteria = new ArrayList<Criteria>();

}

Page 32: Ssm 简单 crud 项目

public void setOrderByClause(String

orderByClause) {

this.orderByClause = orderByClause;

}

public String getOrderByClause() {

return orderByClause;

}

public void setDistinct(boolean distinct) {

this.distinct = distinct;

}

public boolean isDistinct() {

return distinct;

}

public List<Criteria> getOredCriteria() {

return oredCriteria;

}

Page 33: Ssm 简单 crud 项目

public void or(Criteria criteria) {

oredCriteria.add(criteria);

}

public Criteria or() {

Criteria criteria =

createCriteriaInternal();

oredCriteria.add(criteria);

return criteria;

}

public Criteria createCriteria() {

Criteria criteria =

createCriteriaInternal();

if (oredCriteria.size() == 0) {

oredCriteria.add(criteria);

}

return criteria;

}

protected Criteria createCriteriaInternal() {

Criteria criteria = new Criteria();

Page 34: Ssm 简单 crud 项目

return criteria;

}

public void clear() {

oredCriteria.clear();

orderByClause = null;

distinct = false;

}

protected abstract static class

GeneratedCriteria {

protected List<Criterion> criteria;

protected GeneratedCriteria() {

super();

criteria = new ArrayList<Criterion>();

}

public boolean isValid() {

return criteria.size() > 0;

}

Page 35: Ssm 简单 crud 项目

public List<Criterion> getAllCriteria() {

return criteria;

}

public List<Criterion> getCriteria() {

return criteria;

}

protected void addCriterion(String

condition) {

if (condition == null) {

throw new RuntimeException("Value for

condition cannot be null");

}

criteria.add(new Criterion(condition));

}

protected void addCriterion(String

condition, Object value, String property) {

if (value == null) {

throw new RuntimeException("Value for

" + property + " cannot be null");

Page 36: Ssm 简单 crud 项目

}

criteria.add(new Criterion(condition,

value));

}

protected void addCriterion(String

condition, Object value1, Object value2, String

property) {

if (value1 == null || value2 == null) {

throw new RuntimeException("Between

values for " + property + " cannot be null");

}

criteria.add(new Criterion(condition,

value1, value2));

}

public Criteria andDeptIdIsNull() {

addCriterion("dept_id is null");

return (Criteria) this;

}

public Criteria andDeptIdIsNotNull() {

Page 37: Ssm 简单 crud 项目

addCriterion("dept_id is not null");

return (Criteria) this;

}

public Criteria andDeptIdEqualTo(Integer

value) {

addCriterion("dept_id =", value,

"deptId");

return (Criteria) this;

}

public Criteria andDeptIdNotEqualTo(Integer

value) {

addCriterion("dept_id <>", value,

"deptId");

return (Criteria) this;

}

public Criteria andDeptIdGreaterThan(Integer

value) {

addCriterion("dept_id >", value,

"deptId");

Page 38: Ssm 简单 crud 项目

return (Criteria) this;

}

public Criteria

andDeptIdGreaterThanOrEqualTo(Integer value) {

addCriterion("dept_id >=", value,

"deptId");

return (Criteria) this;

}

public Criteria andDeptIdLessThan(Integer

value) {

addCriterion("dept_id <", value,

"deptId");

return (Criteria) this;

}

public Criteria

andDeptIdLessThanOrEqualTo(Integer value) {

addCriterion("dept_id <=", value,

"deptId");

return (Criteria) this;

Page 39: Ssm 简单 crud 项目

}

public Criteria andDeptIdIn(List<Integer>

values) {

addCriterion("dept_id in", values,

"deptId");

return (Criteria) this;

}

public Criteria andDeptIdNotIn(List<Integer>

values) {

addCriterion("dept_id not in", values,

"deptId");

return (Criteria) this;

}

public Criteria andDeptIdBetween(Integer

value1, Integer value2) {

addCriterion("dept_id between", value1,

value2, "deptId");

return (Criteria) this;

}

Page 40: Ssm 简单 crud 项目

public Criteria andDeptIdNotBetween(Integer

value1, Integer value2) {

addCriterion("dept_id not between",

value1, value2, "deptId");

return (Criteria) this;

}

public Criteria andDeptNameIsNull() {

addCriterion("dept_name is null");

return (Criteria) this;

}

public Criteria andDeptNameIsNotNull() {

addCriterion("dept_name is not null");

return (Criteria) this;

}

public Criteria andDeptNameEqualTo(String

value) {

addCriterion("dept_name =", value,

"deptName");

Page 41: Ssm 简单 crud 项目

return (Criteria) this;

}

public Criteria andDeptNameNotEqualTo(String

value) {

addCriterion("dept_name <>", value,

"deptName");

return (Criteria) this;

}

public Criteria

andDeptNameGreaterThan(String value) {

addCriterion("dept_name >", value,

"deptName");

return (Criteria) this;

}

public Criteria

andDeptNameGreaterThanOrEqualTo(String value) {

addCriterion("dept_name >=", value,

"deptName");

return (Criteria) this;

Page 42: Ssm 简单 crud 项目

}

public Criteria andDeptNameLessThan(String

value) {

addCriterion("dept_name <", value,

"deptName");

return (Criteria) this;

}

public Criteria

andDeptNameLessThanOrEqualTo(String value) {

addCriterion("dept_name <=", value,

"deptName");

return (Criteria) this;

}

public Criteria andDeptNameLike(String

value) {

addCriterion("dept_name like", value,

"deptName");

return (Criteria) this;

}

Page 43: Ssm 简单 crud 项目

public Criteria andDeptNameNotLike(String

value) {

addCriterion("dept_name not like", value,

"deptName");

return (Criteria) this;

}

public Criteria andDeptNameIn(List<String>

values) {

addCriterion("dept_name in", values,

"deptName");

return (Criteria) this;

}

public Criteria

andDeptNameNotIn(List<String> values) {

addCriterion("dept_name not in", values,

"deptName");

return (Criteria) this;

}

Page 44: Ssm 简单 crud 项目

public Criteria andDeptNameBetween(String

value1, String value2) {

addCriterion("dept_name between",

value1, value2, "deptName");

return (Criteria) this;

}

public Criteria andDeptNameNotBetween(String

value1, String value2) {

addCriterion("dept_name not between",

value1, value2, "deptName");

return (Criteria) this;

}

}

public static class Criteria extends

GeneratedCriteria {

protected Criteria() {

super();

}

}

Page 45: Ssm 简单 crud 项目

public static class Criterion {

private String condition;

private Object value;

private Object secondValue;

private boolean noValue;

private boolean singleValue;

private boolean betweenValue;

private boolean listValue;

private String typeHandler;

public String getCondition() {

return condition;

}

Page 46: Ssm 简单 crud 项目

public Object getValue() {

return value;

}

public Object getSecondValue() {

return secondValue;

}

public boolean isNoValue() {

return noValue;

}

public boolean isSingleValue() {

return singleValue;

}

public boolean isBetweenValue() {

return betweenValue;

}

public boolean isListValue() {

return listValue;

Page 47: Ssm 简单 crud 项目

}

public String getTypeHandler() {

return typeHandler;

}

protected Criterion(String condition) {

super();

this.condition = condition;

this.typeHandler = null;

this.noValue = true;

}

protected Criterion(String condition, Object

value, String typeHandler) {

super();

this.condition = condition;

this.value = value;

this.typeHandler = typeHandler;

if (value instanceof List<?>) {

this.listValue = true;

} else {

Page 48: Ssm 简单 crud 项目

this.singleValue = true;

}

}

protected Criterion(String condition, Object

value) {

this(condition, value, null);

}

protected Criterion(String condition, Object

value, Object secondValue, String typeHandler) {

super();

this.condition = condition;

this.value = value;

this.secondValue = secondValue;

this.typeHandler = typeHandler;

this.betweenValue = true;

}

protected Criterion(String condition, Object

value, Object secondValue) {

this(condition, value, secondValue,

Page 49: Ssm 简单 crud 项目

null);

}

}

}

package com.domain;

import javax.validation.constraints.Email;

import javax.validation.constraints.Pattern;

public class Employee {

private Integer empId;

@Pattern(regexp =

"(^[a-zA-Z0-9]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,6}$)"

,message = "用户名是 2-5位中文或 6-16位英文")

private String empName;

private String gender;

@Email

Page 50: Ssm 简单 crud 项目

private String email;

private Integer dId;

private Department department;

public Department getDepartment() {

return department;

}

public void setDepartment(Department department)

{

this.department = department;

}

public Integer getEmpId() {

return empId;

}

public void setEmpId(Integer empId) {

this.empId = empId;

}

Page 51: Ssm 简单 crud 项目

public String getEmpName() {

return empName;

}

public void setEmpName(String empName) {

this.empName = empName == null ? null :

empName.trim();

}

public String getGender() {

return gender;

}

public void setGender(String gender) {

this.gender = gender == null ? null :

gender.trim();

}

public String getEmail() {

return email;

}

Page 52: Ssm 简单 crud 项目

public void setEmail(String email) {

this.email = email == null ? null :

email.trim();

}

public Integer getdId() {

return dId;

}

public void setdId(Integer dId) {

this.dId = dId;

}

@Override

public String toString() {

return "Employee{" +

"empId=" + empId +

", empName='" + empName + '\'' +

", gender='" + gender + '\'' +

", email='" + email + '\'' +

", dId=" + dId +

Page 53: Ssm 简单 crud 项目

", department=" + department +

'}';

}

}

package com.domain;

import java.util.ArrayList;

import java.util.List;

public class EmployeeExample {

protected String orderByClause;

protected boolean distinct;

protected List<Criteria> oredCriteria;

public EmployeeExample() {

oredCriteria = new ArrayList<Criteria>();

}

public void setOrderByClause(String

Page 54: Ssm 简单 crud 项目

orderByClause) {

this.orderByClause = orderByClause;

}

public String getOrderByClause() {

return orderByClause;

}

public void setDistinct(boolean distinct) {

this.distinct = distinct;

}

public boolean isDistinct() {

return distinct;

}

public List<Criteria> getOredCriteria() {

return oredCriteria;

}

public void or(Criteria criteria) {

oredCriteria.add(criteria);

Page 55: Ssm 简单 crud 项目

}

public Criteria or() {

Criteria criteria =

createCriteriaInternal();

oredCriteria.add(criteria);

return criteria;

}

public Criteria createCriteria() {

Criteria criteria =

createCriteriaInternal();

if (oredCriteria.size() == 0) {

oredCriteria.add(criteria);

}

return criteria;

}

protected Criteria createCriteriaInternal() {

Criteria criteria = new Criteria();

return criteria;

}

Page 56: Ssm 简单 crud 项目

public void clear() {

oredCriteria.clear();

orderByClause = null;

distinct = false;

}

protected abstract static class

GeneratedCriteria {

protected List<Criterion> criteria;

protected GeneratedCriteria() {

super();

criteria = new ArrayList<Criterion>();

}

public boolean isValid() {

return criteria.size() > 0;

}

public List<Criterion> getAllCriteria() {

return criteria;

Page 57: Ssm 简单 crud 项目

}

public List<Criterion> getCriteria() {

return criteria;

}

protected void addCriterion(String

condition) {

if (condition == null) {

throw new RuntimeException("Value for

condition cannot be null");

}

criteria.add(new Criterion(condition));

}

protected void addCriterion(String

condition, Object value, String property) {

if (value == null) {

throw new RuntimeException("Value for

" + property + " cannot be null");

}

criteria.add(new Criterion(condition,

Page 58: Ssm 简单 crud 项目

value));

}

protected void addCriterion(String

condition, Object value1, Object value2, String

property) {

if (value1 == null || value2 == null) {

throw new RuntimeException("Between

values for " + property + " cannot be null");

}

criteria.add(new Criterion(condition,

value1, value2));

}

public Criteria andEmpIdIsNull() {

addCriterion("emp_id is null");

return (Criteria) this;

}

public Criteria andEmpIdIsNotNull() {

addCriterion("emp_id is not null");

return (Criteria) this;

Page 59: Ssm 简单 crud 项目

}

public Criteria andEmpIdEqualTo(Integer

value) {

addCriterion("emp_id =", value, "empId");

return (Criteria) this;

}

public Criteria andEmpIdNotEqualTo(Integer

value) {

addCriterion("emp_id <>", value,

"empId");

return (Criteria) this;

}

public Criteria andEmpIdGreaterThan(Integer

value) {

addCriterion("emp_id >", value, "empId");

return (Criteria) this;

}

public Criteria

Page 60: Ssm 简单 crud 项目

andEmpIdGreaterThanOrEqualTo(Integer value) {

addCriterion("emp_id >=", value,

"empId");

return (Criteria) this;

}

public Criteria andEmpIdLessThan(Integer

value) {

addCriterion("emp_id <", value, "empId");

return (Criteria) this;

}

public Criteria

andEmpIdLessThanOrEqualTo(Integer value) {

addCriterion("emp_id <=", value,

"empId");

return (Criteria) this;

}

public Criteria andEmpIdIn(List<Integer>

values) {

addCriterion("emp_id in", values,

Page 61: Ssm 简单 crud 项目

"empId");

return (Criteria) this;

}

public Criteria andEmpIdNotIn(List<Integer>

values) {

addCriterion("emp_id not in", values,

"empId");

return (Criteria) this;

}

public Criteria andEmpIdBetween(Integer

value1, Integer value2) {

addCriterion("emp_id between", value1,

value2, "empId");

return (Criteria) this;

}

public Criteria andEmpIdNotBetween(Integer

value1, Integer value2) {

addCriterion("emp_id not between",

value1, value2, "empId");

Page 62: Ssm 简单 crud 项目

return (Criteria) this;

}

public Criteria andEmpNameIsNull() {

addCriterion("emp_name is null");

return (Criteria) this;

}

public Criteria andEmpNameIsNotNull() {

addCriterion("emp_name is not null");

return (Criteria) this;

}

public Criteria andEmpNameEqualTo(String

value) {

addCriterion("emp_name =", value,

"empName");

return (Criteria) this;

}

public Criteria andEmpNameNotEqualTo(String

value) {

Page 63: Ssm 简单 crud 项目

addCriterion("emp_name <>", value,

"empName");

return (Criteria) this;

}

public Criteria andEmpNameGreaterThan(String

value) {

addCriterion("emp_name >", value,

"empName");

return (Criteria) this;

}

public Criteria

andEmpNameGreaterThanOrEqualTo(String value) {

addCriterion("emp_name >=", value,

"empName");

return (Criteria) this;

}

public Criteria andEmpNameLessThan(String

value) {

addCriterion("emp_name <", value,

Page 64: Ssm 简单 crud 项目

"empName");

return (Criteria) this;

}

public Criteria

andEmpNameLessThanOrEqualTo(String value) {

addCriterion("emp_name <=", value,

"empName");

return (Criteria) this;

}

public Criteria andEmpNameLike(String value)

{

addCriterion("emp_name like", value,

"empName");

return (Criteria) this;

}

public Criteria andEmpNameNotLike(String

value) {

addCriterion("emp_name not like", value,

"empName");

Page 65: Ssm 简单 crud 项目

return (Criteria) this;

}

public Criteria andEmpNameIn(List<String>

values) {

addCriterion("emp_name in", values,

"empName");

return (Criteria) this;

}

public Criteria andEmpNameNotIn(List<String>

values) {

addCriterion("emp_name not in", values,

"empName");

return (Criteria) this;

}

public Criteria andEmpNameBetween(String

value1, String value2) {

addCriterion("emp_name between", value1,

value2, "empName");

return (Criteria) this;

Page 66: Ssm 简单 crud 项目

}

public Criteria andEmpNameNotBetween(String

value1, String value2) {

addCriterion("emp_name not between",

value1, value2, "empName");

return (Criteria) this;

}

public Criteria andGenderIsNull() {

addCriterion("gender is null");

return (Criteria) this;

}

public Criteria andGenderIsNotNull() {

addCriterion("gender is not null");

return (Criteria) this;

}

public Criteria andGenderEqualTo(String

value) {

addCriterion("gender =", value,

Page 67: Ssm 简单 crud 项目

"gender");

return (Criteria) this;

}

public Criteria andGenderNotEqualTo(String

value) {

addCriterion("gender <>", value,

"gender");

return (Criteria) this;

}

public Criteria andGenderGreaterThan(String

value) {

addCriterion("gender >", value,

"gender");

return (Criteria) this;

}

public Criteria

andGenderGreaterThanOrEqualTo(String value) {

addCriterion("gender >=", value,

"gender");

Page 68: Ssm 简单 crud 项目

return (Criteria) this;

}

public Criteria andGenderLessThan(String

value) {

addCriterion("gender <", value,

"gender");

return (Criteria) this;

}

public Criteria

andGenderLessThanOrEqualTo(String value) {

addCriterion("gender <=", value,

"gender");

return (Criteria) this;

}

public Criteria andGenderLike(String value) {

addCriterion("gender like", value,

"gender");

return (Criteria) this;

}

Page 69: Ssm 简单 crud 项目

public Criteria andGenderNotLike(String

value) {

addCriterion("gender not like", value,

"gender");

return (Criteria) this;

}

public Criteria andGenderIn(List<String>

values) {

addCriterion("gender in", values,

"gender");

return (Criteria) this;

}

public Criteria andGenderNotIn(List<String>

values) {

addCriterion("gender not in", values,

"gender");

return (Criteria) this;

}

Page 70: Ssm 简单 crud 项目

public Criteria andGenderBetween(String

value1, String value2) {

addCriterion("gender between", value1,

value2, "gender");

return (Criteria) this;

}

public Criteria andGenderNotBetween(String

value1, String value2) {

addCriterion("gender not between",

value1, value2, "gender");

return (Criteria) this;

}

public Criteria andEmailIsNull() {

addCriterion("email is null");

return (Criteria) this;

}

public Criteria andEmailIsNotNull() {

addCriterion("email is not null");

return (Criteria) this;

Page 71: Ssm 简单 crud 项目

}

public Criteria andEmailEqualTo(String

value) {

addCriterion("email =", value, "email");

return (Criteria) this;

}

public Criteria andEmailNotEqualTo(String

value) {

addCriterion("email <>", value, "email");

return (Criteria) this;

}

public Criteria andEmailGreaterThan(String

value) {

addCriterion("email >", value, "email");

return (Criteria) this;

}

public Criteria

andEmailGreaterThanOrEqualTo(String value) {

Page 72: Ssm 简单 crud 项目

addCriterion("email >=", value, "email");

return (Criteria) this;

}

public Criteria andEmailLessThan(String

value) {

addCriterion("email <", value, "email");

return (Criteria) this;

}

public Criteria

andEmailLessThanOrEqualTo(String value) {

addCriterion("email <=", value, "email");

return (Criteria) this;

}

public Criteria andEmailLike(String value) {

addCriterion("email like", value,

"email");

return (Criteria) this;

}

Page 73: Ssm 简单 crud 项目

public Criteria andEmailNotLike(String

value) {

addCriterion("email not like", value,

"email");

return (Criteria) this;

}

public Criteria andEmailIn(List<String>

values) {

addCriterion("email in", values,

"email");

return (Criteria) this;

}

public Criteria andEmailNotIn(List<String>

values) {

addCriterion("email not in", values,

"email");

return (Criteria) this;

}

public Criteria andEmailBetween(String

Page 74: Ssm 简单 crud 项目

value1, String value2) {

addCriterion("email between", value1,

value2, "email");

return (Criteria) this;

}

public Criteria andEmailNotBetween(String

value1, String value2) {

addCriterion("email not between", value1,

value2, "email");

return (Criteria) this;

}

public Criteria andDIdIsNull() {

addCriterion("d_id is null");

return (Criteria) this;

}

public Criteria andDIdIsNotNull() {

addCriterion("d_id is not null");

return (Criteria) this;

}

Page 75: Ssm 简单 crud 项目

public Criteria andDIdEqualTo(Integer value)

{

addCriterion("d_id =", value, "dId");

return (Criteria) this;

}

public Criteria andDIdNotEqualTo(Integer

value) {

addCriterion("d_id <>", value, "dId");

return (Criteria) this;

}

public Criteria andDIdGreaterThan(Integer

value) {

addCriterion("d_id >", value, "dId");

return (Criteria) this;

}

public Criteria

andDIdGreaterThanOrEqualTo(Integer value) {

addCriterion("d_id >=", value, "dId");

Page 76: Ssm 简单 crud 项目

return (Criteria) this;

}

public Criteria andDIdLessThan(Integer

value) {

addCriterion("d_id <", value, "dId");

return (Criteria) this;

}

public Criteria

andDIdLessThanOrEqualTo(Integer value) {

addCriterion("d_id <=", value, "dId");

return (Criteria) this;

}

public Criteria andDIdIn(List<Integer>

values) {

addCriterion("d_id in", values, "dId");

return (Criteria) this;

}

public Criteria andDIdNotIn(List<Integer>

Page 77: Ssm 简单 crud 项目

values) {

addCriterion("d_id not in", values,

"dId");

return (Criteria) this;

}

public Criteria andDIdBetween(Integer

value1, Integer value2) {

addCriterion("d_id between", value1,

value2, "dId");

return (Criteria) this;

}

public Criteria andDIdNotBetween(Integer

value1, Integer value2) {

addCriterion("d_id not between", value1,

value2, "dId");

return (Criteria) this;

}

}

public static class Criteria extends

Page 78: Ssm 简单 crud 项目

GeneratedCriteria {

protected Criteria() {

super();

}

}

public static class Criterion {

private String condition;

private Object value;

private Object secondValue;

private boolean noValue;

private boolean singleValue;

private boolean betweenValue;

private boolean listValue;

Page 79: Ssm 简单 crud 项目

private String typeHandler;

public String getCondition() {

return condition;

}

public Object getValue() {

return value;

}

public Object getSecondValue() {

return secondValue;

}

public boolean isNoValue() {

return noValue;

}

public boolean isSingleValue() {

return singleValue;

}

Page 80: Ssm 简单 crud 项目

public boolean isBetweenValue() {

return betweenValue;

}

public boolean isListValue() {

return listValue;

}

public String getTypeHandler() {

return typeHandler;

}

protected Criterion(String condition) {

super();

this.condition = condition;

this.typeHandler = null;

this.noValue = true;

}

protected Criterion(String condition, Object

value, String typeHandler) {

super();

Page 81: Ssm 简单 crud 项目

this.condition = condition;

this.value = value;

this.typeHandler = typeHandler;

if (value instanceof List<?>) {

this.listValue = true;

} else {

this.singleValue = true;

}

}

protected Criterion(String condition, Object

value) {

this(condition, value, null);

}

protected Criterion(String condition, Object

value, Object secondValue, String typeHandler) {

super();

this.condition = condition;

this.value = value;

this.secondValue = secondValue;

this.typeHandler = typeHandler;

Page 82: Ssm 简单 crud 项目

this.betweenValue = true;

}

protected Criterion(String condition, Object

value, Object secondValue) {

this(condition, value, secondValue,

null);

}

}

}

五. Mapper层编写

3. 在 dao 包下创建 DepartmentMapper,与 EmployeeMapper 接口

package com.dao;

import com.domain.Department;

import com.domain.DepartmentExample;

import java.util.List;

import org.apache.ibatis.annotations.Param;

public interface DepartmentMapper {

int countByExample(DepartmentExample example);

Page 83: Ssm 简单 crud 项目

int deleteByExample(DepartmentExample example);

int deleteByPrimaryKey(Integer deptId);

int insert(Department record);

int insertSelective(Department record);

List<Department>

selectByExample(DepartmentExample example);

Department selectByPrimaryKey(Integer deptId);

int updateByExampleSelective(@Param("record")

Department record, @Param("example")

DepartmentExample example);

int updateByExample(@Param("record") Department

record, @Param("example") DepartmentExample

example);

Page 84: Ssm 简单 crud 项目

int updateByPrimaryKeySelective(Department

record);

int updateByPrimaryKey(Department record);

}

package com.dao;

import com.domain.Employee;

import com.domain.EmployeeExample;

import java.util.List;

import org.apache.ibatis.annotations.Param;

public interface EmployeeMapper {

int countByExample(EmployeeExample example);

int deleteByExample(EmployeeExample example);

int deleteByPrimaryKey(Integer empId);

int insert(Employee record);

Page 85: Ssm 简单 crud 项目

int insertSelective(Employee record);

List<Employee> selectByExample(EmployeeExample

example);

List<Employee>

selectByExampleWithDept(EmployeeExample example);

Employee selectByPrimaryKeyWidthDept(Integer

empId);

Employee selectByPrimaryKey(Integer empId);

int updateByExampleSelective(@Param("record")

Employee record, @Param("example") EmployeeExample

example);

int updateByExample(@Param("record") Employee

record, @Param("example") EmployeeExample example);

int updateByPrimaryKeySelective(Employee

record);

Page 86: Ssm 简单 crud 项目

int updateByPrimaryKey(Employee record);

}

2. 在 resources 的 mapper 下创建对应 mapper.xml 文件 DepartmentMapper.xml 与EmployeeMapper.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.dao.DepartmentMapper" >

<resultMap id="BaseResultMap"

type="com.domain.Department" >

<id column="dept_id" property="deptId"

jdbcType="INTEGER" />

<result column="dept_name" property="deptName"

jdbcType="VARCHAR" />

</resultMap>

<sql id="Example_Where_Clause" >

<where >

<foreach collection="oredCriteria"

item="criteria" separator="or" >

<if test="criteria.valid" >

Page 87: Ssm 简单 crud 项目

<trim prefix="(" suffix=")"

prefixOverrides="and" >

<foreach collection="criteria.criteria"

item="criterion" >

<choose >

<when test="criterion.noValue" >

and ${criterion.condition}

</when>

<when test="criterion.singleValue" >

and ${criterion.condition}

#{criterion.value}

</when>

<when

test="criterion.betweenValue" >

and ${criterion.condition}

#{criterion.value} and #{criterion.secondValue}

</when>

<when test="criterion.listValue" >

and ${criterion.condition}

<foreach

collection="criterion.value" item="listItem"

open="(" close=")" separator="," >

Page 88: Ssm 简单 crud 项目

#{listItem}

</foreach>

</when>

</choose>

</foreach>

</trim>

</if>

</foreach>

</where>

</sql>

<sql id="Update_By_Example_Where_Clause" >

<where >

<foreach collection="example.oredCriteria"

item="criteria" separator="or" >

<if test="criteria.valid" >

<trim prefix="(" suffix=")"

prefixOverrides="and" >

<foreach collection="criteria.criteria"

item="criterion" >

<choose >

<when test="criterion.noValue" >

and ${criterion.condition}

Page 89: Ssm 简单 crud 项目

</when>

<when test="criterion.singleValue" >

and ${criterion.condition}

#{criterion.value}

</when>

<when

test="criterion.betweenValue" >

and ${criterion.condition}

#{criterion.value} and #{criterion.secondValue}

</when>

<when test="criterion.listValue" >

and ${criterion.condition}

<foreach

collection="criterion.value" item="listItem"

open="(" close=")" separator="," >

#{listItem}

</foreach>

</when>

</choose>

</foreach>

</trim>

</if>

Page 90: Ssm 简单 crud 项目

</foreach>

</where>

</sql>

<sql id="Base_Column_List" >

dept_id, dept_name

</sql>

<select id="selectByExample"

resultMap="BaseResultMap"

parameterType="com.domain.DepartmentExample" >

select

<if test="distinct" >

distinct

</if>

<include refid="Base_Column_List" />

from tnl_dept

<if test="_parameter != null" >

<include refid="Example_Where_Clause" />

</if>

<if test="orderByClause != null" >

order by ${orderByClause}

</if>

</select>

Page 91: Ssm 简单 crud 项目

<select id="selectByPrimaryKey"

resultMap="BaseResultMap"

parameterType="java.lang.Integer" >

select

<include refid="Base_Column_List" />

from tnl_dept

where dept_id = #{deptId,jdbcType=INTEGER}

</select>

<delete id="deleteByPrimaryKey"

parameterType="java.lang.Integer" >

delete from tnl_dept

where dept_id = #{deptId,jdbcType=INTEGER}

</delete>

<delete id="deleteByExample"

parameterType="com.domain.DepartmentExample" >

delete from tnl_dept

<if test="_parameter != null" >

<include refid="Example_Where_Clause" />

</if>

</delete>

<insert id="insert"

parameterType="com.domain.Department" >

Page 92: Ssm 简单 crud 项目

insert into tnl_dept (dept_id, dept_name)

values (#{deptId,jdbcType=INTEGER},

#{deptName,jdbcType=VARCHAR})

</insert>

<insert id="insertSelective"

parameterType="com.domain.Department" >

insert into tnl_dept

<trim prefix="(" suffix=")"

suffixOverrides="," >

<if test="deptId != null" >

dept_id,

</if>

<if test="deptName != null" >

dept_name,

</if>

</trim>

<trim prefix="values (" suffix=")"

suffixOverrides="," >

<if test="deptId != null" >

#{deptId,jdbcType=INTEGER},

</if>

<if test="deptName != null" >

Page 93: Ssm 简单 crud 项目

#{deptName,jdbcType=VARCHAR},

</if>

</trim>

</insert>

<select id="countByExample"

parameterType="com.domain.DepartmentExample"

resultType="java.lang.Integer" >

select count(*) from tnl_dept

<if test="_parameter != null" >

<include refid="Example_Where_Clause" />

</if>

</select>

<update id="updateByExampleSelective"

parameterType="map" >

update tnl_dept

<set >

<if test="record.deptId != null" >

dept_id = #{record.deptId,jdbcType=INTEGER},

</if>

<if test="record.deptName != null" >

dept_name =

#{record.deptName,jdbcType=VARCHAR},

Page 94: Ssm 简单 crud 项目

</if>

</set>

<if test="_parameter != null" >

<include

refid="Update_By_Example_Where_Clause" />

</if>

</update>

<update id="updateByExample" parameterType="map" >

update tnl_dept

set dept_id = #{record.deptId,jdbcType=INTEGER},

dept_name =

#{record.deptName,jdbcType=VARCHAR}

<if test="_parameter != null" >

<include

refid="Update_By_Example_Where_Clause" />

</if>

</update>

<update id="updateByPrimaryKeySelective"

parameterType="com.domain.Department" >

update tnl_dept

<set >

<if test="deptName != null" >

Page 95: Ssm 简单 crud 项目

dept_name = #{deptName,jdbcType=VARCHAR},

</if>

</set>

where dept_id = #{deptId,jdbcType=INTEGER}

</update>

<update id="updateByPrimaryKey"

parameterType="com.domain.Department" >

update tnl_dept

set dept_name = #{deptName,jdbcType=VARCHAR}

where dept_id = #{deptId,jdbcType=INTEGER}

</update>

</mapper>

<?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.dao.EmployeeMapper" >

<resultMap id="BaseResultMap"

type="com.domain.Employee" >

<id column="emp_id" property="empId"

jdbcType="INTEGER" />

Page 96: Ssm 简单 crud 项目

<result column="emp_name" property="empName"

jdbcType="VARCHAR" />

<result column="gender" property="gender"

jdbcType="CHAR" />

<result column="email" property="email"

jdbcType="VARCHAR" />

<result column="d_id" property="dId"

jdbcType="INTEGER" />

</resultMap>

<resultMap id="WithDeptResultMap"

type="com.domain.Employee" >

<id column="emp_id" property="empId"

jdbcType="INTEGER" />

<result column="emp_name" property="empName"

jdbcType="VARCHAR" />

<result column="gender" property="gender"

jdbcType="CHAR" />

<result column="email" property="email"

jdbcType="VARCHAR" />

<result column="d_id" property="dId"

javaType="INTEGER"/>

Page 97: Ssm 简单 crud 项目

<association property="department"

javaType="com.domain.Department">

<id column="dept_id" property="deptId"/>

<result property="deptName"

column="dept_name"/>

</association>

</resultMap>

<sql id="Example_Where_Clause" >

<where >

<foreach collection="oredCriteria"

item="criteria" separator="or" >

<if test="criteria.valid" >

<trim prefix="(" suffix=")"

prefixOverrides="and" >

<foreach collection="criteria.criteria"

item="criterion" >

<choose >

<when test="criterion.noValue" >

and ${criterion.condition}

</when>

<when test="criterion.singleValue" >

and ${criterion.condition}

Page 98: Ssm 简单 crud 项目

#{criterion.value}

</when>

<when

test="criterion.betweenValue" >

and ${criterion.condition}

#{criterion.value} and #{criterion.secondValue}

</when>

<when test="criterion.listValue" >

and ${criterion.condition}

<foreach

collection="criterion.value" item="listItem"

open="(" close=")" separator="," >

#{listItem}

</foreach>

</when>

</choose>

</foreach>

</trim>

</if>

</foreach>

</where>

</sql>

Page 99: Ssm 简单 crud 项目

<sql id="Update_By_Example_Where_Clause" >

<where >

<foreach collection="example.oredCriteria"

item="criteria" separator="or" >

<if test="criteria.valid" >

<trim prefix="(" suffix=")"

prefixOverrides="and" >

<foreach collection="criteria.criteria"

item="criterion" >

<choose >

<when test="criterion.noValue" >

and ${criterion.condition}

</when>

<when test="criterion.singleValue" >

and ${criterion.condition}

#{criterion.value}

</when>

<when

test="criterion.betweenValue" >

and ${criterion.condition}

#{criterion.value} and #{criterion.secondValue}

</when>

Page 100: Ssm 简单 crud 项目

<when test="criterion.listValue" >

and ${criterion.condition}

<foreach

collection="criterion.value" item="listItem"

open="(" close=")" separator="," >

#{listItem}

</foreach>

</when>

</choose>

</foreach>

</trim>

</if>

</foreach>

</where>

</sql>

<sql id="Base_Column_List" >

emp_id, emp_name, gender, email, d_id

</sql>

<sql id="WithDept_Column_List">

e.emp_id,e.emp_name,e.gender,e.email,e.d_id,d.dept

_id,d.dept_name

Page 101: Ssm 简单 crud 项目

</sql>

<select id="selectByExample"

resultMap="BaseResultMap"

parameterType="com.domain.EmployeeExample" >

select

<if test="distinct" >

distinct

</if>

<include refid="Base_Column_List" />

from tbl_emp

<if test="_parameter != null" >

<include refid="Example_Where_Clause" />

</if>

<if test="orderByClause != null" >

order by ${orderByClause}

</if>

</select>

<select id="selectByPrimaryKey"

resultMap="BaseResultMap"

parameterType="java.lang.Integer" >

select

Page 102: Ssm 简单 crud 项目

<include refid="Base_Column_List" />

from tbl_emp

where emp_id = #{empId,jdbcType=INTEGER}

</select>

<delete id="deleteByPrimaryKey"

parameterType="java.lang.Integer" >

delete from tbl_emp

where emp_id = #{empId,jdbcType=INTEGER}

</delete>

<delete id="deleteByExample"

parameterType="com.domain.EmployeeExample" >

delete from tbl_emp

<if test="_parameter != null" >

<include refid="Example_Where_Clause" />

</if>

</delete>

<insert id="insert"

parameterType="com.domain.Employee" >

insert into tbl_emp (emp_id, emp_name, gender,

email, d_id)

values (#{empId,jdbcType=INTEGER},

#{empName,jdbcType=VARCHAR},

Page 103: Ssm 简单 crud 项目

#{gender,jdbcType=CHAR},

#{email,jdbcType=VARCHAR},

#{dId,jdbcType=INTEGER})

</insert>

<insert id="insertSelective"

parameterType="com.domain.Employee" >

insert into tbl_emp

<trim prefix="(" suffix=")"

suffixOverrides="," >

<if test="empId != null" >

emp_id,

</if>

<if test="empName != null" >

emp_name,

</if>

<if test="gender != null" >

gender,

</if>

<if test="email != null" >

email,

</if>

<if test="dId != null" >

Page 104: Ssm 简单 crud 项目

d_id,

</if>

</trim>

<trim prefix="values (" suffix=")"

suffixOverrides="," >

<if test="empId != null" >

#{empId,jdbcType=INTEGER},

</if>

<if test="empName != null" >

#{empName,jdbcType=VARCHAR},

</if>

<if test="gender != null" >

#{gender,jdbcType=CHAR},

</if>

<if test="email != null" >

#{email,jdbcType=VARCHAR},

</if>

<if test="dId != null" >

#{dId,jdbcType=INTEGER},

</if>

</trim>

</insert>

Page 105: Ssm 简单 crud 项目

<select id="countByExample"

parameterType="com.domain.EmployeeExample"

resultType="java.lang.Integer" >

select count(*) from tbl_emp

<if test="_parameter != null" >

<include refid="Example_Where_Clause" />

</if>

</select>

<select id="selectByPrimaryKeyWidthDept"

resultMap="WithDeptResultMap">

select

<include refid="WithDept_Column_List"/>

from tbl_emp e

left join tnl_dept d on e.d_id = d.dept_id

where emp_id = #{empId,jdbcType=INTEGER}

</select>

<select id="selectByExampleWithDept"

resultMap="WithDeptResultMap">

select

<if test="distinct" >

Page 106: Ssm 简单 crud 项目

distinct

</if>

<include refid="WithDept_Column_List" />

from tbl_emp e

left join tnl_dept d on e.d_id = d.dept_id

<if test="_parameter != null" >

<include refid="Example_Where_Clause" />

</if>

<if test="orderByClause != null" >

order by ${orderByClause}

</if>

</select>

<update id="updateByExampleSelective"

parameterType="map" >

update tbl_emp

<set >

<if test="record.empId != null" >

emp_id = #{record.empId,jdbcType=INTEGER},

</if>

<if test="record.empName != null" >

emp_name =

#{record.empName,jdbcType=VARCHAR},

Page 107: Ssm 简单 crud 项目

</if>

<if test="record.gender != null" >

gender = #{record.gender,jdbcType=CHAR},

</if>

<if test="record.email != null" >

email = #{record.email,jdbcType=VARCHAR},

</if>

<if test="record.dId != null" >

d_id = #{record.dId,jdbcType=INTEGER},

</if>

</set>

<if test="_parameter != null" >

<include

refid="Update_By_Example_Where_Clause" />

</if>

</update>

<update id="updateByExample" parameterType="map" >

update tbl_emp

set emp_id = #{record.empId,jdbcType=INTEGER},

emp_name =

#{record.empName,jdbcType=VARCHAR},

gender = #{record.gender,jdbcType=CHAR},

Page 108: Ssm 简单 crud 项目

email = #{record.email,jdbcType=VARCHAR},

d_id = #{record.dId,jdbcType=INTEGER}

<if test="_parameter != null" >

<include

refid="Update_By_Example_Where_Clause" />

</if>

</update>

<update id="updateByPrimaryKeySelective"

parameterType="com.domain.Employee" >

update tbl_emp

<set >

<if test="empName != null" >

emp_name = #{empName,jdbcType=VARCHAR},

</if>

<if test="gender != null" >

gender = #{gender,jdbcType=CHAR},

</if>

<if test="email != null" >

email = #{email,jdbcType=VARCHAR},

</if>

<if test="dId != null" >

d_id = #{dId,jdbcType=INTEGER},

Page 109: Ssm 简单 crud 项目

</if>

</set>

where emp_id = #{empId,jdbcType=INTEGER}

</update>

<update id="updateByPrimaryKey"

parameterType="com.domain.Employee" >

update tbl_emp

set emp_name = #{empName,jdbcType=VARCHAR},

gender = #{gender,jdbcType=CHAR},

email = #{email,jdbcType=VARCHAR},

d_id = #{dId,jdbcType=INTEGER}

where emp_id = #{empId,jdbcType=INTEGER}

</update>

</mapper>

六. Service层编写

1. Service包下分别创建 DepartmentService接口与 EmployeeService并

创建 impl包在此包下创建他们的实现类

package com.service;

import com.domain.Department;

Page 110: Ssm 简单 crud 项目

import java.util.List;

public interface DepartmentService {

List<Department> getAll();

}

package com.service;

import com.domain.Employee;

import java.util.List;

public interface EmployeeService {

List<Employee> getAll();

int save(Employee employee);

Boolean checkName(String empName);

Employee getEmp(Integer id);

int update(Employee employee);

Page 111: Ssm 简单 crud 项目

int delete(Integer id);

int deleteBatch(List<Integer> ids);

}

package com.service.impl;

import com.dao.DepartmentMapper;

import com.domain.Department;

import com.service.DepartmentService;

import

org.springframework.beans.factory.annotation.Autow

ired;

import org.springframework.stereotype.Service;

import java.util.List;

@Service("departmentService")

public class DepartmentServiceImpl implements

DepartmentService {

Page 112: Ssm 简单 crud 项目

@Autowired

private DepartmentMapper departmentMapper;

@Override

public List<Department> getAll() {

return

departmentMapper.selectByExample(null);

}

}

package com.service.impl;

import com.dao.EmployeeMapper;

import com.domain.Employee;

import com.domain.EmployeeExample;

import com.service.EmployeeService;

import

org.springframework.beans.factory.annotation.Autow

ired;

import org.springframework.stereotype.Service;

Page 113: Ssm 简单 crud 项目

import java.util.List;

@Service

public class EmployeeServiceImpl implements

EmployeeService {

@Autowired

EmployeeMapper employeeMapper;

/**查询所有员工

* @return

*/

@Override

public List<Employee> getAll(){

return

employeeMapper.selectByExampleWithDept(null);

}

@Override

public int save( Employee employee) {

return

employeeMapper.insertSelective(employee);

}

Page 114: Ssm 简单 crud 项目

@Override

public Boolean checkName(String empName) {

EmployeeExample example = new

EmployeeExample();

EmployeeExample.Criteria criteria =

example.createCriteria();

criteria.andEmpNameEqualTo(empName);

return

employeeMapper.countByExample(example) == 0;

}

@Override

public Employee getEmp(Integer id) {

return

employeeMapper.selectByPrimaryKey(id);

}

@Override

public int update(Employee employee) {

return

employeeMapper.updateByPrimaryKeySelective(employe

Page 115: Ssm 简单 crud 项目

e);

}

@Override

public int delete(Integer id) {

return

employeeMapper.deleteByPrimaryKey(id);

}

@Override

public int deleteBatch(List<Integer> ids) {

EmployeeExample example = new

EmployeeExample();

EmployeeExample.Criteria criteria =

example.createCriteria();

criteria.andEmpIdIn(ids);

return

employeeMapper.deleteByExample(example);

}

}

七. Controller层编写

Page 116: Ssm 简单 crud 项目

1. Controller下创建 DepartmentController与 EmployeeController

package com.controller;

import com.domain.Department;

import com.message.Msg;

import com.service.DepartmentService;

import

org.springframework.beans.factory.annotation.Autow

ired;

import org.springframework.stereotype.Controller;

import

org.springframework.web.bind.annotation.RequestMap

ping;

import

org.springframework.web.bind.annotation.ResponseBo

dy;

import java.util.List;

@Controller

public class DepartmentController {

@Autowired

Page 117: Ssm 简单 crud 项目

DepartmentService departmentService;

@RequestMapping("/depts")

@ResponseBody

public Msg getAllDept(){

List<Department> list =

departmentService.getAll();

return Msg.success().add("depts",list);

}

}

package com.controller;

import com.domain.Employee;

import com.github.pagehelper.PageHelper;

import com.github.pagehelper.PageInfo;

import com.message.Msg;

import com.service.EmployeeService;

import

org.springframework.beans.factory.annotation.Autow

ired;

import org.springframework.stereotype.Controller;

Page 118: Ssm 简单 crud 项目

import

org.springframework.validation.BindingResult;

import org.springframework.validation.FieldError;

import org.springframework.web.bind.annotation.*;

import

org.springframework.web.servlet.ModelAndView;

import javax.validation.Valid;

import java.util.HashMap;

import java.util.List;

import java.util.Map;

@Controller

public class EmployeeController {

@Autowired

EmployeeService employeeService;

@RequestMapping("/empJson")

public String empJson(){

return "listAjax";

Page 119: Ssm 简单 crud 项目

}

@RequestMapping("/empsAjax")

public @ResponseBody Msg

getEmpsAjax(@RequestParam(value = "pn",defaultValue

= "1")Integer pn){

PageHelper.startPage(pn,5);

List<Employee> list =

employeeService.getAll();

PageInfo<Employee> pageInfo = new

PageInfo<>(list,5);

return Msg.success().add("msg",pageInfo);

}

@RequestMapping(value = "/empSave")

public @ResponseBody Msg empSave(@Valid Employee

employee, BindingResult result){

System.out.println(employee);

if(result.hasErrors()){

Map<String,Object> map = new HashMap<>();

List<FieldError> fieldErrors =

result.getFieldErrors();

Page 120: Ssm 简单 crud 项目

for(FieldError e : fieldErrors){

System.out.println("错误的字段" +

e.getField());

System.out.println("错误信息" +

e.getDefaultMessage());

map.put(e.getField(),e.getDefaultMessage());

}

return

Msg.fail().add("errorField",map);

}else{

employeeService.save(employee);

return Msg.success();

}

}

@RequestMapping("checkName")

@ResponseBody

public Msg checkName(String empName){

String regx =

"(^[a-zA-Z0-9]{6,16}$)|(^[\\u2E80-\\u9FFF]{2,6}$)"

;

Page 121: Ssm 简单 crud 项目

boolean matches = empName.matches(regx);

if(!matches){

return Msg.fail().add("va_msg","用户名必

须是 6-16位或中文");

}

Boolean flag =

employeeService.checkName(empName);

if(flag){

return Msg.success();

} else {

return Msg.fail().add("va_msg","用户名不

可用");

}

}

@RequestMapping(value = "/emp/{id}",method =

RequestMethod.GET)

@ResponseBody

public Msg getEmp(@PathVariable("id") Integer

id){

Employee employee =

employeeService.getEmp(id);

Page 122: Ssm 简单 crud 项目

return Msg.success().add("emp",employee);

}

@RequestMapping(value = "/emp/{empId}",method =

RequestMethod.PUT)

@ResponseBody

public Msg saveEmp(Employee employee){

employeeService.update(employee);

return Msg.success();

}

/**

* 批量删除 一次删除二合一

* */

@RequestMapping(value = "/emp/{ids}",method =

RequestMethod.DELETE)

@ResponseBody

public Msg delEmp(@PathVariable List<Integer>

ids){

if(ids.size() == 1){

employeeService.delete(ids.get(0));

} else{

Page 123: Ssm 简单 crud 项目

employeeService.deleteBatch(ids);

}

return Msg.success();

}

}

八. Msg编写

1. Message包下创建 Msg类用于封装 Controller的返回值

package com.message;

import lombok.Data;

import java.util.HashMap;

import java.util.Map;

@Data

public class Msg {

// 状态码

/**

*

*/

private int code;

Page 124: Ssm 简单 crud 项目

private String msg;

//返回数据

private Map<String,Object> map = new HashMap<>();

public Msg add(String key,Object value){

map.put(key, value);

return this;

}

public static Msg success(){

Msg result = new Msg();

result.setCode(200);

result.setMsg("处理成功!");

return result;

}

public static Msg fail(){

Msg result = new Msg();

result.setCode(500);

result.setMsg("处理失败!");

Page 125: Ssm 简单 crud 项目

return result;

}

}

九. 前端代码编写

1. 创建如下目录,导入 bootstrap,jquery等 js与 css插件

在 index.jsp 中写入如下代码

<%--

Created by IntelliJ IDEA.

User: dell

Date: 2020/2/8

Time: 13:22

To change this template use File | Settings | File

Templates.

Page 126: Ssm 简单 crud 项目

--%>

<%@ page contentType="text/html;charset=UTF-8"

language="java" %>

<%@taglib prefix="c"

uri="http://java.sun.com/jsp/jstl/core" %>

<!DOCTYPE html>

<html>

<head>

<title>Title</title>

<link rel="stylesheet"

href="${pageContext.request.contextPath}/css/boots

trap.css">

<link rel="stylesheet"

href="${pageContext.request.contextPath}/css/boots

trap-theme.css">

<script

src="${pageContext.request.contextPath}/js/jQuery.

1.12.4.js"></script>

<script

src="${pageContext.request.contextPath}/js/bootstr

ap.min.js"></script>

</head>

Page 127: Ssm 简单 crud 项目

<body>

<c:redirect url="empJson"/>

</body>

</html>

2. 主业务代码在 listAjax.jsp 中编写

<%@ taglib prefix="c"

uri="http://java.sun.com/jsp/jstl/core" %>

<%@ page contentType="text/html;charset=UTF-8"

language="java" %>

<!DOCTYPE html>

<html>

<head>

<title>Title</title>

<link rel="stylesheet"

href="${pageContext.request.contextPath}/css/boots

trap.css">

<link rel="stylesheet"

href="${pageContext.request.contextPath}/css/boots

trap-theme.css">

<script

src="${pageContext.request.contextPath}/js/jQuery.

Page 128: Ssm 简单 crud 项目

1.12.4.js"></script>

<script

src="${pageContext.request.contextPath}/js/bootstr

ap.min.js"></script>

</head>

<body>

<%--直接发送ajax请求进行查询 以json形式进行解析实现平

台无关型--%>

<div class="container">

<%--标题--%>

<div class="row">

<div class="col-md-12">

<h1>SSM_CRUD</h1>

</div>

</div>

<div class="row">

<div class="col-md-offset-8">

<button class="btn btn-primary"

id="addEmp">新增</button>

<button class="btn btn-danger"

id="delEmp">删除</button>

</div>

Page 129: Ssm 简单 crud 项目

</div>

<div class="row">

<div class="col-md-12">

<table class="table table-hover">

<thead>

<tr>

<th><input id="checkAll"

type="checkbox"/></th>

<th>#</th>

<th>empName</th>

<th>gender</th>

<th>email</th>

<th>deptName</th>

<th>操作</th>

</tr>

</thead>

<tbody id="empTbody"></tbody>

</table>

</div>

</div>

<div class="row">

<div class="col-md-6" id="pageInfo"></div>

Page 130: Ssm 简单 crud 项目

<div class="col-md-6" id="pageNav"></div>

</div>

</div>

<%--模态框--%>

<!-- Modal -->

<div class="modal fade" id="empAddModal"

tabindex="-1" role="dialog"

aria-labelledby="myModalLabel">

<div class="modal-dialog" role="document">

<div class="modal-content">

<div class="modal-header">

<button type="button" class="close"

data-dismiss="modal" aria-label="Close"><span

aria-hidden="true">&times;</span></button>

<h4 class="modal-title"

id="myModalLabel">添加员工</h4>

</div>

<div class="modal-body">

<form class="form-horizontal"

id="empFrom">

<div class="form-group"

Page 131: Ssm 简单 crud 项目

id="addEmpName">

<label for="inputEmpName"

class="col-sm-2 control-label">empName</label>

<div class="col-sm-10">

<input type="text"

name="empName" class="form-control"

id="inputEmpName" placeholder="empName">

<span

id="empNameHelpBlock" class="help-block"></span>

</div>

</div>

<div class="form-group"

id="addEmpEmail">

<label for="inputEmail"

class="col-sm-2 control-label">email</label>

<div class="col-sm-10">

<input type="email"

name="email" class="form-control" id="inputEmail"

placeholder="[email protected]">

<span id="emailHelpBlock"

class="help-block"></span>

</div>

Page 132: Ssm 简单 crud 项目

</div>

<div class="form-group"

id="addEmpGender">

<label for="inputEmail"

class="col-sm-2 control-label">gender</label>

<div class="col-sm-10">

<label

class="radio-inline">

<input type="radio"

name="gender" id="genderBoy" value="男">男

</label>

<label

class="radio-inline">

<input type="radio"

name="gender" id="genderGirl" value="女">女

</label>

</div>

</div>

<div class="form-group"

id="addEmpDid">

<label for="inputEmail"

class="col-sm-2 control-label">department</label>

Page 133: Ssm 简单 crud 项目

<div class="col-sm-4">

<%--部门提交 id--%>

<select

class="form-control" id="deptSelect"

name="dId"></select>

</div>

</div>

</form>

</div>

<div class="modal-footer">

<button type="button" class="btn

btn-default" data-dismiss="modal">关闭</button>

<button type="button" class="btn

btn-primary" id="empSave">保存</button>

</div>

</div>

</div>

</div>

<!-- Modal -->

<div class="modal fade" id="empEditModal"

tabindex="-1" role="dialog"

Page 134: Ssm 简单 crud 项目

aria-labelledby="myModalLabel">

<div class="modal-dialog" role="document">

<div class="modal-content">

<div class="modal-header">

<button type="button" class="close"

data-dismiss="modal" aria-label="Close"><span

aria-hidden="true">&times;</span></button>

<h4 class="modal-title" >修改员工

</h4>

</div>

<div class="modal-body">

<form class="form-horizontal"

id="empEditFrom">

<div class="form-group"

id="EditEmpName">

<label for="EditInputEmpName"

class="col-sm-2 control-label">empName</label>

<div class="col-sm-10">

<p

class="form-control-static"

id="EditInputEmpName"></p>

<span

Page 135: Ssm 简单 crud 项目

class="help-block"></span>

</div>

</div>

<div class="form-group"

id="EditEmpEmail">

<label for="EditInputEmail"

class="col-sm-2 control-label">email</label>

<div class="col-sm-10">

<input type="email"

name="email" class="form-control"

id="EditInputEmail" placeholder="[email protected]">

<span

class="help-block"></span>

</div>

</div>

<div class="form-group"

id="EditEmpGender">

<label for="EditInputEmail"

class="col-sm-2 control-label">gender</label>

<div class="col-sm-10">

<label

class="radio-inline">

Page 136: Ssm 简单 crud 项目

<input type="radio"

name="gender" id="EditGenderBoy" value="男">男

</label>

<label

class="radio-inline">

<input type="radio"

name="gender" id="EditGenderGirl" value="女">女

</label>

</div>

</div>

<div class="form-group"

id="EditEmpDid">

<label for="inputEmail"

class="col-sm-2 control-label">department</label>

<div class="col-sm-4">

<%--部门提交 id--%>

<select

class="form-control" id="deptEditSelect"

name="dId"></select>

</div>

</div>

</form>

Page 137: Ssm 简单 crud 项目

</div>

<div class="modal-footer">

<button type="button" class="btn

btn-default" data-dismiss="modal">关闭</button>

<button type="button" class="btn

btn-primary" id="empEdit">修改</button>

</div>

</div>

</div>

</div>

<script type="text/javascript">

var total

var thisPage

var aPageNum

$(function () {

to_page(1)

});

$(function () {

$('#delEmp').click(function () {

Page 138: Ssm 简单 crud 项目

var empName = ""

var ids=new Array()

$.each($('.checkItem:checked'),function

() {

var name =

$(this).parents("tr").find("td:eq(2)").text()

var empId =

$(this).parents("tr").find("td:eq(1)").text()

empName = empName + name + " "

ids.push(empId)

})

if(confirm("确定删除[" + empName + "]

么?")){

$.ajax({

url :

"${pageContext.request.contextPath}/emp/" + ids,

type : "POST",

data : "_method=DELETE",

success(data){

alert(data.msg)

to_page(thisPage)

}

Page 139: Ssm 简单 crud 项目

})

}

})

});

$(function () {

$('#checkAll').click(function () {

var status = $(this).prop("checked")

$('.checkItem').prop("checked",status)

})

});

$(function () {

//加载完成后绑定事件用 on

$(document).on("click",".checkItem",function () {

//判断当前选中的元素的个数 决定是否选满了

var len = $('.checkItem:checked').length

$('#checkAll').prop("checked",len ==

aPageNum)

});

Page 140: Ssm 简单 crud 项目

});

$(function () {

//加载完成后绑定事件用 on

$(document).on("click",".edit-btn",function

() {

getDepts("#deptEditSelect")

getEmp($(this).attr("empId"))

//吧 id传给更新按钮

$('#empEdit').attr("empId",$(this).attr("empId"))

$("#empEditModal").modal({

backdrop : 'static'

})

});

});

$(function () {

//加载完成后绑定事件用 on

$(document).on("click",".del-btn",function

() {

Page 141: Ssm 简单 crud 项目

var empName =

$(this).parents("tr").find("td:eq(2)").text()

var empId = $(this).attr("empId")

if(confirm("确认删除[" + empName + "]

么?")){

$.ajax({

url :

"${pageContext.request.contextPath}/emp/" + empId,

type : "POST",

data : "_method=DELETE",

success(data){

to_page(thisPage)

}

})

}

})

});

function getEmp(id) {

$.ajax({

url:"${pageContext.request.contextPath}/emp/" + id,

Page 142: Ssm 简单 crud 项目

type:"GET",

success(data) {

$("#EditInputEmpName").html("<b>" +

data.map.emp.empName + "</b>")

$("#EditInputEmail").val(data.map.emp.email)

$("#empEditModal

input[name=gender]").val([data.map.emp.gender])

$("#empEditModal

select").val([data.map.emp.dId])

}

})

}

$(function () {

$("#addEmp").click(function () {

//表单重置 表单状态重置

reset_from('#empAddModal form')

getDepts("#deptSelect")

$("#empAddModal").modal({

backdrop : 'static'

})

Page 143: Ssm 简单 crud 项目

})

});

function reset_from(ele){

$(ele)[0].reset()

$(ele).find('.form-group').removeClass("has-succes

s has-error")

.find('.help-block').text("")

}

$(function () {

$('#inputEmpName').change(function () {

//发送请求校验用户名

$.ajax({

url:"${pageContext.request.contextPath}/checkName"

,

data:"empName=" + this.value,

success:function (data) {

Page 144: Ssm 简单 crud 项目

if(data.code == 200){

show_validate_msg("#addEmpName","success",data.map

.va_msg)

$('#empSave').attr("ajax-va","success")

} else if(data.code == 500) {

show_validate_msg("#addEmpName","error",data.map.v

a_msg)

$('#empSave').attr("ajax-va","error")

}

}

})

})

});

$(function () {

$('#empEdit').click(function(){

validate_edit_form()

$.ajax({

Page 145: Ssm 简单 crud 项目

url :

"${pageContext.request.contextPath}/emp/" +

$(this).attr("empId"),

//jquery 可以发送 put请求 但是 tomcat

默认不封装参数到请求域(只有 post才会封装)

//需要设置 tomcat一个 filter来帮忙封装

进去

type : "POST",

data : $("#empEditModal

form").serialize() + "&_method=PUT",

success(data){

$('#empEditModal').modal('hide')

to_page(thisPage)

}

})

})

});

$(function () {

$('#empSave').click(function () {

//校验格式

Page 146: Ssm 简单 crud 项目

if(!validate_add_form()){

return false

}

$.ajax({

url:"${pageContext.request.contextPath}/empSave",

data:$("#empAddModal

form").serialize(),

type:"post",

success:function (data) {

//检验是否添加失败

if(data.code == 200){

// 可以通过 serialize() 方法来

序列化表单

$('#empAddModal').modal('hide')

to_page(total)

} else {

console.log(data)

if(undefined !=

data.map.errorField.empName){

Page 147: Ssm 简单 crud 项目

show_validate_msg("#addEmpName","error",data.map.e

rrorField.empName)

$('#empSave').attr("ajax-va","error")

}

if(undefined !=

data.map.errorField.email){

show_validate_msg("#addEmpEmail","error",data.map.

errorField.email)

$('#empSave').attr("ajax-va","error")

}

}

}

})

})

});

function validate_add_form() {

var emp = $("#empAddModal

Page 148: Ssm 简单 crud 项目

form").serializeArray()

var empName = emp[0].value

var email = emp[1].value

var regName =

/(^[a-zA-Z0-9]{6,16}$)|(^[\u2E80-\u9FFF]{2,6}$)/

var regEmail =

/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z

0-9]+)*\.[A-Za-z0-9]+$/

if(!regName.test(empName)){

show_validate_msg("#addEmpName","error","请输入

6-16英文或 2-6的中文")

return false

} else {

show_validate_msg("#addEmpName","success","")

}

if(!regEmail.test(email)){

Page 149: Ssm 简单 crud 项目

show_validate_msg("#addEmailName","error","邮箱格式

错误")

return false

} else {

show_validate_msg("#addEmailName","success","")

}

$("#addEmpGender").addClass("has-success")

$("#addEmpDid").addClass("has-success")

return true

}

function validate_edit_form() {

var emp = $("#empEditModal

form").serializeArray()

var email = emp[1].value

var regEmail =

/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z

0-9]+)*\.[A-Za-z0-9]+$/

Page 150: Ssm 简单 crud 项目

if(!regEmail.test(email)){

show_validate_msg("#eidtEmpName","error","邮箱格式

错误")

return false

} else {

show_validate_msg("#addEmpName","success","")

}

return true

}

function show_validate_msg(ele,status,msg) {

$(ele).removeClass("has-success

has-error").find('span').text("")

if("success" == status){

$(ele).addClass("has-success").find('span').text(m

sg)

} else if("error" == status){

Page 151: Ssm 简单 crud 项目

$(ele).addClass("has-error").find('span').text(msg

)

}

}

function getDepts(ele) {

$.ajax({

url:"${pageContext.request.contextPath}/depts",

type:"get",

success:function (data) {

var department = data.map.depts

$(ele).empty()

$.each(department,function () {

var options =

$("<option></option>").append(this.deptName).val(t

his.deptId)

$(ele).append(options)

})

}

})

Page 152: Ssm 简单 crud 项目

}

function build_emp(result) {

$('#empTbody').empty()

var emps = result.map.msg.list

$.each(emps,function (index, item) {

var empid =

$("<td></td>").append(item.empId)

var empName =

$("<td></td>").append(item.empName)

var gender =

$("<td></td>").append(item.gender)

var email =

$("<td></td>").append(item.email)

var departmentName =

$("<td></td>").append(item.department.deptName)

var buttonEdit =

$("<button></button>").addClass("btn btn-primary

btn-sm")

.append($("<span></span>").addClass

("glyphicon glyphicon-pencil

edit-btn").attr("empId",item.empId).append("编辑

Page 153: Ssm 简单 crud 项目

"))

var buttonDel =

$("<button></button>").addClass("btn btn-danger

btn-sm")

.append($("<span></span>").addClass

("glyphicon glyphicon-remove

del-btn").attr("empId",item.empId).append("删除"))

var btnTd =

$("<td></td>").append(buttonEdit).append("

").append(buttonDel)

$("<tr></tr>").append("<td><input

type='checkbox' class='checkItem'/></td>")

.append(empid).append(empName).appe

nd(gender).append(email).append(departmentName)

.append(btnTd)

.appendTo($('#empTbody'))

})

}

function build_page(result) {

// 解析分页信息

var pageInfo = result.map.msg

Page 154: Ssm 简单 crud 项目

$("#pageInfo").empty().append("当前第"+

pageInfo.pageNum +"页,总共"+ pageInfo.pages + "页\n"

+

",总"+ pageInfo.total +"个")

total = pageInfo.pages

thisPage = pageInfo.pageNum

aPageNum = pageInfo.size

}

function build_nav(result) {

// 解析分页条数据

var ul =

$("<ul></ul>").addClass("pagination")

var firstPageLi =

$("<li></li>").append($("<a></a>").append("首页

").attr("href","#"))

var lastPageLi =

$("<li></li>").append($("<a></a>").append("尾页

").attr("href","#"))

var nextPageLi =

$("<li></li>").append($("<a></a>").append("&raquo;

").attr("href","#"))

var prePageLi =

Page 155: Ssm 简单 crud 项目

$("<li></li>").append($("<a></a>").append("&laquo;

").attr("href","#"))

prePageLi.click(function () {

to_page(result.map.msg.pageNum - 1 )

})

nextPageLi.click(function () {

to_page(result.map.msg.pageNum + 1 )

})

if(result.map.msg.hasPreviousPage == false){

prePageLi = null

firstPageLi.addClass("disabled")

} else {

firstPageLi.click(function () {

to_page(1)

})

}

if(result.map.msg.hasNextPage == false){

nextPageLi = null

lastPageLi.addClass("disabled")

Page 156: Ssm 简单 crud 项目

} else {

lastPageLi.click(function () {

to_page(result.map.msg.pages)

})

}

ul.append(firstPageLi).append(prePageLi)

$.each(result.map.msg.navigatepageNums,function

(index, item) {

var numLi =

$("<li></li>").append($("<a></a>").append(item).at

tr("href","#"))

if(result.map.msg.pageNum == item){

numLi.addClass("active")

}

numLi.click(function () {

to_page(item)

})

ul.append(numLi)

})

Page 157: Ssm 简单 crud 项目

ul.append(nextPageLi).append(lastPageLi)

var nav = $("<nav></nav>").addClass("Page

navigation").append(ul)

$("#pageNav").empty().append(nav)

}

function to_page(pn) {

$.ajax({

url:"${pageContext.request.contextPath}/empsAjax",

data:"pn=" + pn,

type:"get",

success:function (data) {

build_emp(data)

build_page(data)

build_nav(data)

}

})

$("#checkAll").prop("checked",false)

}

</script>

</body>

Page 158: Ssm 简单 crud 项目

</html>

十. 配置 tomcat服务器

1. 在 addConfiguration 配置添加 tomcat

创建完成后点击右下角 fix创建 war 包,并指定 tomcat

Page 159: Ssm 简单 crud 项目

2. 点击绿色小箭头启动如果出现 java.lang.ClassNotFoundException:org.springframework.web.context.ContextLoaderListener 异常再在 project structure 中的

artifacts 中右边右键 putinto ,build 一下项目

3. 完成效果图

Page 160: Ssm 简单 crud 项目

工程中类和方法的说明

一. Msg 类Msg 类用于封装 controller返回的值,除了这种封装也可以封装为枚举类

code属性用于保存响应状态码(200 说明成功)Msg 用于保存返回的信息

Msp 用于保存返回的数据

Add()方法用于向 map 中添加数据

Success 方法会返回一个 Msg 可以链式调用 add 方法来进行赋值

Msg.success().add("depts",list);

二. Example 实体类

用于封装与解耦 mapper 中的 sql 语句,产生 sql 模板,这样就将某条件下的 sql

语句变为了方法

OrderByClause 用于封装排序规则

Distinct 用于封装查询字段

oredCriteria 封装条件的集合

Criteria 用于封装 GeneratedCriteria暴露 Criterion 集合继承于 GeneratedCriteria类

GeneratedCriteria 里面创建了一个 Criterion 集合,定义了具体的条件

Criterion 类将条件进行了封装产生条件的实体类

三. Mapper.xml 文件

Sql标签将条件进行了封装到时候需要时直接引用即可

XxxExample 进行条件查询的方法里面调用了 sql标签定义好的 sql

Ps 邮箱请写正确邮箱,若邮箱不正确会添加不上没有反应,邮箱没有在前端做验

证,可以自己写一个