1、Mybatis的配置使用

1》Jar包:mybatis-3.4.5.jar、mysql-connector-6.0.2或者ojdbc6-11.2.0.4.jar。

2》编写conf.xml,用于构建SqlSessionFactory。

<?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>
<!-- 配置用于控制台输出sql日志。低版本的mybatis不支持logImpl -->
<setting name="logImpl" value="LOG4J"/>
</settings> <environments default="oracle">
<environment id="oracle">
<!-- 指定事务管理类型,type="JDBC"指直接使用JDBC的提交与回滚 -->
<transactionManager type="JDBC" />
<!-- 配置数据库连接信息 -->
<dataSource type="POOLED">
<property name="driver" value="oracle.jdbc.OracleDriver" />
<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl" />
<property name="username" value="scott" />
<property name="password" value="scott" />
</dataSource>
</environment>
<environment id="mysql">
<transactionManager type="JDBC" />
<!-- 配置数据库连接信息 -->
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver" />
<property name="url" value="jdbc:mysql://127.0.0.1:3306/world" />
<property name="username" value="root" />
<property name="password" value="root" />
</dataSource>
</environment>
</environments> <mappers>
<!-- 注册empMapper.xml文件-->
<mapper resource="com/lfy/mapping/empMapper.xml"/>
</mappers> </configuration>

3》编写mapper.xml、或者使用注解、或者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-->
<mapper namespace="com.lfy.mapping.empMapper">
<select id="getEmp" parameterType="int" resultType="com.lfy.bean.Emp">
select * from emp where empno=#{empno}
</select>
</mapper>

4》获取SqlSession,使用SqlSession调用相关方法进行数据库操作。

package com.lfy.Util;

import java.io.InputStream;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder; public class MyBatisUtil { /**
* 获取SqlSessionFactory
* @return SqlSessionFactory
*/
public static SqlSessionFactory getSqlSessionFactory() {
String resource = "conf.xml";
InputStream is = MyBatisUtil.class.getClassLoader().getResourceAsStream(resource);
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(is);
return factory;
} /**
* 获取SqlSession
* @return SqlSession
*/
public static SqlSession getSqlSession() {
return getSqlSessionFactory().openSession();
} /**
* 获取SqlSession
* @param isAutoCommit
* true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务
* false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务
* @return SqlSession
*/
public static SqlSession getSqlSession(boolean isAutoCommit) {
return getSqlSessionFactory().openSession(isAutoCommit);
} /**
* 获取对应的mapper接口
* @param clazz
* @return
*/
public static <T> T getMapper(Class<T> clazz){
return getSqlSessionFactory().openSession().getMapper(clazz);
} /**
* 获取对应的mapper接口
* @param clazz mapper接口类型
* @param isAutoCommit
* true 表示创建的SqlSession对象在执行完SQL之后会自动提交事务
* false 表示创建的SqlSession对象在执行完SQL之后不会自动提交事务,这时就需要我们手动调用sqlSession.commit()提交事务
* @return
*/
public static <T> T getMapper(Class<T> clazz,boolean isAutoCommit){
return getSqlSessionFactory().openSession(isAutoCommit).getMapper(clazz);
}
}

2、Spring的配置使用

1》Jar包:spring、commons-logging.1.2.jar、aspectj-1.8.0.jar、aopalliance-1.0.jar

2》编写beans.xml,注册spring Bean。

<?xml version="1.0" encoding="UTF-8"?>
<!-- spring配置文件的根元素,使用spring-beans-4.0.xsd语义约束 -->
<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:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.0.xsd"> <!-- 指定自动搜索bean组件、自动搜索切面类 -->
<context:component-scan base-package="com.lfy.aspect,com.lfy.impl">
<context:include-filter type="annotation" expression="org.aspectj.lang.annotation.Aspect"/>
</context:component-scan> <!-- 或者不打算使用spring的xml schema配置方式,则应该在spring配置文件中增加如下片段
来启动@AspectJ的支持
<bean class="org.springframework.aop.aspectj.annotation.
AnnotationAwareAspectJAutoProxyCreator"/>
为了在spring应用中启动@AspectJ的支持,还需要在应用的类加载路径下增加两个AspectJ库:
aspectjweaver.jar和aspectjrt.jar,除此之外,spring AOP还依赖aopalliance.jar
-->
<!-- 启动@AspectJ支持 -->
<aop:aspectj-autoproxy/> <!-- 完全不打算使用spring的xml schema配置方式使用spring AOP,即bean的注册也使用注解的形式。
应该加入如下代码 ,AnnotationAwareAspectJAutoProxyCreator是一个bean后处理器,该bean
后处理器将会为容器中的所有bean生成AOP代理
-->
<bean class="org.springframework.aop.aspectj.annotation.AnnotationAwareAspectJAutoProxyCreator"/>
</beans>

3》编写相关的bean或者AOP切面。可以是注解类型的、也可以是bean配置文件配置的,切面有5种类型(before、around、afterThrowing、afterReturning、after)。

4》根据beans.xml创建ApplicationContext,根据ApplicationContext获取容器中的bean使用。

3、Spring MVC的配置使用

1》Jar包:spring、commons-logging-1.2.jar

2》在Web.xml中配置前端控制器,并引入springmvc-config.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>springMVCInterceptorTest-1.0.0</display-name> <servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:config/spring/springmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 让Spring MVC的前端控制器拦截所有请求 -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- 编码过滤器 -->
<filter>
<filter-name>characterEncodingFilter</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> -->
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>

springmvc-config.xml

<?xml version="1.0" encoding="utf-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans"
xmlns:p="http://www.springframework.org/schema/p"
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-4.0.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"> <mvc:default-servlet-handler/>

<!-- 扫描控制器 -->
<context:component-scan base-package="com.lfy.controller"/> <!-- 映射器、适配器策略 -->
<mvc:annotation-driven/> <!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/content/" p:suffix=".jsp" />
</beans>

3》@Controller编写控制器、@RequestMapping配置处理方法路径。额外的增加自定义类型转换器、拦截器。

4、Mybatis+Spirng+Spring MVC的配置使用(常规复制jar包的形式)

1》搭建的jar包

1>springframework框架jar包。springframework-5.0.1框架jar包+commons-logging-1.2日志jar包

2>Mybatis框架jar包。mybatis-3.4.5.jar及mybatis-3.4.5包下lib文件所有的jar包:cblib-3.2.5.jar、javassist-3.22.0-CR2.jar、log4j-1.2.17.jar、log4j-api-2.3.jar、log4j-core-2.3.jar、ognl-3.1.15.jar等。

3>Mybatis整合spring中间件的jar包。mybatis-spring-1.3.1.jar,主要作用是:

1>>在spring中配置Mybatis工厂类

2>>在DAO层使用spring注入的工具Bean对数据进行操作。

4>aspectj框架jar包。aspectjrt.jar、aspectjtools.jar、aspectjweaver.jar、org.aspectj.matcher.jar。

5>AOP联盟jar包。aopalliance.jar。

6>数据库驱动包。mysql-connector-java-5.1.30.jar。

7>数据源c3p0所需的jar包。c3p0-0.9.5.2.jar、hibernate-c3p0-4.3.5.Final.jar、mchange-commons-java-0.2.1.1.jar。

8>jsp、JSTL标签库jar包。javax.servlet.jsp.jstl-1.2.1.jar、javax.servlet.jsp.jstl-api-1.2.1.jar

2》项目目录结构

db.properties

dataSource.driverClass=com.mysql.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://127.0.0.1:3306/mybatis
dataSource.user=root
dataSource.password=root
dataSource.maxPoolSize=20
dataSource.maxIdleTime = 1000
dataSource.minPoolSize=6
dataSource.initialPoolSize=5

web.xml:整合spring、springMVC

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1"> <display-name>springMybatisSpringMVC-1.0.0</display-name> <!-- 配置spring核心监听器,默认会以 /WEB-INF/applicationContext.xml作为配置文件 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- contextConfigLocation参数用来指定Spring的配置文件 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext*.xml</param-value>
</context-param> <!-- 定义Spring MVC的前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/springmvc-config.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet> <!-- 让Spring MVC的前端控制器拦截所有请求 -->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- 编码过滤器 -->
<filter>
<filter-name>characterEncodingFilter</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>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> </web-app>

springmvc-config.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:p="http://www.springframework.org/schema/p"
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:default-servlet-handler/> <context:component-scan base-package="com.lfy.controller"/> <!-- 映射器、适配器 -->
<mvc:annotation-driven/> <bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/content/" p:suffix=".jsp"/> </beans>

applicationContext.xml:整合Mybatis

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://mybatis.org/schema/mybatis-spring
http://mybatis.org/schema/mybatis-spring.xsd "> <!-- 扫描com.lfy包下面的java文件,有Spring的相关注解的类,则把这些类注册为Spring的bean -->
<context:component-scan base-package="com.lfy"/> <!-- 使用PropertyOverrideConfigurer后处理器加载数据源参数 -->
<context:property-override location="classpath:db.properties"/> <!-- 配置c3p0数据源 -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"/> <!-- 配置SqlSessionFactory,org.mybatis.spring.SqlSessionFactoryBean是Mybatis社区开发用于整合Spring的bean -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
p:dataSource-ref="dataSource"/>

<!-- mybatis:scan会将com.lfy.mapper包里的所有接口当作mapper配置,之后可以自动引入mapper类-->
      <mybatis:scan base-package="com.lfy.mapper"/>

    <!-- JDBC事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
p:dataSource-ref="dataSource"/> <!-- 启用支持annotation注解方式事务管理 -->
<tx:annotation-driven transaction-manager="transactionManager"/> </beans>

5、Mybatis+Spring+SpringMVC的配置使用(Maven)

1》项目目录结构

2》引入依赖

<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.lfy.cn</groupId>
<artifactId>mavenMybatisSpringSpringMVC-1.0.0</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version> <name>mavenMybatisSpringSpringMVC-1.0.0 Maven Webapp</name>
<url>http://maven.apache.org</url> <properties>
<!-- 自定义的spring的版本号 -->
<spring.version>5.0.1.RELEASE</spring.version>
<!-- 自定义的mybaits的版本号 -->
<mybatis.version>3.4.5</mybatis.version>
<!-- 自定义的mybaits-spring的版本号 -->
<mybatis.spring.version>1.3.1</mybatis.spring.version>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties> <dependencies>
<!-- springMVC的jar包,由于springMVC依赖 springBeans,springContext,springCore 所以这些jar包会被导入进来-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
<scope>compile</scope>
</dependency>
<!-- spring-tx 事务 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
<scope>compile</scope>
</dependency>
<!-- spring-jdbc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
<scope>compile</scope>
</dependency>
<!-- aspectjweaver aop 依赖该jar包-->
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.13</version>
</dependency> <!-- servlet的jar包 begin -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>compile</scope>
</dependency>
<!-- servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<!-- javax.servlet.jsp.jstl-api -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>javax.servlet.jsp.jstl-api</artifactId>
<version>1.2.2</version>
</dependency>
<!-- taglibs-standard-impl jstl的实现 -->
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-impl</artifactId>
<version>1.2.5</version>
</dependency>
<!-- servlet的jar包 end --> <!-- mybatis begin -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>${mybatis.version}</version>
<scope>compile</scope>
</dependency>
<!-- mybatis-spring -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>${mybatis.spring.version}</version>
<scope>compile</scope>
</dependency>
<!--druid 连接池 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.10</version>
<scope>compile</scope>
</dependency>
<!-- mysql的连接驱动 -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
<!-- mybatis end --> <!--log4j2 begin -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.1</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-web</artifactId>
<version>2.1</version>
</dependency>
<!--log4j2 end --> <!-- junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies> <build>
<finalName>mavenMybatisSpringSpringMVC-1.0.0</finalName>
</build>
</project>

3》web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1"> <display-name>mavenMybatisSpringSpringMVC-1.0.0</display-name> <!-- 配置编码 -->
<filter>
<filter-name>characterEncodingFilter</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>forceRequestEncoding</param-name>
<param-value>true</param-value>
</init-param>
<init-param>
<param-name>forceResponseEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping> <!-- spring IOC容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext-*.xml</param-value>
</context-param>
<!-- 加载监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- 配置spring mvc的前端控制器 -->
<servlet>
<servlet-name>spring-mvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 本地的上下文配置 加载springmvc的配置文件 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc-config.xml</param-value>
</init-param>
<!-- 启动容器的时候加载 -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring-mvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping> <!-- log4j2-begin -->
<context-param>
<param-name>isLog4jAutoInitializationDisabled</param-name>
<param-value>false</param-value>
</context-param>
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>classpath:log4j2.xml</param-value>
</context-param>
<listener>
<listener-class>org.apache.logging.log4j.web.Log4jServletContextListener</listener-class>
</listener>
<filter>
<filter-name>log4jServletFilter</filter-name>
<filter-class>org.apache.logging.log4j.web.Log4jServletFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>log4jServletFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
<!-- log4j2-end -->
</web-app>

4》springmvc-config.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:p="http://www.springframework.org/schema/p"
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 ">
<!--
springmvc的配置文件:
扫描handler对象
配置注解的处理器映射器和处理器适配器
配置内部资源视图解析器
处理不了的静态资源交给tomcat
--> <context:component-scan base-package="com.login.web.controller"/> <mvc:annotation-driven/> <bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver"
p:prefix="/WEB-INF/content/" p:suffix=".jsp"/> <mvc:default-servlet-handler/> </beans>

5》applicationContext-dao.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://mybatis.org/schema/mybatis-spring
http://mybatis.org/schema/mybatis-spring.xsd ">
<!--
spring 整合 mybatis 的配置:
配置数据库连接池
配置sqlSessionFactory
配置扫描器
配置扫描所有的service类
--> <!-- 加载db.properties文件 -->
<context:property-placeholder location="classpath:db.properties"/> <!-- 配置数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc_driverClassName}"/>
<property name="url" value="${jdbc_url}"/>
<property name="username" value="${jdbc_username}"/>
<property name="password" value="${jdbc_password}"/>
</bean> <!-- 配置sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource"/>
<!-- mybatis的配置文件 -->
<property name="configLocation" value="classpath:mybatis/mybatis-config.xml"/>
<!-- mapper文件 -->
<property name="mapperLocations">
<!--加载所有的mapper文件 -->
<list>
<!-- 或者 <value>classpath:mybatis/mappers/*.xml</value> -->
<value>classpath:mybatis/mappers/IUserMapper.xml</value>
</list>
</property>
</bean> <!-- 配置mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
<property name="basePackage" value="com.login.dao"/>
</bean> <!--扫描所有的service作为spring bean -->
<context:component-scan base-package="com.login.service"/>
</beans>

6》applicationContext-tx.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mybatis="http://mybatis.org/schema/mybatis-spring"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:tx="http://www.springframework.org/schema/tx"
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/tx
http://www.springframework.org/schema/tx/spring-tx.xsd
http://mybatis.org/schema/mybatis-spring
http://mybatis.org/schema/mybatis-spring.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd ">
<!-- 配置spring的事务
mybatis采用的是spring中的jdbc中的事务管理(配置事务管理器)
事务增强
aop切面
-->
<!--事务管理 -->
<bean id="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean> <!-- 增强 -->
<tx:advice id="tx_advice" transaction-manager="tx" >
<tx:attributes>
<!-- 事务传播规则 -->
<tx:method name="save*" propagation="REQUIRED"/>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="do*" propagation="REQUIRED"/> <tx:method name="get*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="list*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="query*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="count*" propagation="SUPPORTS" read-only="true"/>
</tx:attributes>
</tx:advice> <!-- Aop 切面
proxy-target-class="false" 是默认的 =====》 默认使用jdk动态代理 基于接口
proxy-target-class="true" =============》使用cglib动态代理 基于类
-->
<aop:config proxy-target-class="false">
<aop:advisor advice-ref="tx_advice" pointcut="execution(* com.login.service.*Service.*(..) )"/>
</aop:config> </beans>

7》mybatis-config.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>
<!-- 配置mybatis的日志 -->
<setting name="logImpl" value="LOG4J2"/>
<!--开启延迟加载 -->
<setting name="lazyLoadingEnabled" value="true"/>
<!--设置不要积极去加载 -->
<setting name="aggressiveLazyLoading" value="false"/>
<!--延迟加载的触发方法 -->
<setting name="lazyLoadTriggerMethods" value="clone"/>
</settings>
<!-- 别名 -->
<typeAliases>
<package name="com.login.dao"/>
</typeAliases>
</configuration>

8》IUserMapper.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.login.dao.IUserMapper"> <select id="getUserByUsername" parameterType="map" resultType="com.login.entity.User">
SELECT * FROM user WHERE username = #{username} and password= #{password}
</select>
</mapper>

9》db.properties

jdbc_driverClassName=com.mysql.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/db_ssm
jdbc_username=root
jdbc_password=root

10》log4j2.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- log4j2使用说明(create By SeanXiao ):
使用方式如下:
private static final Logger logger = LogManager.getLogger(实际类名.class.getName()); 2、日志说明:
(1)请根据实际情况配置各项参数
(2)需要注意日志文件备份数和日志文件大小,注意预留目录空间
(3)实际部署的时候backupFilePatch变量需要修改成linux目录
-->
<configuration status="OFF">
<Properties>
<Property name="fileName">front.log</Property>
<Property name="backupFilePatch">C:/Users/lfy/Desktop/work/temp/log/</Property>
</Properties>
<!--先定义所有的appender-->
<appenders>
<!--这个输出控制台的配置-->
<Console name="Console" target="SYSTEM_OUT">
<!--控制台只输出level及以上级别的信息(onMatch),其他的直接拒绝(onMismatch)-->
<ThresholdFilter level="trace" onMatch="ACCEPT" onMismatch="DENY" />
<!--这个都知道是输出日志的格式-->
<PatternLayout pattern="%d{HH:mm:ss.SSS} %-5level %class{36} %L %M - %msg%xEx%n" />
</Console> <!--这个会打印出所有的信息,每次大小超过size,则这size大小的日志会自动存入按年份-月份建立的文件夹下面并进行压缩,作为存档-->
<RollingFile name="RollingFile" fileName="${backupFilePatch}${fileName}"
filePattern="${backupFilePatch}$${date:yyyy-MM}/app-%d{yyyyMMddHHmmssSSS}.log.gz">
<PatternLayout
pattern="%d{yyyy.MM.dd 'at' HH:mm:ss.SSS z} %-5level %class{36} %L %M - %msg%xEx%n" /> <!-- 日志文件大小 -->
<SizeBasedTriggeringPolicy size="20MB" />
<!-- 最多保留文件数 -->
<DefaultRolloverStrategy max="20"/>
</RollingFile>
</appenders> <!--然后定义logger,只有定义了logger并引入的appender,appender才会生效-->
<loggers>
<!--建立一个默认的root的logger-->
<Logger name="com.login.service" level="trace" additivity="true">
<AppenderRef ref="RollingFile" />
</Logger>
<Root level="info">
<AppenderRef ref="Console" />
</Root>
</loggers>
</configuration>

11》Controller

package com.login.web.controller;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.login.entity.User;
import com.login.service.IUserService; @Controller
@RequestMapping("/UserController")
public class UserController { private static final Logger logger = LogManager.getLogger(UserController.class.getName()); @Autowired
private IUserService service; /**
* redirect page
* @return
*/
@RequestMapping(path="/loginForm")
public String loginForm() {
return "loginForm";
} @RequestMapping(path="/login")
public ModelAndView login(String username,String password,ModelAndView mv) { User user = service.login(username, password); if(user != null){ logger.info(user); mv.addObject("user", user);
mv.setViewName("success");
}else{
mv.addObject("message", "登录名或密码错误,请重新输入!");
mv.setViewName("loginForm");
}
return mv;
}
}

12》Service

package com.login.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.login.dao.IUserMapper;
import com.login.entity.User;
import com.login.service.IUserService; @Service
public class UserServiceImpl implements IUserService { @Autowired
private IUserMapper mapper; @Override
public User login(String username, String password) { return mapper.getUserByUsername(username,password);
}
}

13》DAO

package com.login.dao;

import org.apache.ibatis.annotations.Param;

import com.login.entity.User;

public interface IUserMapper {

  User getUserByUsername(@Param("username") String username,@Param("password") String password);
}

14》Entity

package com.login.entity;

import java.io.Serializable;

public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    private String username;
private String password; public User() {
super();
} public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
} @Override
public String toString() {
return "User=[username="+username+",password="+password+"]";
}
}

spring-第N篇整合SSM,即Mybatis+Spring+Spring MVC的更多相关文章

  1. SSM :MyBatis与Spring的整合

    MyBatis与Spring的整合 一:Spring整合MyBatis的准备工作: (1.)在项目中加入Spring,ByBatis及整合相关的jar文件 (2.)建立开发目录结构,创建实体类 (3. ...

  2. 关于Mybatis与Spring整合之后SqlSession与mapper对象之间数量的问题。

    1,sqlsession的真实类型和数量 由于使用spring管理bean,当我们在代码中需要使用这个bean的时候,会首先去容器中找,第一次需要调用MapperFactoryBean的getObje ...

  3. SSM框架整合(IntelliJ IDEA + maven + Spring + SpringMVC + MyBatis)

    本篇文章主要内容是介绍如何使用IntelliJ IDEA创建Spring + SpringMVC + MyBatis项目,下面会给出项目搭建的详细步骤以及相关的配置文件. 1. 创建maven项目   ...

  4. Java基础-SSM之Spring和Mybatis以及Spring MVC整合案例

    Java基础-SSM之Spring和Mybatis以及Spring MVC整合案例 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. 能看到这篇文章的小伙伴,详细你已经有一定的Java ...

  5. SSM 即所谓的 Spring MVC + Spring + MyBatis 整合开发。

    SSM 即所谓的 Spring MVC + Spring + MyBatis 整合开发.是目前企业开发比较流行的架构.代替了之前的SSH(Struts + Spring + Hibernate) 计划 ...

  6. Mybatis第五篇【Mybatis与Spring整合】

    Mybatis与Spring整合 既然我们已经学了Mybatis的基本开发了,接下来就是Mybatis与Spring的整合了! 以下使用的是Oracle数据库来进行测试 导入jar包 aopallia ...

  7. 从0开始整合SSM框架--2.spring整合mybatis

    依赖:<properties> <!-- spring版本号 --> <spring.version>4.1.3.RELEASE</spring.versio ...

  8. 【MyBatis学习14】MyBatis和Spring整合

    前面十几篇博文总结了mybatis在开发中的相关技术,但在实际中都是和spring整合开发的,所以这里总结一下mybatis和spring的整合方法,并在整合后进行测试. 1. 整合的环境 这都是老掉 ...

  9. Mybatis+struts2+spring整合

    把student项目改造成ssm  struts2 +mybatis+spring 1,先添加spring支持:类库三个,applicationContext.xml写在webinf下四个命名空间,监 ...

随机推荐

  1. MySQL 创建唯一索引忽略对已经重复数据的检查

    MySQL 创建唯一索引忽略对已经重复数据的检查 在创建唯一索引的基础上加上关键字"IGNORE "即可.(注意,经测试,在5.7版本已经不再支持该参数) # 重复数据 mysql ...

  2. pt-config-diff的使用记录

    pt-config-diff的使用记录 pt-config-diff功能:比较差异两套库配置差不多,性能就是不一样,无奈之举,去比对数据库配置是否相同. 运行的MySQL和运行的MySQL做对比 [r ...

  3. Nginx静态文件服务器配置方法

    在Java开发以及生产环境中,最常用的web应用服务器当属Tomcat,尽管这只猫也能够处理一些静态请求,例如图片.html.样式文件等,但是效率并不是那么尽人意.在生产环境中,我们一般使用Nginx ...

  4. 【NOIP2016提高A组模拟8.17】(雅礼联考day1)Value

    题目 分析 易证,最优的答案一定是按\(w_i\)从小到大放. 我们考虑dp, 先将w从小到大排个序,再设\(f_{i,j}\)表示当前做到第i个物品,已选择了j个物品的最大值.转移就是\[f_{i, ...

  5. shiro框架学习-3- Shiro内置realm

    1. shiro默认自带的realm和常见使用方法 realm作用:Shiro 从 Realm 获取安全数据 默认自带的realm:idae查看realm继承关系,有默认实现和自定义继承的realm ...

  6. SQL基础-order by

    若sql语句中order by指定了多个字段,则怎么排序? 举个例子吧:order by id desc,time desc 先是按 id 降序排列  (优先)如果 id 字段 有些是一样的话   再 ...

  7. SSM整合之---简单选课系统

    简单选课系统 一.实体图 二.功能 三.代码实现 1.SSM环境搭建 (1)pom.xml <dependencies> <dependency> <groupId> ...

  8. FP AUTO节点ZPP002M执行卡住解决

    正常情况下,不到一分钟即可执行完ZPP002M节点 异常情况下,超过十分钟都没有响应 再等待只会影响FP的执行时间,影响后续的节点,解决办法是将正在执行的JOB STOP掉 再到服务器上将该节点重新执 ...

  9. SpringBoot,用200行代码完成一个一二级分布式缓存

    缓存系统的用来代替直接访问数据库,用来提升系统性能,减小数据库复杂.早期缓存跟系统在一个虚拟机里,这样内存访问,速度最快. 后来应用系统水平扩展,缓存作为一个独立系统存在,如redis,但是每次从缓存 ...

  10. 微信 JS-SDK 各种问题记录

    在开发微信公众号网页中,使用微信的 JS-SDK 会遇到各种坑.记录遇到的坑及解决方法. 1.JS-SDK 配置(url 指向). 在 JS-SDK 配置中,配置的签名基本在服务器完成,网上有各种方法 ...