1. 整合Spring和MyBatis
注意:(1) 如果Mapper接口的名称是HelloWorldMapper,则对应的mapper映射文件也应该名称为HelloWorldMapper.xml或者是helloWorldMapper.xml。
(2) 对于Maven项目而言,我们通常会把配置文件放到resources目录下面的,对于HelloWorldMapper.xml文件我也喜欢放到该目录下面。但是如果直接放到该目录下面是找不到该mapper映射文件的。如果直接放到src/main/java目录对应的HelloWorldMapper接口的目录中是可以找到的,所以我们可以在resources目录下建一个目录为对应于HelloWorldMapper接口的目录。例如:com.jd.mapper.HelloWorldMapper目录,则在resources目录下也建一个目录com.jd.mapper.HelloWorldMapper.xml即可。
(3) 在使用MyBatis的时候,SQL语句是写在xml文件当中的,对于xml格式的文件而言,不允许出现类似“>”这样的字符,但是都可以使用<![CDATA[ ]]>符号将你写的含有特殊字符SQL语句括起来,将此类符号不进行解析。
(4) 在使用MyBatis框架的时候,你所写的Java实体类的属性字段必须和数据库中的字段名称相同。如果不同时,要在mapper映射文件中使用
<resultMap>进行特别的处理。
整合过程如下:
- 项目目录结构
- 实体bean
package com.jd.common.bean; /** * Created by shifeifei on 2015/7/26. */ public class User { private int id; private String name; private String phone; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Override public String toString() { return "User{" + "id=" + id + ", name=‘" + name + ‘\‘‘ + ", phone=‘" + phone + ‘\‘‘ + ‘}‘; } }
- mapper接口,对于mapper接口而言,一定要让它收Spring容器管理。
package com.jd.mapper; import com.jd.common.bean.User; import org.springframework.stereotype.Repository;/** * Created by shifeifei on 2015/7/26. */@Repositorypublic interface HelloWorldMapper { public User findUserById(Integer id); }
- Spring的配置文件:spring-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: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/context http://www.springframework.org/schema/context/spring-context.xsd"> <!--引入外部资源文件--> <context:property-placeholder location="classpath:/jdbc.properties"></context:property-placeholder> <!-- 数据源配置,使用DruidDataSource数据库连接池 --> <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- 基本属性 url、user、password --> <property name="url" value="jdbc:mysql://172.23.171.169:3306/activity"/> <property name="username" value="root"/> <property name="password" value="123456"/> <!-- 配置初始化大小、最小、最大 --> <property name="initialSize" value="3"/> <property name="minIdle" value="1"/> <property name="maxActive" value="20"/> <!-- 配置获取连接等待超时的时间 --> <property name="maxWait" value="60000"/> <!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 --> <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"/> <!-- 配置监控统计拦截的filters --> <property name="filters" value="stat"/> </bean> <!-- 配置会话工厂SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!--指定连接池数据源--> <property name="dataSource" ref="dataSource"></property> <!-- 它一般对应我们的实体类所在的包,这个时候会自动取对应包中类名作为包的别名。 多个package之间可以用逗号或者分号等来进行分隔。 --> <property name="typeAliasesPackage" value="com.jd.common.bean"></property> <property name="mapperLocations"> <list> <value>classpath:/com/jd/mapper/HelloWorldMapper.xml</value> </list> </property> </bean> <!-- Spring容器中配置mapper扫描器 --> <bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 指定扫描包的路径,就是mapper接口的路径 --> <property name="basePackage" value="com.jd.mapper"></property> <!-- 配置sqlSessionFactoryBeanName,也就是配置会话工厂 --> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property> </bean> </beans>
- 资源文件:jdbc.properties
#因为是使用的阿里巴巴的连接池,可以不用写mysql的驱动,Druid能够自动的识别各种数据库驱动 flow.datasources.username=root flow.datasources.password=123456 flow.datasources.url=jdbc:mysql://172.23.171.169:3306/activity
- mapper映射文件:HelloWorldMapper.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"> <!-- namespace:SQL映射文件(***Mapper.xml文件)所在的路径 --> <mapper namespace="com.jd.mapper.HelloWorldMapper"> <sql id="COL_SELECT"> <![CDATA[ select * from test ]]> </sql> <select id="findUserById" parameterType="Integer" resultType="User"> <include refid="COL_SELECT"></include> <!--使用<![CDATA[ ]]>符号进行说明,将">"等此类特殊符号不进行解析--> <![CDATA[ where id < #{id} ]]> </select> </mapper>
2. 整合Spring MVC + Velocity + log4j
(1) 导入Spring-MVC依赖包:spring-web-3.2.4.RELEASE和spring-webmvc-3.2.4.RELEASE。
(2) 导入Velocity依赖包:veloctiy-1.5和velocity-tools。
(3) 由于使用IDEA作为开发工具,自己新建web项目中servlet的jar包,所以还要导入servlet-api.jar包。
(4) 导入log4j的依赖包。
- Spring MVC的配置文件: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: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/context http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd"> <!-- 自动扫描该包,受Spring容器管理 --> <context:component-scan base-package="com.jd.controller,com.jd.service,com.jd.mapper" /> <!--配置velocity引擎--> <bean id="velocityConfig" class="org.springframework.web.servlet.view.velocity.VelocityConfigurer"> <!--velocity文件存放的路径--> <property name="resourceLoaderPath" value="/WEB-INF/views/"/> <!--防止velocity页面乱码--> <property name="velocityProperties"> <props> <prop key="input.encoding">UTF-8</prop> <prop key="output.encoding">UTF-8</prop> <prop key="contentType">text/html;charset=UTF-8</prop> </props> </property> </bean> <!--配置velocity视图解析器--> <bean id="viewResolver" class="org.springframework.web.servlet.view.velocity.VelocityViewResolver"> <property name="prefix" value=""/> <property name="suffix" value=".vm"/> <!--velocity页面显示乱码的解决的最重要的一步--> <property name="contentType" value="text/html;charset=UTF-8"/> </bean> </beans>
- web.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_2_5.xsd" version="2.5"> <!--加载Spring配置文件--> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring-config.xml</param-value> </context-param> <!--Web容器启动时加载Spring--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--log4j配置--> <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> <!--配置编码过滤器--> <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> <dispatcher>REQUEST</dispatcher> <dispatcher>FORWARD</dispatcher> </filter-mapping> <!--配置Spring MVC--> <servlet> <servlet-name>spring-mvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!--加载spring-mvc的配置文件--> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/spring-mvc.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> <!--配置druid连接池--> <servlet> <servlet-name>DruidStatView</servlet-name> <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>DruidStatView</servlet-name> <url-pattern>/druid/*</url-pattern> </servlet-mapping> </web-app>
- log4j.properties属性文件
#定义LOG输出级别 log4j.rootLogger=DEBUG,Console #定义日志输出目的地为控制台 log4j.appender.Console=org.apache.log4j.ConsoleAppender #可以灵活地指定日志输出格式,下面一行是指定具体的格式 log4j.appender.Console.layout = org.apache.log4j.PatternLayout #输出所以日志,如果换成DEBUG表示输出DEBUG以上级别日志 log4j.appender.Console.layout.ConversionPattern =[%p] [%d{yyyy-MM-dd HH\:mm\:ss}][%c]%m%n
3. Maven的pom.xml文件
<?xml version="1.0" encoding="UTF-8"?> <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>test-framework</groupId> <artifactId>integrate-framework</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <!-- Spring 依赖包--> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-expression</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>3.2.4.RELEASE</version> </dependency> <!--MyBatis依赖包--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.2</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.0</version> </dependency> <!--Spring MVC依赖--> <dependency> <groupId>servlet-api</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>3.2.4.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>3.2.4.RELEASE</version> </dependency> <!--Velocity依赖--> <dependency> <groupId>velocity</groupId> <artifactId>velocity</artifactId> <version>1.5</version> </dependency> <dependency> <groupId>velocity-tools</groupId> <artifactId>velocity-tools</artifactId> <version>1.2</version> </dependency> <!--MySQL依赖--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.26</version> </dependency> <!--连接池--> <dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>0.2.25</version> </dependency> <!--log4j依赖--> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> </dependencies> <build> <!--产生的构件的文件名,默认值是${artifactId}-${version} <finalName>test-framework-1</finalName>--> <!--指定所有的资源文件的路径,这些资源被包含在最终的打包文件里。--> <resources> <resource> <directory>src/main/resources</directory> <filtering>true</filtering> </resource> </resources> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <configuration> <source>1.6</source> <target>1.6</target> <encoding>utf-8</encoding> </configuration> </plugin> </plugins> </build> </project>
4. 其他各个部分的代码
(1) controller包下的代码
package com.jd.controller; import com.jd.common.bean.User; import com.jd.service.HelloWorldService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; /** * Created by shifeifei on 2015/7/27. */ @Controller public class HelloWorldController { @Autowired private HelloWorldService helloWorldServiceImpl; @RequestMapping( value = "/hello") public String hello(Model model) { User user = helloWorldServiceImpl.getUser(); System.out.println("hello: " + user ); model.addAttribute("user",user); return "index"; } }(2) service包下的代码
package com.jd.service; import com.jd.common.bean.User; /** * Created by shifeifei on 2015/8/1. */ public interface HelloWorldService { public User getUser(); }package com.jd.service; import com.jd.common.bean.User; import com.jd.mapper.HelloWorldMapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; /** * Created by shifeifei on 2015/8/1. */ @Service public class HelloWorldServiceImpl implements HelloWorldService { @Autowired private HelloWorldMapper mapper; @Override public User getUser() { return mapper.findUserById(2); } }(3) mapper包下的代码
package com.jd.mapper; import com.jd.common.bean.User; import org.springframework.stereotype.Repository; /** * Created by shifeifei on 2015/7/26. */ @Repository public interface HelloWorldMapper { public User findUserById(Integer id); }
整合结束,博客有源代码下载,注意我使用的是IDEA开发的,请不要直接把代码导入Eclipse中测试。代码下载链接: http://pan.baidu.com/s/18szAu