SpringMVC与MyBatis的整合

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010281503/article/details/77899166

SpringMVC与MyBatis的整合

1、文件结构图

所有需要的JAR包都引入以后,首先进行SpringMyBatis的整合,先看一个项目结构图:

                     

1.1、建立JDBC属性文件

jdbc.properities

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://10.108.171.181:3306/mybatis?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=www1234
initialSize=0   
maxIdle=20  
minIdle=1 
1.2、log4j日志系统(log4j.properities)

# log4j configuration used during build and unit tests
log4j.rootLogger=INFO,stdout
log4j.threshhold=ALL
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ISO8601} %-5p %c{2} (%F:%M(%L)) - %m%n
2、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" 
	xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" 
	id="WebApp_ID" version="2.5">

	<display-name>Develop Example</display-name>
	<description>JSP 2.0 Tech Book's Examples</description>
 	<icon>
		<small-icon>/images/small.gif</small-icon>
		<large-icon>/images/large.gif</large-icon>
	</icon> 
	<!-- 首页 --> 
	<welcome-file-list>
    	<welcome-file>/views/main.html</welcome-file>
    	<welcome-file>main.htm</welcome-file>
    	<welcome-file>main.jsp</welcome-file>
    </welcome-file-list>
    <!-- 错误页 -->  
    <error-page>  
        <error-code>404</error-code>  
        <location>/views/error.html</location>  
    </error-page>  
    <error-page>  
        <error-code>500</error-code>  
        <location>/rest/page/500</location>  
    </error-page>
 	<!-- 配置Spring配置文件路径 -->
 	<context-param>  
      	<param-name>contextConfigLocation</param-name>  
      	<param-value>/WEB-INF/applicationContext.xml</param-value>  
 	</context-param>
 	 <!-- 配置Spring上下文监听器 -->
 	<listener>  
 		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
	</listener>
 	
 	<!-- 配置log4j配置文件路径 -->
 	<context-param>  
        <param-name>log4jConfigLocation</param-name>  
        <param-value>/WEB-INF/mybatis/log4j.properties</param-value>  
    </context-param>
    <!-- 配置Log4j监听器 -->
    <listener>  
        <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>  
    </listener>
 	<!-- Spring MVC 核心控制器 DispatcherServlet 配置 --> 
   	<servlet>
   		<servlet-name>index</servlet-name>
   		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
   		<init-param>  
        	<param-name>contextConfigLocation</param-name>  
        	<param-value>/WEB-INF/index-servlet.xml</param-value>  
   		 </init-param>
   		<load-on-startup>1</load-on-startup>  
   	</servlet>
   	<servlet-mapping>  
        <servlet-name>index</servlet-name>  
        <url-pattern>/</url-pattern>  
    </servlet-mapping> 
      
    <!-- 解决post乱码问题的过滤器 -->
  	<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>
3、applicationContext.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:jdbc="http://www.springframework.org/schema/jdbc"
		xmlns:jee="http://www.springframework.org/schema/jee"
		xmlns:aop="http://www.springframework.org/schema/aop"
		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://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop.xsd">
 
   		<!-- 加载数据库连接的资源文件 -->
		<context:property-placeholder location="/WEB-INF/mybatis/jdbc.properties"/>
 		<!-- 引入配置文件 -->  
    	<bean id="propertyConfigurer"  
        	class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">  
        	<property name="location" value="/WEB-INF/mybatis/jdbc.properties" />  
    	</bean> 
 		<!-- 配置数据源 -->
    	<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
         	<property name="driverClassName" value="${jdbc.driver}"></property>
         	<property name="url" value="${jdbc.url}"></property>
         	<property name="username" value="${jdbc.username}"></property>
         	<property name="password" value="${jdbc.password}"></property>
         	<!-- 配置初始化大小、最小、最大 --> 
         	<property name="initialSize" value="${initialSize}"></property>  
        	<property name="minIdle" value="${minIdle}"/> 
        	<!-- 连接池最大空闲 -->  
        	<property name="maxIdle" value="${maxIdle}"></property>   
       	
     	</bean>
 
		<!-- 配置sqlSessionFactory -->
		<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
   			 <!-- 数据库连接池 -->
    		 <property name="dataSource" ref="dataSource"/>
   			 <!-- 加载Mybatis全局配置文件 -->
    		 <property name="configLocation" value="/WEB-INF/mybatis/mybatis-config.xml"/>
    		 <!-- 自动扫描mapping.xml文件 -->
    		 <property name="mapperLocations" value="/WEB-INF/mybatis/mappers/*.xml" />
		</bean>
		
    	<!-- 配置mybatis mapper接口 -->
		<bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
  			<property name="mapperInterface" value="com.dao.UserMapper" />
 			<property name="sqlSessionFactory" ref="sqlSessionFactory" />
	    </bean>

</beans> 

4、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>  
    <!-- 配置别名  -->
    <typeAliases>  
        <typeAlias type="com.dao.User" alias="User" />  
    </typeAliases>   
</configuration>

5、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.dao.UserMapper">
    <select id="getUser" parameterType="int" resultType="User">
        select * from users where id = #{id}
    </select>
    <insert id="insert" flushCache="true" parameterType="User">
	    insert into users (id, name, age) values (
	    	#{id}, #{name}, #{age}
	    )
	</insert>
	<!-- 对应userDao中的updateUser方法 -->
   <update id="update" parameterType="User">
           update users set name = #{name}, age = #{age} where id = #{id};
   </update>
    
   <!-- 对应userDao中的deleteUser 方法 --> 
   <delete id="delete" parameterType="int">
           delete from users where id = #{id};
   </delete>
</mapper>
6、index-servet配置文件
<?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:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    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">  
     <!-- 自动扫描的包名 -->  
    <context:component-scan base-package="com.controller,com.dao" />
    <!-- 默认的注解映射的支持 -->  
    <mvc:annotation-driven />  
       
    <!-- 视图解释类 -->  
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
        <property name="prefix" value="/views/"/>  
        <property name="suffix" value=".html"/><!--可为空,方便实现自已的依据扩展名来选择视图解释类的逻辑  -->  
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />  
    </bean>  
             
    <mvc:resources mapping="/images/**" location="/images/" cache-period="31556926"/>  
    <mvc:resources mapping="/js/**" location="/js/" cache-period="31556926"/>  
    <mvc:resources mapping="/css/**" location="/css/" cache-period="31556926"/>  
    <mvc:resources mapping="/views/**" location="/views/" cache-period="31556926"/>
    
</beans>

7、UserMapper.java

public interface UserMapper {
	
	public User getUser(int id);
	
	public void insert(User user);
	
	public void update(User user);
	
	public void delete(int id);
}

user.java

public class User {
    private int id;
    private String name;
    private int age;

    private int test;
    public User(int id, String name, int age) {
		super();
		this.id = id;
		this.name = name;
		this.age = age;
	}

	public User() {
		super();
		// TODO Auto-generated constructor stub
	}
	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 int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
	}

	public int getTest() {
		return test;
	}

	public void setTest(int test) {
		this.test = test;
	}
    
}


8、UserService.java

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

@Service
public class UserService{

	@Autowired
	private UserMapper userMapper;

	public void setUserMapper(UserMapper userMapper) {
	  this.userMapper = userMapper;
	}
	
	public User doGetUser(int id) {
	  return this.userMapper.getUser(id);
	}
	public void doInsertUser(User user) {
		  this.userMapper.insert(user);
	}
	public void doUpdateUser(User user) {
		  this.userMapper.update(user);
	}
	public void doDeleteUser(int id) {
		  this.userMapper.delete(id);
	}
}

9、IndexController.java

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.dao.User;
import com.dao.UserService;

@Controller
public class IndexController {
	@Autowired
	private UserService userService;
	
	private static Logger logger = Logger.getLogger(IndexController.class);
	
	@RequestMapping({"/index","/"})
	public String index() throws Exception{
		 
	    User user1 = userService.doGetUser(7);
	    logger.info(user1.getName());
		return "main";
	}
}

10、测试显示

访问:http://localhost:8080/UI/index


从以上的显示中可以发现,从数据库中读取了数据。













猜你喜欢

转载自blog.csdn.net/u010281503/article/details/77899166