初学Spring
、SpringMVC
以及Mybatis
时,将其整合时步骤繁多,新手容易不理解,面对繁多的XML
配置,往往也不易跑通代码,这里用于记录一次整合的配置。
整合的目的:通过Spring
的IoC
和AOP
对组件进行管理。即:通过IoC
解决组件间的动态依赖注入;通过AOP
来对事务进行控制,即通过Spring
来整合SpringMVC
及Mybatis
。
想法:对Mybatis
的整合是,在Service
层调用dao
层的接口时,使其自动装配。
首先:一张数据库表对应一个实体类,一个实体类对应一张Mapper.xml
配置文件。在resources
文件夹下创建一个mapper
文件夹,用于存放实体类的Mapper
文件。这里创建EmployeeMapper.xml
配置文件。
一、pom.xml相关配置
1.1 pom.xml
中properties
版本控制
1 2 3 4 5 6 7 8 9 10
| <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <maven.compiler.source>1.8</maven.compiler.source> <maven.compiler.target>1.8</maven.compiler.target> <spring.version>5.0.2.RELEASE</spring.version> <slf4j.version>1.6.6</slf4j.version> <log4j.version>1.2.12</log4j.version> <mysql.version>5.1.6</mysql.version> <mybatis.version>3.4.5</mybatis.version> </properties>
|
1.2 Spring相关依赖导入
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
|
<dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8</version> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</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-web</artifactId> <version>${spring.version}</version> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>${spring.version}</version> </dependency>
<dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</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-jdbc</artifactId> <version>${spring.version}</version> </dependency>
|
1.3 Mybatis及Mybatis-Spring适配包依赖导入
1 2 3 4 5 6 7 8 9 10 11 12
| <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>${mybatis.version}</version> </dependency>
<dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.0</version> </dependency>
|
1.4 数据库相关
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.2</version> <type>jar</type> <scope>compile</scope> </dependency>
<dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>${mysql.version}</version> </dependency>
|
1.5 其他相关
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73
| <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.0</version> <scope>provided</scope> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency>
<dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>${log4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency>
<dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.0.0</version> </dependency>
<dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency>
<dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency>
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.9.0</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.9.0</version> </dependency>
|
二、Mybatis相关配置文件
2.1 Mybatis-config.xml配置文件
创建conf
文件夹,在其下方创建Mybatis-config.xml
。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
| <?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> <properties resource="jdbcConfig.properties"/> <typeAliases> <typeAlias type="cn.lizhi.domain.User" alias="user"/> <package name="cn.lizhi.domain"/> </typeAliases> <environments default="mysql"> <environment id="mysql"> <transactionManager type="JDBC"/> <dataSource type="POOLED"> <property name="driver" value="${jdbc.driver}"/> <property name="url" value="${jdbc.url}"/> <property name="username" value="${jdbc.username}"/> <property name="password" value="${jdbc.password}"/> </dataSource> </environment> </environments> <mappers> <mapper resource="./mappers/EmployeeMapper.xml"/> </mappers> </configuration>
|
2.2 数据库连接配置文件 —— jdbcConfig.properties
1 2 3 4
| jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://url:3306/mybatis?characterEncoding=utf8 jdbc.username=root jdbc.password=root
|
2.3 实体类对应的映射文件Mapper
在conf
文件夹下创建mappers
文件包,继而用于存放全部的实体类映射文件。这里创建EmployeeMapper.xml
配置文件。
1 2 3 4 5 6 7 8 9 10
| <?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="cn.lizhi.dao.UserDao"> <select id="findAll" resultType="employee"> SELECT *FROM employee; </select> </mapper>
|
三、web.xml相关配置文件
3.1 Spring的配置文件的加载
1 2 3 4 5 6 7 8 9
| <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener>
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
|
3.2 前端控制器 —— 对SpringMVC配置文件的加载
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
|
3.3 中文乱码过滤器
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| <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>characterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
|
3.4 Restful风格配置
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <filter> <filter-name>HttpPutFormContentFilter</filter-name> <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class> </filter> <filter-mapping> <filter-name>HttpPutFormContentFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
|
四、SpringMVC配置文件的编写 —— Spring-servlet.xml
SpringMVC
只是用来控制网站跳转逻辑。首先导入相关的名称空间。
1 2 3 4 5 6 7 8 9
| <?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" xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> </beans>
|
4.1 自动扫描所有的组件 —— 只对控制器进行扫描
采用注解扫描,只扫描控制器。
1 2 3 4 5
| <context:component-scan base-package="cn.lizhi" use-default-filters="false"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan>
|
4.2 Springmvc处理器的配置(两个基本配置)
1 2 3 4 5
|
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
|
4.3 视图解析器
1 2 3 4 5
| <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value="/WEB-INF/views/"></property> <property name="suffix" value=".jsp"></property> </bean>
|
4.4 静态资源的处理
1 2 3 4 5 6 7
| <mvc:resources location="/css/" mapping="/css/**"/> <mvc:resources location="/images/" mapping="/images/**"/> <mvc:resources location="/static/js/" mapping="/static/js/**"/> <mvc:resources location="/js/" mapping="/js/**"/> <mvc:resources location="/font/" mapping="/font/**"/> <mvc:resources location="/static/" mapping="/static/**"/>
|
五、Spring的配置文件 —— applicationContext.xml
通过Spring
来管理所有的业务逻辑组件。
5.1 名称空间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| <?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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation="http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> </beans>
|
5.2 配置注解扫描
controller
层交由给SpringMVC
进行管理控制。
1 2 3 4
| <context:component-scan base-package="cn.lizhi"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan>
|
5.3 业务逻辑等相关配置
Spring
用来控制业务逻辑。数据源、事务控制、aop
等等都交由Spring
进行控制。
数据源配置:
1 2 3 4 5 6 7 8 9
| <context:property-placeholder location="classpath:dbconfig.properties" />
<bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="driverClass" value="${jdbc.driverClass}"></property> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> </bean>
|
事务控制:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="pooledDataSource"></property> </bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="*" propagation="REQUIRED" read-only="false"/> <tx:method name="get*" propagation="SUPPORTS" read-only="true"/> </tx:attributes> </tx:advice>
<aop:config> <aop:pointcut expression="execution(* cn.lizhi.service..*(..))" id="txPoint"/> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/> </aop:config>
|
整合mybatis:
目的:
spring
来管理所有组件,即管理mapper
的实现类。
service ==》dao @Autowired:自动注入mapper
;
spring
用来管理事务,spring
声明式事务。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <property name="dataSource" ref="pooledDataSource"></property> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> </bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="cn.lizhi.dao"></property> </bean>
<bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg> <constructor-arg name="executorType" value="BATCH"></constructor-arg> </bean>
|
5.4 重写Mybatis主配置文件
当在Spring
的配置文件中整合了Mybatis
后,需要将Mybatis
中主配置文件中多余的信息删除,此时Mybatis
主配置文件只用来Mybatis中自身的配置,其余的交给Spring
,进行管理。此时配置结果如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| <?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> <typeAliases> <package name="cn.lizhi.domain"/> </typeAliases>
</configuration>
|
六 测试
6.1 dao层的编写
1 2 3 4 5 6
| @Repository public interface EmployeeDao {
Employee findById(Integer id); List<Employee> findAll(); }
|
6.2 service层的编写
1 2 3 4 5 6 7 8 9 10 11 12
| @Service public class EmployeeServiceImpl implements EmployeeService {
@Autowired private EmployeeDao employeeDao;
@Override public List<Employee> findAll() { List<Employee> employees = employeeDao.findAll(); return employees; } }
|
6.3 controller层的编写
1 2 3 4 5 6 7 8 9 10 11 12 13
| @Controller @RequestMapping("/emps") public class EmployeeController { @Autowired private EmployeeService employeeService;
@RequestMapping("/allEmp") public String findAllEmployee(Model model) { List<Employee> employees = employeeService.findAll(); model.addAttribute("employees", employees); return "all"; } }
|
6.4 EmployeeMapper.xml的编写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
| <?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="cn.lizhi.dao.EmployeeDao"> <resultMap id="empFindAll" type="employee"> <id property="empId" column="emp_id"></id> <result property="empName" column="emp_name"></result> <result property="empSalary" column="emp_salary"></result> <result property="empAge" column="emp_age"></result> </resultMap>
<select id="findById" parameterType="int" resultType="employee"> SELECT * FROM table_emp WHERE id=#{id}; </select>
<select id="findAll" resultMap="empFindAll"> SELECT * FROM table_emp; </select> </mapper>
|