IntelliJ IDEA 创建maven 项目 并且,将springMVC 与Mybatis 整合

时间:2022-12-25 09:53:32

好记性不如烂笔头,今天弄一个springMVC 与Mybatis整合,虽然网上有好多,但是只有自己实践过才是最真的,有不足的地方请指教(大牛请绕开)
之前已经写好了,在有些地方也写了自己的理解,但是一不小心踢到插头,哎,悲剧,这是写的第二遍,然后没有讲太多。下面是项目地址

https://github.com/Breet1413/SpringMVC-Maven/tree/master

环境准备

  • IntelliJ IDEA 2016.3.5  
  • jdk1.7
  • maven-3.2.3
  • tomcat7
  • Mybatis 3.0

创建一个基本的maven 框架

1,创建项目  选择 file>new>project,弹出一个界面,按照图中标注,最后下一步

IntelliJ IDEA 创建maven 项目 并且,将springMVC 与Mybatis 整合

2,填写GroupId和ArtifactId后接着下一步 (version 可以改也可以不该,一般默认)。

IntelliJ IDEA 创建maven 项目 并且,将springMVC 与Mybatis 整合

 

3,接着到了maven环境的选择,你可以默认idea自带的maven,可以选择自己的版本,我这里是选择本地的maven,然后设置setting.xml
IntelliJ IDEA 创建maven 项目 并且,将springMVC 与Mybatis 整合

 IntelliJ IDEA 创建maven 项目 并且,将springMVC 与Mybatis 整合

在穿件maven 骨架和下载jar 是非常慢的,因为要访问外国的服务器,所以你懂得,最好有个自己的vpn。

然后确定会在出现一个界面,next 填写项目名称,然后finish

为项目创建java目录

4, 选择file》project structure ,然后选择modules ,按照下图标注步骤操作,在这里简单介绍一下 ,Sources标注类似 src 这种可编译目录,如果你需要别的目录也编译,那就要用sources来标注。Tests 标注可编译的单元测试目录,Resources 标注资源文件目录

IntelliJ IDEA 创建maven 项目 并且,将springMVC 与Mybatis 整合

5,完成上述步骤后,接下就可以建立相应的目录结构,大家可以按照自己平时的习惯来建立(我没介绍的东西可以忽略比如redis)

IntelliJ IDEA 创建maven 项目 并且,将springMVC 与Mybatis 整合

 6.pom.xml文件配置

IntelliJ IDEA 创建maven 项目 并且,将springMVC 与Mybatis 整合IntelliJ IDEA 创建maven 项目 并且,将springMVC 与Mybatis 整合
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.example</groupId>
<artifactId>MySpringMVC</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>SpringMVC-Maven</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.build.timestamp.format>yyyyMMdd</maven.build.timestamp.format>
<commons-fileupload.version>1.3.1</commons-fileupload.version>
<commons-io.version>2.4</commons-io.version>
<dom4j.version>1.6.1</dom4j.version>
<spring.version>4.2.0.RELEASE</spring.version>
<dom4j.version>1.6.1</dom4j.version>
<tomcat.version>2.2</tomcat.version>
<webserver.port>8182</webserver.port>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!--common start -->
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>18.0</version>
</dependency>

<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>1.2.17</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>

<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>

<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2.1</version>
</dependency>
<!--common end -->

<!--spring start -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aspects</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-expression</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<!--spring end -->
<!--springmvc 控制层 start -->
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>

<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
<version>3.1.0</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.7.4</version>
</dependency>
<!--springmvc end -->

<!--mybatis 数据访问层 start -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
<scope>runtime</scope>
</dependency>

<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.20</version>
</dependency>

<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.0</version>
</dependency>

<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.0</version>
</dependency>
<!-- jedis-->
<dependency>
<groupId>redis.clients</groupId>
<artifactId>jedis</artifactId>
<version>2.8.0</version>
</dependency>

<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>1.6.4.RELEASE</version>
</dependency>

<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-core</artifactId>
<version>1.0.8</version>
</dependency>

<dependency>
<groupId>com.dyuproject.protostuff</groupId>
<artifactId>protostuff-runtime</artifactId>
<version>1.0.8</version>
</dependency>

<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.7.0</version>
</dependency>
<!--mybatis 数据访问层 end -->
<!-- 文件上传 -->
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>${commons-fileupload.version}</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>${commons-io.version}</version>
</dependency>
</dependencies>
<build>
<finalName>MySpringMVC</finalName>
<resources>
<resource>
<!--directory: 资源所在的位置 -->
<directory>src/main/resources</directory>
<!--filtering: 是否替换资源中的属性placehold -->
<filtering>true</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>2.3.2</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-war-plugin</artifactId>
<version>2.6</version>
</plugin>
<!-- tomcat7插件 -->
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>${tomcat.version}</version>
<configuration>
<port>${webserver.port}</port>
<path>/</path>
<uriEncoding>${project.build.sourceEncoding}</uriEncoding>
</configuration>
</plugin>

</plugins>
</build>
</project>
pom.xml

pom文件配置好之后,idea会自动去下载你配置的jar包,不过这个下载的过程比较慢,访问是国外的服务器,可以使用vpn

7.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>Archetype Created Web Application</display-name>
<!--配置DispatcherServlet -->
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置SpringMVC需要加载的配置文件 spring-xxx.xml -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-*.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<!--默认匹配所有的请求 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--welcome pages-->
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>

 

8,springmvc文件配置 ,我这里写了两个resources/spring,文件下spring-web.xml.spring-dao.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:context
="http://www.springframework.org/schema/context"
xmlns:mvc
="http://www.springframework.org/schema/mvc"
xmlns:aop
="http://www.springframework.org/schema/aop"
xsi:schemaLocation
="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd"
>

<!-- 扫描controller(后端控制器),并且扫描其中的注解-->
<context:component-scan base-package="com.example.controller"/>
<!-- 定义无Controller的path<->view直接映射 -->
<mvc:view-controller path="/" view-name="redirect:admin"/>

<!--配置JSP 显示ViewResolver(视图解析器)-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 开启驱动注解 可以将request参数与绑定到controller参数上-->
<mvc:annotation-driven/>
<!-- 服务扫描-->
<context:component-scan base-package="com.example.service" />
<!--静态资源默认servlet配置
1、加入对静态资源的处理:js,css,gif,png
2、允许使用"/"做整体映射
-->
<mvc:default-servlet-handler/>
<mvc:resources mapping="/statics/**" location="/WEB-INF/statics/" /><!--可配置多个 -->

<!--spring mvc 子线程配置 为了提高效率有的项目需要线程来完成相关功能,不要可忽略-->
<bean id="taskExecutor" class="org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor">
<!-- 核心线程数 -->
<property name="corePoolSize" value="5" />
<!-- 最大线程数 -->
<property name="maxPoolSize" value="50" />
<!-- 队列最大长度 -->
<property name="queueCapacity" value="1000" />
<!-- 线程池维护线程所允许的空闲时间,默认为60s -->
<property name="keepAliveSeconds" value="60" />
</bean>
<!-- 拦截器配置(可配置多个),拦截顺序:先执行后定义的,排在第一位的最后执行。-->
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/admin/**" /><!--需要拦截的控制器-->
<mvc:exclude-mapping path="/admin/login"/>
<!--<mvc:exclude-mapping path="/admin/index"/>-->
<mvc:exclude-mapping path="/admin/loginIn"/><!--不需要拦截的控制器-->
<bean class="com.example.interceptor.LogInterceptor" />
</mvc:interceptor>
</mvc:interceptors>

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

</beans>

spring-dao.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:context
="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd"

>

<!--配置整合mybatis过程-->

<!--1、配置数据库相关参数-->
<context:property-placeholder location="classpath:jdbc.properties" ignore-unresolvable="true"/>

<!--2.数据源druid -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method
="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driverClassName}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />

<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="${druid.pool.size.init}" />
<property name="minIdle" value="${druid.pool.size.min}" />
<property name="maxActive" value="${druid.pool.size.max}" />

<!-- 配置监控统计拦截的filters,wall用于防止sql注入,stat用于统计分析 -->
<property name="filters" value="wall,stat" />

</bean>
<!--mybatis 步骤是什么样子的
1.创建sqlSessionFactory
2.通过sqlSessionFactory创建sqlSession
3.通过sqlSession执行curd操作,(即创建、更新、读取、删除)
4.调用session.commit()提交事务
5.调用session.close()关闭回话;
-->
<!--3、配置SqlSessionFactory对象-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!--注入数据库连接池-->
<property name="dataSource" ref="dataSource"/>
<!--配置mybatis全局配置文件:mybatis-config.xml-->
<property name="configLocation" value="classpath:mybatis-config.xml"/>
<!--扫描entity包,使用别名,多个用;隔开-->
<property name="typeAliasesPackage" value="com.click.oea.core.entity"/>
<!--扫描sql配置文件:mapper需要的xml文件-->
<property name="mapperLocations" value="classpath:mapper/*.xml"/>
</bean>

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

<!-- 扫描basePackage下所有以@MyBatisDao注解的接口 -->
<bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
<property name="basePackage" value="com.example.dao"/>
<property name="annotationClass" value="com.example.annotation.MyBatisDao"/>
</bean>

<!-- 定义事务 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource" />
</bean>

<!-- 配置 Annotation 驱动,扫描@Transactional注解的类定义事务 -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>

</beans>

当前配置写到这里可能xml文件会报错,但是请忽略它,下面将解决 

9.jdbc.properties连接数据库配置

#本地数据库
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true
&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123
druid.pool.size.max=20
druid.pool.size.min=3
druid.pool.size.init=3

 

 10,log4j.properties配置,做个比较优秀的调试bug工具,项目中还是必不可少的

IntelliJ IDEA 创建maven 项目 并且,将springMVC 与Mybatis 整合IntelliJ IDEA 创建maven 项目 并且,将springMVC 与Mybatis 整合
 1 log4j.rootLogger=info, console, log, error
2
3 ###Console ###
4 log4j.appender.console = org.apache.log4j.ConsoleAppender
5 log4j.appender.console.Target = System.out
6 log4j.appender.console.layout = org.apache.log4j.PatternLayout
7 log4j.appender.console.layout.ConversionPattern = %d %p[%C:%L]- %m%n
8
9 ### log ###
10 log4j.appender.log = org.apache.log4j.DailyRollingFileAppender
11 #log4j.appender.log.File = ${catalina.base}/logs/debug.log
12 log4j.appender.log.File = ./logs/debug.log
13 log4j.appender.log.Append = true
14 log4j.appender.log.Threshold = DEBUG
15 log4j.appender.log.DatePattern='.'yyyy-MM-dd
16 log4j.appender.log.layout = org.apache.log4j.PatternLayout
17 log4j.appender.log.layout.ConversionPattern = %d %p[%c:%L] - %m%n
18
19
20 ### Error ###
21 log4j.appender.error = org.apache.log4j.DailyRollingFileAppender
22 #log4j.appender.error.File = ${catalina.base}/logs/error.log
23 log4j.appender.error.File = ./logs/error.log
24 log4j.appender.error.Append = true
25 log4j.appender.error.Threshold = ERROR
26 log4j.appender.error.DatePattern='.'yyyy-MM-dd
27 log4j.appender.error.layout = org.apache.log4j.PatternLayout
28 log4j.appender.error.layout.ConversionPattern =%d %p[%c:%L] - %m%n
29
30 ### \u8F93\u51FA SQL
31 log4j.logger.com.example=DEBUG
32 log4j.logger.com.ibatis=DEBUG
33 log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=DEBUG
34 log4j.logger.com.ibatis.common.jdbc.ScriptRunner=DEBUG
35 log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapClientDelegate=DEBUG
36 log4j.logger.java.sql.Connection=DEBUG
37 log4j.logger.java.sql.Statement=DEBUG
38 log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.properties

 

11.接下来就解决上面有问题的地方

  11.1在package com.example.interceptor文件夹下新建LogInterceptor类

package com.example.interceptor;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
* Created by Administrator on
*/
public class LogInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o) throws Exception {
//该方法将在请求处理之前进行调用,比如判断当前登录的用户,如果没有登录
// 跳到你自己的登录页面 response.sendRedirect("/admin/login"); 返回 false,下面两个方法都不会执行
//有登录,返回true
return true;
}
@Override
public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {
//preHandle 方法的返回值为true 时才能被调当前请求进行处理之后,
// 也就是Controller 方法调用之后执行,但是它会在DispatcherServlet 进行视图返回渲染之前被调用
}
@Override
public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {
//该方法将在整个请求结束之后,也就是在DispatcherServlet 渲染了对应的视图之后执行
// 在这里可以做些日志处理 LogUtils.saveLog(request, handler, e);
}
}

 

  11.2 在package com.example.annotation新建一个接口来自定注解MyBatisDao,为什么要写这个自定注解,因为mapper文件对应的dao跟方法接口dao是功能类型是一样,所以就把它放到一起,这个思路可以参照jeesite这个开源项目,这样使结构更加清晰,虽然有点牵强但是还是不错的。

package com.example.annotation;

import org.springframework.stereotype.Component;
import java.lang.annotation.*;

/**
* Created by Administrator on 2017/3/23.
*/
//自定义注解 适用类、接口(包括注解类型)或枚举,
@Retention(RetentionPolicy.RUNTIME)//RetentionPolicy还有好多其他参数,想知道可自行了解
@Target(ElementType.TYPE)
@Documented
//注解表明这个注解应该被 javadoc工具记录
@Component//泛指组件,当组件不好归类的时候,我们可以使用这个注解进行标注
public @interface MyBatisDao {
}

 12,基础配置都写完了,接下就开始操作数据库了,随便写个数据库,建立测试表user,id(int,主键,自增),name(varchar),set(varchar),age(int)

   对应的实体就不在这里建立了,篇幅比较长.

   新建mapper文件,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.example.dao.UserDao">
<sql id="userField">
a.id as "id",
a.name as "name",
a.sex as "sex",
a.age as "age"
</sql>
<!-- 插入一条用户记录 -->
<insert id="saveUser" parameterType="com.example.entity.User">
insert into user (name, sex, age)
values ( #{name}, #{sex}, #{age} )
</insert>

<!-- 获取所有用户 -->
<select id="listAllUser" resultType="com.example.entity.User">
select
<include refid="userField"/>
from user as a
</select>

<!-- 更新用户信息 -->
<update id="updateUser" parameterType="com.example.entity.User">
update user
<set>
<if test="name != null and name != '' ">
name = #{name},
</if>
<if test="sex != null and sex != '' ">
sex = #{sex},
</if>
<if test="age != null and age != '' ">
age = #{age},
</if>
</set>
where id = #{id}
</update>

<!-- 根据id删除用户 -->
<delete id="deleteUserById" parameterType="java.lang.Integer">
delete from user where id = #{id}
</delete>
<!-- 根据id获取用户-->
<select id="getUserById" parameterType="java.lang.Integer" resultType="com.example.entity.User">
select
<include refid="userField"/>
from user as a where a.id = #{id}
</select>
<!-- 批量添加用户-->
<insert id="batchSaveUser" parameterType="java.util.List">
insert into user (name,sex,age) values
<!-- 动态SQL之foreach的用法 -->
<!-- collection="users" 用于指定循环集合的名称,如果接口中并未指定参数别名,那么默认就是list
item="u" 用于指定每次循环后的对象的别名
separator="," 用于指定每次循环后之间的分割符
-->
<foreach collection="list" item="u" separator=",">
(#{u.name},#{u.sex},#{u.age})
</foreach>
</insert>
<!-- 批量删除-->
<delete id="batchDeleteUser" parameterType="java.lang.String">
DELETE FROM user where id in
<foreach item="idItem" collection="array" open="(" separator="," close=")">
#{idItem}
</foreach>
</delete>
</mapper>

 

13,userDao建立

package com.example.dao;

import com.example.annotation.MyBatisDao;
import com.example.base.CrudDao;
import com.example.entity.User;
import java.util.List;
import org.apache.ibatis.annotations.Param;

/**
* Created by Administrator on 2017/3/23.
*/
@MyBatisDao
public interface UserDao extends CrudDao<User> {
/**
* 保存用户
*
@param user
*/
void saveUser(User user);

/**
* 获取所有用户列表
*
@return
*/
List
<User> listAllUser();

/**
* 根据id查询用户信息
*
@param id
*
@return
*/
User getUserById(@Param(
"id") Integer id);

/**
* 更新用户的信息
*
@param user
*/
int updateUser(User user);

/**
* 根据id删除指定的用户
*
@param id
*/
void deleteUserById(@Param("id") Integer id);

/**
* 批量添加用户
*
@param list
*/
void batchSaveUser(List<User> list);

/**
* 批量删除用户
*
@param ids
*/
void batchDeleteUser(String[] ids);

}

 

 14,userService建立 

package com.example.service;

import com.example.base.CrudService;
import com.example.dao.UserDao;
import com.example.entity.User;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import java.util.List;

/**
* Created by Administrator on 2017/3/23.
*/
@Service
//只能被应用到public方法上, 对于其它非public的方法,如果标记了@Transactional也不会报错,但方法没有事务功能.
@Transactional(readOnly = true)//否为只读事务 true表示只读,false表示不是,发生错误会回滚
public class UserService extends CrudService<UserDao, User> {

public User getUserById(Integer id){
return dao.getUserById(id);
}

public List<User> listAllUser(){
return dao.listAllUser();
}
//对于不是添加,修改,删除,设置readOnly = false,
@Transactional(readOnly = false)
public void batchSaveUser(List<User> list){
dao.batchSaveUser(list);
}
@Transactional(readOnly
= false)
public int updateUser(User user){
return dao.updateUser(user);
}
}

 

  15,Controller建立

package com.example.controller;

import com.example.entity.User;
import com.example.service.UserService;
import com.google.common.collect.Lists;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.RequestMethod;
import java.util.List;

/**
* Created by Administrator on 2017/3/23.
*/
@Controller
@RequestMapping(
"index")
public class indexController {
private final Logger LOG = LoggerFactory.getLogger(this.getClass());
@Autowired
private UserService userService;
@RequestMapping(value
= "", method = RequestMethod.GET)
public String index(){
//根据id获取
System.out.println(userService.getUserById(1));
List
<User> aList = Lists.newArrayList();
aList.add(
new User("2","1",1));
aList.add(
new User("2","3",4));
//批量插入
userService.batchSaveUser(aList);

List
<User> list = userService.listAllUser();
for(User u:list){
System.out.println(u);
}
//更
User user = new User(1,"小名","",23);
     LOG.info(userService.updateUser(user)+"");
return "index"; } }

 

16,项目运行的方式有两种一个是配置本地的tomcat 服务器,二是运行tomcat的插件,本地我就不配置了,此处是用插件运行
IntelliJ IDEA 创建maven 项目 并且,将springMVC 与Mybatis 整合

运行成功后 在浏览器输入http://localhost:8182/index 然后点回车,就可以看到操作数据库的,向页面传值,什么分页啊,这些插件网上百度一大把我就不介绍