整合maven+spring+springmvc+mybatis实现ssm通用增删查改基础开发框架

发布时间:2017-6-29 10:27:30编辑:www.fx114.net 分享查询网我要评论
本篇文章主要介绍了"整合maven+spring+springmvc+mybatis实现ssm通用增删查改基础开发框架",主要涉及到整合maven+spring+springmvc+mybatis实现ssm通用增删查改基础开发框架方面的内容,对于整合maven+spring+springmvc+mybatis实现ssm通用增删查改基础开发框架感兴趣的同学可以参考一下。

整合maven+spring+springmvc+mybatis实现ssm基础开发框架,封装通用增删查改api,提高程序开发效率

myeclipse创建maven项目:


把maven项目转成maven web项目:项目右键Properties


把WebRoot里面的东西移到src/main/webapp下面


打开pom.xml,加入如下,否则报错


项目缺少web.xml文件,在src/main/webapp/WEB-INF下加入web.xml文件即可

pom.xml管理ssm相关jar包

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.xe.demo</groupId>
	<artifactId>demo-ssm</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>war</packaging>
	<properties>
		<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
		<jdk.version>1.8</jdk.version>
		<spring.version>4.2.5.RELEASE</spring.version>
		<mybatis.version>3.3.1</mybatis.version>
		<mybatis.spring.version>1.2.4</mybatis.spring.version>
		<mysql.version>5.1.29</mysql.version>
		<fastjson.version>1.2.4</fastjson.version>
		<druid.version>1.0.13</druid.version>
	</properties>
	<dependencies>
		<!--web -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>javax.servlet-api</artifactId>
			<version>3.1.0</version>
		</dependency>

		<!-- spring -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-context</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-orm</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-oxm</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-jdbc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-tx</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
		</dependency>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-aop</artifactId>
		</dependency>

		<!--spring-aop依赖 -->
		<dependency>
			<groupId>org.aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.8.2</version>
		</dependency>
		<!--spring-json依赖 -->
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.4.6</version>
		</dependency>

		<!--Mybatis -->
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis</artifactId>
			<version>${mybatis.version}</version>
		</dependency>
		<dependency>
			<groupId>org.mybatis</groupId>
			<artifactId>mybatis-spring</artifactId>
			<version>${mybatis.spring.version}</version>
		</dependency>
		<!--分页插件 -->
		<dependency>
			<groupId>com.github.pagehelper</groupId>
			<artifactId>pagehelper</artifactId>
			<version>4.1.6</version>
		</dependency>

		<!--mysql -->
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>${mysql.version}</version>
		</dependency>

		<!--druid -->
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>fastjson</artifactId>
			<version>${fastjson.version}</version>
		</dependency>
		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>${druid.version}</version>
		</dependency>

		<!-- commons -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3</version>
		</dependency>
		<dependency>
			<groupId>commons-collections</groupId>
			<artifactId>commons-collections</artifactId>
			<version>3.2.2</version>
		</dependency>
		<dependency>
			<groupId>org.apache.commons</groupId>
			<artifactId>commons-lang3</artifactId>
			<version>3.1</version>
		</dependency>

		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
	</dependencies>
	<dependencyManagement>
		<dependencies>
			<dependency>
				<groupId>org.springframework</groupId>
				<artifactId>spring-framework-bom</artifactId>
				<version>${spring.version}</version>
				<type>pom</type>
				<scope>import</scope>
			</dependency>
		</dependencies>
	</dependencyManagement>
	<build>
		<plugins>
			<plugin>
				<artifactId>maven-compiler-plugin</artifactId>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
			<!-- 打成war包 -->
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-war-plugin</artifactId>
				<configuration>
					<warName>ssm</warName>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

删除WebRoot目录,右键更新项目


创建项目包结构



到此项目基础结构创建完成


==================================================整合ssm==================================================

配置mybatis-config.xml:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD SQL Map Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		<!-- mybatis支持log4j日志 -->
		<setting name="logImpl" value="LOG4J"/>
		<!-- 开启缓存 -->
		<setting name="cacheEnabled" value="true" />
		<!-- 开启全局懒加载 -->
		<setting name="lazyLoadingEnabled" value="true" />
		<!-- 当设置为‘true’的时候,懒加载的对象可能被任何懒属性全部加载。否则,每个属性都按需加载 -->
		<setting name="aggressiveLazyLoading" value="false" />
		<!-- 允许单一语句返回多结果集 -->
		<setting name="multipleResultSetsEnabled" value="true" />
		<!-- 使用列标签代替列名 -->
		<setting name="useColumnLabel" value="true" />
		<!-- 允许 JDBC 支持生成的键 -->
		<setting name="useGeneratedKeys" value="true" />
		<!-- 指定 MyBatis 如何自动映射列到字段/ 属性 -->
		<setting name="autoMappingBehavior" value="FULL" />
		<!-- 配置默认的执行器 -->
		<setting name="defaultExecutorType" value="REUSE" />
		<!-- 设置超时时间 -->
		<setting name="defaultStatementTimeout" value="25000" />
	</settings>

	<plugins>
		<!-- 分页插件 -->
		<plugin interceptor="com.github.pagehelper.PageHelper"/>
	</plugins>
</configuration>

配置spring-mybatis.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.2.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
    http://www.springframework.org/schema/cache
    http://www.springframework.org/schema/cache/spring-cache-4.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

	<mvc:annotation-driven />
	<!-- 启动组件扫描,排除@Controller组件,该组件由SpringMVC配置文件扫描 -->
	<context:component-scan base-package="com.xe.demo">
		<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

	<!-- mysql数据源 -->
	<bean id="mysqlDataSource" class="com.alibaba.druid.pool.DruidDataSource" destroy-method="close">
		<property name="driverClassName" value="${mysql.driver}" />
		<property name="url" value="${mysql.url}" />
		<property name="username" value="${mysql.username}" />
		<property name="password" value="${mysql.password}" />
		<property name="defaultAutoCommit" value="false" />
		<property name="maxActive" value="20" />
		<property name="initialSize" value="1" />
		<property name="maxWait" value="60000" />
		<property name="minIdle" value="1" />
		<property name="timeBetweenEvictionRunsMillis" value="60000" />
		<property name="minEvictableIdleTimeMillis" value="300000" />
		<property name="validationQuery" value="SELECT 'x'" />
		<property name="testWhileIdle" value="true" />
		<property name="testOnBorrow" value="false" />
		<property name="testOnReturn" value="false" />
		<property name="poolPreparedStatements" value="true" />
		<property name="maxPoolPreparedStatementPerConnectionSize" value="50" />
	</bean>

	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
		<property name="dataSource" ref="mysqlDataSource" />
		<property name="typeAliasesPackage" value="com.xe.demo.model" />
		<property name="configLocation" value="classpath:mybatis/mybatis-config.xml" />
		<property name="mapperLocations" value="classpath:mybatis/*/*.xml"></property>
	</bean>

	<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
		<property name="basePackage" value="com.xe.demo.mapper" />
		<property name="markerInterface" value="com.xe.demo.mapper.BaseMapper" />
		<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
	</bean>

	<bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
		<constructor-arg ref="sqlSessionFactory" />
	</bean>

	<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
		<property name="dataSource" ref="mysqlDataSource" />
	</bean>
	
	<!-- 启动对@AspectJ注解的支持 -->
	<aop:aspectj-autoproxy proxy-target-class="true" />

	<!-- 配置事务切面Bean,指定事务管理器 -->
	<tx:advice id="txAdvice" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="delete*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" />
			<tx:method name="update*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" />
			<tx:method name="save*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" />
			<tx:method name="batch*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception" />
		</tx:attributes>
	</tx:advice>
	<!-- Service aop -->
	<aop:config>
		<aop:pointcut id="pc" expression="execution(* com.xe.demo.service.*Service.*(..))" />
		<aop:advisor pointcut-ref="pc" advice-ref="txAdvice" />
	</aop:config>
</beans>
spring管理配置文件spring.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:tx="http://www.springframework.org/schema/tx"
	xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
	xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:task="http://www.springframework.org/schema/task"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-4.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-4.2.xsd
    http://www.springframework.org/schema/aop
    http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
    http://www.springframework.org/schema/cache
    http://www.springframework.org/schema/cache/spring-cache-4.2.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd">

	<!-- 读取配置文件 -->
	<context:property-placeholder location="classpath*:config.properties" ignore-unresolvable="false" />
	
	<import resource="classpath:spring/spring-mybatis.xml"/>
</beans>

配置spring-mvc.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
	xmlns:context="http://www.springframework.org/schema/context"
	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-mvc.xsd	
		http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

	<mvc:annotation-driven />
	<context:component-scan base-package="com.xe.demo.controller" />
	<!-- 对静态资源文件的访问 -->
	<mvc:resources mapping="/assets/**" location="/assets/" />

	<!-- 配置SpringMVC的视图解析器 -->
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="" />
		<property name="suffix" value=".jsp" />
	</bean>

	<!-- 上传配置 -->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="defaultEncoding" value="UTF-8" />
		<property name="maxUploadSize" value="-1" />
		<property name="maxInMemorySize" value="40960" />
	</bean>
</beans>

创建全局配置文件config.properties:

########################### 数据源配置 ###########################
#########本地数据库#########
#数据源驱动
mysql.driver=com.mysql.jdbc.Driver
mysql.username=root
mysql.password=xie8845233
mysql.url=jdbc:mysql://localhost/demo?autoReconnect=true&useUnicode=true&characterEncoding=utf-8&zeroDateTimeBehavior=convertToNull&allowMultiQueries=true

加载log4j.properties日志文件:

log4j.rootLogger=DEBUG,CONSOLE,ERR_LOG
log4j.addivity.org.apache=false
#打印到控制台
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=%d{yyyy-MM-dd HH\:mm\:ss} -%-4r [%t] %-5p  %x - %m%n
#输入日志到文件
log4j.appender.ERR_LOG=org.apache.log4j.DailyRollingFileAppender
log4j.appender.ERR_LOG.Threshold=ERROR
log4j.appender.ERR_LOG.File=${catalina.home}/logs/demo
log4j.appender.ERR_LOG.DatePattern='_'yyyyMMdd'.log'
log4j.appender.ERR_LOG.Encoding=utf-8
log4j.appender.ERR_LOG.layout=org.apache.log4j.PatternLayout
log4j.appender.ERR_LOG.layout.ConversionPattern=[m6]  %d{yyyy-MM-dd HH\:mm\:ss} %5p %c{1}\:%L \: %m%n

log4j.logger.org.apache=ERROR
log4j.logger.org.mybatis=ERROR
log4j.logger.org.springframework=ERROR

配置web.xml:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
	<display-name>demo-bstable</display-name>
	<welcome-file-list>
		<welcome-file>index.jsp</welcome-file>
	</welcome-file-list>

	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:spring/spring.xml</param-value>
	</context-param>
	<context-param>
		<param-name>log4jConfigLocation</param-name>
		<param-value>classpath:log4j.properties</param-value>
	</context-param>

	<listener>
		<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
	</listener>
	<!-- 启动加载spring容器 -->
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

	<servlet>
		<servlet-name>demoServlet</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>classpath:spring/spring-mvc.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>demoServlet</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
	
	<!-- 编码过滤器 -->
	<filter>
		<filter-name>encodingFilter</filter-name>
		<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
		<init-param>
			<param-name>encoding</param-name>
			<param-value>UTF-8</param-value>
		</init-param>
		<init-param>
			<param-name>forceEncoding</param-name>
			<param-value>true</param-value>
		</init-param>
	</filter>
	<filter-mapping>
		<filter-name>encodingFilter</filter-name>
		<url-pattern>/*</url-pattern>
	</filter-mapping>
</web-app>

创建通用mapper接口BaseMapper.java:

package com.xe.demo.mapper;

import java.io.Serializable;
import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.xe.demo.common.pojo.PageAjax;

/**
 * Mybatis基础DAO
 * @author 蔡泽华
 */
public interface BaseMapper<T> {

	/**
	 * 通过ID查询
	 * @param id
	 * @return
	 */
	Object selectById(Serializable id);
	
	/**
	 * 查询单条记录
	 * @param entity
	 * @return
	 */
	Object selectOne(@Param("item")Object obj);

	/**
	 * 查询记录集合
	 * @param entity
	 * @return
	 */
	List<?> selectList(@Param("item")Object obj);
	
	/**
	 * 分页查询
	 * @param t
	 * @param page
	 * @return
	 */
	List<T> selectPage(@Param("item")Object obj, @Param("page")PageAjax<T> page);

	/**
	 * 通用的保存方法
	 * @param <T>
	 * @param entity
	 */
	void save(@Param("item")Object obj);
	
	/**
	 * 批量保存
	 * @param list
	 */
	int batchSave(List<?> list);

	/**
	 * 通用的修改方法
	 * @param <T>
	 * @param entity
	 */
	int update(@Param("item")Object obj);
	
	/**
	 * 批量更新
	 * @param list
	 * @return
	 */
	int batchUpdate(List<?> list);

	/**
	 * 删除方法
	 * @param id
	 */
	int delById(Serializable id);
	
	/**
	 * 批量删除
	 * @param list
	 * @return
	 */
	int delList(List<?> list);

	/**
	 * 批量删除方法
	 * @param ids
	 */
	int delArray(int[] ids);

	/**
	 * 统计查询
	 * @param <T>
	 * @param params 查询参数
	 * @return 总记录条数
	 */
	int count(Object obj);

}

创建通用业务层实现BaseService.java:

package com.xe.demo.service;

import java.io.Serializable;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;

import com.xe.demo.common.pojo.PageAjax;
import com.xe.demo.mapper.BaseMapper;

/**
 * 通用业务层
 * @author 蔡泽华
 */
public class BaseService<T> {
	
	@Autowired
	private BaseMapper<T> baseMapper;

	/**
	 * 通过ID查询
	 * @param id
	 * @return
	 */
	public Object selectById(Serializable id) {
		return baseMapper.selectById(id);
	}

	/**
	 * 查询单条记录
	 * @param entity
	 * @return
	 */
	public Object selectOne(Object obj) {
		return baseMapper.selectOne(obj);
	}

	/**
	 * 查询集合
	 * @param t
	 * @return
	 */
	public List<?> selectList(Object obj) {
		return (List<?>) baseMapper.selectList(obj);
	}
	
	/**
	 * 分页查询
	 * @param t
	 * @param page
	 * @return
	 */
	public PageAjax<T> selectPage(Object obj, PageAjax<T> page){
		List<T> list = baseMapper.selectPage(obj, page);
		return new PageAjax<T>(list);
	}

	/**
	 * 通用的保存方法
	 * @param <T>
	 * @param entity
	 */
	public void save(Object obj) {
		baseMapper.save(obj);
	}

	/**
	 * 批量保存
	 * @param list
	 */
	public void batchSave(List<?> list) {
		baseMapper.batchSave(list);
	}

	/**
	 * 通用的修改方法
	 * @param <T>
	 * @param entity
	 */
	public void update(Object obj) {
		baseMapper.update(obj);
	}

	/**
	 * 删除方法
	 * @param id
	 */
	public int delById(Serializable id) {
		return baseMapper.delById(id);
	}

	/**
	 * 批量删除
	 * @param list
	 * @return
	 */
	public int delList(List<?> list) {
		return baseMapper.delList(list);
	}

	/**
	 * 批量删除方法
	 * @param ids
	 */
	public int delArray(int[] ids) {
		return baseMapper.delArray(ids);
	}

	/**
	 * 统计查询
	 * @param <T>
	 * @param params 查询参数
	 * @return 总记录条数
	 */
	public int count(T t) {
		return baseMapper.count(t);
	}
	
	/**
	 * 批量更新
	 * @param list
	 * @return
	 */
	public int batchUpdate(List<?> list){
		return baseMapper.batchUpdate(list);
	}
	/*@Autowired
	private SqlSessionTemplate sqlSessionTemplate;
	
	*//**
	 * 批量更新
	 * @param str
	 * @param obj
	 * @return
	 * @throws Exception
	 *//*
	public int batchUpdate(String str, List<?> objs) {
		SqlSessionFactory sqlSessionFactory = sqlSessionTemplate.getSqlSessionFactory();
		// 批量执行器
		SqlSession sqlSession = sqlSessionFactory.openSession(ExecutorType.BATCH, false);
		int succ = 0;
		try {
			if (objs != null) {
				for (int i = 0, size = objs.size(); i < size; i++) {
					sqlSession.update(str, objs.get(i));
				}
				sqlSession.flushStatements();
				sqlSession.commit();
				sqlSession.clearCache();
			}
		} finally {
			sqlSession.close();
		}
		return succ;
	}*/
}

创建数据表t_user:
CREATE TABLE `t_user` (
  `id` int(3) unsigned NOT NULL AUTO_INCREMENT,
  `username` char(20) NOT NULL,
  `password` char(32) NOT NULL,
  `email` varchar(100) DEFAULT NULL,
  `useable` tinyint(4) NOT NULL DEFAULT '1' COMMENT '是否可用(0禁用,1可用)',
  `addtime` datetime NOT NULL COMMENT '创建时间',
  `logintime` datetime DEFAULT NULL COMMENT '登陆时间',
  `loginip` varchar(15) DEFAULT NULL COMMENT '登陆IP',
  PRIMARY KEY (`id`),
  KEY `username` (`username`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=39 DEFAULT CHARSET=utf8;

编写增删查改sql映射文件UserMapper.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.xe.demo.mapper.UserMapper">
	<select id="selectById" resultType="map">
		SELECT u.id, u.username, u.password, u.email, u.useable, u.addtime, u.logintime, u.loginip FROM t_user u where u.id = #{id}
	</select>
	
	<select id="selectOne" resultType="user">
		SELECT u.id, u.username, u.password, u.email, u.useable, u.addtime, u.logintime, u.loginip FROM t_user u where 1 = 1
		<if test="null != id"> and u.id = #{id}</if>
		<if test="null != username"> and u.username = #{username}</if>
		<if test="null != email"> and u.email = #{email}</if>
	</select>

	<select id="selectList" resultType="map">
		SELECT u.id, u.username, u.password, u.email, u.useable, u.addtime, u.logintime, u.loginip FROM t_user u
		<where>
			<if test="null != username and '' != username"> and u.username like CONCAT('%', #{username}, '%')</if>
			<if test="null != email and '' != email"> and u.email like CONCAT('%', #{email}, '%')</if>
		</where>
	</select>
	
	<select id="selectPage" resultType="map">
		SELECT u.id, u.username, u.password, u.email, u.useable, u.addtime, u.logintime, u.loginip FROM t_user u where 1 = 1
			<if test="null != obj.username and '' != obj.username"> and u.username like CONCAT('%', #{obj.username}, '%')</if>
			<if test="null != obj.email and '' != obj.email"> and u.email = #{obj.email}</if>
		limit #{page.startRow}, #{page.pageSize}
	</select>
	
	<insert id="save">
		insert into t_user(username, password, email, useable, addtime)
		values(#{username}, #{password}, #{email}, #{useable}, now())
	</insert>
	
	<update id="update">
		update t_user set password = #{password}, email = #{email}, useable = #{useable} where id = #{id}
	</update>

	<update id="batchSave">
		insert into t_user(username, password, email, useable, addtime) values
		<foreach collection="list" item="item" index="index" separator=",">
			(#{item.username}, #{item.password}, #{item.email}, #{item.useable}, now())
		</foreach>
	</update>

	<update id="batchUpdate">
		<foreach collection="list" item="item" index="index" open="" close="" separator=";">
			update t_user set password = #{item.password}, email = #{item.email}, useable = #{item.useable} where id = #{item.id}
		</foreach>
	</update>
	
	<delete id="delArray">
		delete from t_user where id in
		<foreach collection="array" item="item" open="(" separator="," close=")">
			#{item}
		</foreach>
	</delete>
	
	<delete id="delList">
		delete from t_user where id in
		<foreach collection="list" item="item" open="(" separator="," close=")">
			#{item}
		</foreach>
	</delete>
</mapper>
创建UserService继承BaseService.java;

创建UserController.java实现功能:

package com.xe.demo.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.xe.demo.common.pojo.AjaxResult;
import com.xe.demo.common.pojo.PageAjax;
import com.xe.demo.model.User;
import com.xe.demo.service.UserService;

@Controller
public class UserController {

	@Autowired
	private UserService userService;
	
	@ResponseBody
	@RequestMapping("/queryById")
	public AjaxResult queryById(int id){
//		User user = userService.selectById(id);
		Object user = userService.selectById(id);
		return new AjaxResult(user);
	}
	
	@ResponseBody
	@RequestMapping("/queryOne")
	public AjaxResult queryOne(User user){
		Object obj = userService.selectOne(user);
		return new AjaxResult(obj);
	}
	
	@ResponseBody
	@RequestMapping("/queryList")
	public AjaxResult queryList(User user){
		List<?> list = userService.selectList(user);
		return new AjaxResult(list);
	}
	
	@ResponseBody
	@RequestMapping("/queryPage")
	public PageAjax<User> queryPage(User user, PageAjax<User> page){
		return userService.selectPage(user, page);
	}

	@ResponseBody
	@RequestMapping("/save")
	public AjaxResult save(User user){
		//保存map测试
		Map<String, Object> map = new HashMap<String, Object>();
		map.put("username", user.getUsername());
		map.put("email", user.getEmail());
		map.put("useable", user.getUseable());
		map.put("password", user.getPassword());
		userService.save(map);
		return new AjaxResult();
	}
	
	@ResponseBody
	@RequestMapping("/update")
	public AjaxResult update(User user){
		//更新map测试
//		Map<String, Object> map = new HashMap<String, Object>();
//		map.put("id", user.getId());
//		map.put("email", user.getEmail());
//		map.put("useable", user.getUseable());
//		map.put("password", user.getPassword());
		userService.update(user);
		return new AjaxResult();
	}
	
	@ResponseBody
	@RequestMapping("/batchSave")
	public AjaxResult batchSave(){
//		List<User> list = new ArrayList<User>();
//		User user = null;
//		for(int i = 0; i < 10; i ++){
//			user = new User();
//			String username = "ourte" + i;
//			user.setUsername(username);
//			user.setPassword("123456");
//			user.setUseable(1);
//			user.setEmail(username + "@163.com");
//			list.add(user);
//		}

		//map批量保存
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = null;
		for(int i = 0; i < 10; i ++){
			map = new HashMap<String, Object>();
			String username = "csefgg" + i;
			map.put("username", username);
			map.put("email", username + "@163.com");
			map.put("useable", 1);
			map.put("password", "658264");
			list.add(map);
		}
		userService.batchSave(list);
		return new AjaxResult();
	}
	
	@ResponseBody
	@RequestMapping("/batchUpdate")
	public AjaxResult batchUpdate(){
		Integer[] ids = new Integer[]{30, 31, 32};

//		List<User> list = new ArrayList<User>();
//		User user = null;
//		for(int id: ids){
//			user = new User();
//			user.setId(id);
//			user.setPassword("654321");
//			user.setUseable(0);
//			user.setEmail("csew@163.com");
//			list.add(user);
//		}
		
		//map批量更新
		List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
		Map<String, Object> map = null;
		for(int id: ids){
			map = new HashMap<String, Object>();
			map.put("id", id);
			map.put("email", "dfdwfg@163.com");
			map.put("useable", 1);
			map.put("password", "565656");
			list.add(map);
		}
		userService.batchUpdate(list);
		return new AjaxResult();
	}

	@ResponseBody
	@RequestMapping("/delList")
	public AjaxResult delList(Integer[] ids){
		List<Integer> list = Arrays.asList(ids);
		userService.delList(list);
		return new AjaxResult();
	}
	
	@ResponseBody
	@RequestMapping("/delArray")
	public AjaxResult delArray(int[] ids){
		userService.delArray(ids);
		return new AjaxResult();
	}

}

部署启动项目,使用http请求模拟器请求接口测试:

1.通过ID查询:

2.通过条件查询返回实体集合


3.通过条件查询返回Map集合


4.多条件分页查询实体


5.多条件分页查询map


6.批量保存数据


7.批量更新数据


8.评论删除(mybatis接收List<Integer>参数)


9.批量删除(mybatis接收int[]参数)


10.添加数据


11.更新数据



项目源码下载地址:整合maven+spring+springmvc+mybatis实现ssm通用增删查改API(没BUG版本)


上一篇:maven搭建项目骨架
下一篇:mac下递归创建ctags报错: "illegal option -

相关文章

相关评论

本站评论功能暂时取消,后续此功能例行通知。

一、不得利用本站危害国家安全、泄露国家秘密,不得侵犯国家社会集体的和公民的合法权益,不得利用本站制作、复制和传播不法有害信息!

二、互相尊重,对自己的言论和行为负责。

好贷网好贷款