Mybatis+Spring整合创建Web项目

来源:互联网 发布:mac装windows iso 编辑:程序博客网 时间:2024/05/20 23:38

出处http://blog.csdn.net/evankaka

        本文要实现使用Mybatis+Spring+MySQL实现一个Web项目的整目。在Spring中配置数据源和Mybatis的SqlSessionFactory,然后在Web中的JSP中取得Spring中的bean。通过这个bean来操作Mysql中的表。网上看了好多人有写,但是要么是图没表示清楚,要么是代码没贴完。本文是一个完整的教程,照着做你也可以自己整合!

使用的版本:Mybatis-3.2.8

                        Spring3.2.9

                         Mysql5.6

开发环境:    Eclipse  Java EE Kepler+Win7

本文工程免费下载

一、创建Web项目并导入包

Eclipse中创建一个Web项目,导入如下的包:


这里一定要注意不能少mybatis-spring-1.2.2.jar这个包,这个包是用来联系Spring和Mybatis的,很重要!!

整个工程目录如下:


二、创建库表映射类并配置MyBatis

1、首先在数据库中创建一张表 t_user

[sql] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. use test;  
  2. DROP TABLE IF EXISTS t_user;  
  3. create table t_user  
  4. (  
  5.  userId  int primary key auto_increment,  
  6.  userName VARCHAR(50) not null,  
  7.  userAge int not null  
  8. );  
然后插入4条数据:

[sql] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. insert into t_user values(1,'小王',10);  
  2. insert into t_user values(2,'红红',11);  
  3. insert into t_user values(3,'明明',12);  
  4. insert into t_user values(4,'天天',13);  
查看下结果:


2、表创建好之后便创建其映射类User,位于包com.mucfc.model中

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package com.mucfc.model;  
  2. /** 
  3.  * User映射类 
  4.  * @author linbingwen 
  5.  * @time 2015.5.15 
  6.  */  
  7. public class User {  
  8.     private Integer userId;  
  9.     private String userName;  
  10.     private int userAge;  
  11.     public Integer getUserId() {  
  12.         return userId;  
  13.     }  
  14.     public void setUserId(Integer userId) {  
  15.         this.userId = userId;  
  16.     }  
  17.     public String getUserName() {  
  18.         return userName;  
  19.     }  
  20.     public void setUserName(String userName) {  
  21.         this.userName = userName;  
  22.     }  
  23.     public int getUserAge() {  
  24.         return userAge;  
  25.     }  
  26.     public void setUserAge(int userAge) {  
  27.         this.userAge = userAge;  
  28.     }  
  29.     @Override  
  30.     public String toString() {  
  31.         return "User [userId=" + userId + ", userName=" + userName  
  32.                 + ", userAge=" + userAge + "]";  
  33.     }  
  34.   
  35. }  

2、映射类创建好之后便创建MyBatis映射文件(即Mapper文件),位于和src同级的conf的mapper包中,文件内容如下:

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"  
  3. "http://mybatis.org/dtd/mybatis-3-mapper.dtd">  
  4. <mapper namespace="com.mucfc.mapper.UserMapper">    
  5.     <!--  查询单条记录  -->    
  6.     <select id="selectUserById" parameterType="int" resultType="User">    
  7.        select * from t_user where userId = #{userId}    
  8.     </select>    
  9. </mapper>  
3、创建映射UserMapper类如下,位于包com.mucfc.mapper中

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package com.mucfc.mapper;  
  2.   
  3. import com.mucfc.model.User;  
  4. /** 
  5.  * Mapper映射类 
  6.  * @author linbingwen 
  7.  * @time 2015.5.15 
  8.  */  
  9. public interface UserMapper {  
  10.     public User selectUserById(int userId);  
  11.   
  12. }  
4、创建操作数据的DAO层

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package com.mucfc.dao;  
  2.   
  3. import com.mucfc.model.User;  
  4. /** 
  5.  * DAO接口层 
  6.  * @author linbingwen 
  7.  * @time 2015.5.15 
  8.  */  
  9. public interface UserDao {  
  10.     /** 
  11.      * 根据用户ID查询用户信息 
  12.      * @param id 
  13.      * @return 
  14.      */  
  15.     public User findUserById(int id);  
  16. }  
然后是对应的实现层

[java] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. package com.mucfc.dao;  
  2.   
  3. import org.springframework.beans.factory.annotation.Autowired;  
  4. import org.springframework.stereotype.Component;  
  5. import  com.mucfc.mapper.UserMapper;  
  6. import com.mucfc.model.User;  
  7. /** 
  8.  * DAO实现层 
  9.  * @author linbingwen 
  10.  * @time 2015.5.15 
  11.  */  
  12. @Component  
  13. public class UserDaoImpl implements UserDao{  
  14.     @Autowired  
  15.     private UserMapper userMapper;  
  16.     @Override  
  17.     public User findUserById(int id) {  
  18.         User user = userMapper.selectUserById(id);  
  19.          return user;   
  20.     }  
  21.       
  22. }  

5、在conf里配置Mybatis的配置文件:

MyBatisConf.xmll放在conf里,注意路径

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  
  3. "http://mybatis.org/dtd/mybatis-3-config.dtd">  
  4. <configuration>  
  5.    <!-- 配置映射类的别名 -->  
  6.     <typeAliases>  
  7.       <typeAlias alias="User" type="com.mucfc.model.User"/>   
  8.    </typeAliases>    
  9.    <!-- 配置Mapper文件的路径 -->  
  10.    <mappers>  
  11.        <mapper resource="mapper/UserMapper.xml"/>  
  12.    </mappers>  
  13. </configuration>  

如果不与Spring进行整合的话,此配置文件还需要配置数据源信息,与Spring整合之后数据源就配置在Spring配置文件中,只需要配置映射文件的路径就可以了。

三、配置Spring

1、在WEB-INF里配置Spring的配置文件:

SpringConf.xml放在WEB-INF里,注意路径

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <beans xmlns="http://www.springframework.org/schema/beans"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  4.     xmlns:aop="http://www.springframework.org/schema/aop"  
  5.     xsi:schemaLocation="    
  6.            http://www.springframework.org/schema/beans    
  7.            http://www.springframework.org/schema/beans/spring-beans-3.0.xsd    
  8.            http://www.springframework.org/schema/aop    
  9.            http://www.springframework.org/schema/aop/spring-aop-3.0.xsd  
  10.            http://www.springframework.org/schema/context    
  11.            http://www.springframework.org/schema/context/spring-context-3.0.xsd">  
  12.     <!-- 配置数据源 -->  
  13.     <bean id="dataSource"  
  14.         class="org.springframework.jdbc.datasource.DriverManagerDataSource">  
  15.         <property name="driverClassName" value="com.mysql.jdbc.Driver" />  
  16.         <property name="url" value="jdbc:mysql://localhost:3306/test" />  
  17.         <property name="username" value="root" />  
  18.         <property name="password" value="christmas258@" />  
  19.     </bean>  
  20.   
  21.   
  22.     <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">  
  23.         <property name="dataSource" ref="dataSource" />  
  24.     <!--      <property name="mapperLocations" value="conf/mapper/UserMapper.xml"/>  -->  
  25.         <property name="configLocation" value="conf/MyBatisConf.xml" />  
  26.         <!-- <property name="typeAliasesPackage" value="com.tiantian.ckeditor.model"   
  27.             /> -->  
  28.     </bean>  
  29.   
  30.       <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">    
  31.        <property name="mapperInterface"    
  32.            value="com.mucfc.mapper.UserMapper" />    
  33.        <property name="sqlSessionFactory" ref="sqlSessionFactory" />    
  34.     </bean>   
  35.     <!-- 自动扫描注解的bean -->  
  36.     <context:component-scan base-package="com.mucfc.dao" />  
  37.   
  38. </beans>  

2、web.xml中启动Spring

web.xml放在WEB-INF里

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"  
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
  4.     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee   
  5.     http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">  
  6.     <!-- 配置初始打开的页面 -->  
  7.     <welcome-file-list>  
  8.         <welcome-file>index.html</welcome-file>  
  9.         <welcome-file>index.htm</welcome-file>  
  10.         <welcome-file>index.jsp</welcome-file>  
  11.     </welcome-file-list>  
  12.       
  13.     <!-- Spring 容器加载 -->  
  14.     <listener>  
  15.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>  
  16.     </listener>  
  17.     <context-param>  
  18.         <param-name>contextConfigLocation</param-name>  
  19.         <param-value>/WEB-INF/SpringConf.xml</param-value>  
  20.     </context-param>  
  21.   
  22. </web-app>  

3、读取bean,进行查找

在index.jsp中设置如下:

index.jsp放置在WebContent中

[html] view plain copy
 在CODE上查看代码片派生到我的代码片
  1. <%@ page import="com.mucfc.dao.UserDao"%>  
  2. <%@page import="org.springframework.web.context.WebApplicationContext"%>  
  3. <%@page  
  4.     import="org.springframework.web.context.support.WebApplicationContextUtils"%>  
  5. <%@ page language="java" contentType="text/html" pageEncoding="UTF-8"%>  
  6.   
  7. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">  
  8. <html>  
  9. <head>  
  10. <title>Insert title here</title>  
  11. </head>  
  12. <body>  
  13.     <center>  
  14.         欢迎<br/>  
  15.         <%  
  16.             WebApplicationContext wac = WebApplicationContextUtils  
  17.                     .getWebApplicationContext(this.getServletContext());  
  18.             UserDao userDao = (UserDao) wac.getBean("userDaoImpl");  
  19.         %>  
  20.         <%=userDao.findUserById(1)%><br />  
  21.         <%=userDao.findUserById(2)%><br />  
  22.         <%=userDao.findUserById(3)%><br />  
  23.         <%=userDao.findUserById(4)%><br />  
  24.     </center>  
  25. </body>  
  26. </html>  

四、运行

1、以run on server运行

2、浏览器输入:http://localhost:8080/MybatisLearningChapter5/

结果如下:



0 0
原创粉丝点击