Spring+Struts2+mybatis三大框架的整合配置

本文详细介绍了mybatis框架与hibernate框架在数据库持久层的应用,包括环境搭建、配置、实体类设计、DAO层、Service层、Action层的实现方式,并通过对比分析了两者在操作数据库、SQL调优、灵活性及与不同数据库兼容性方面的差异。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

现在主流的项目框架中,数据库持久层有可能不是hibernate,而是mybatis或者ibatis,其实它们都是一样的,下面我来把环境搭建一下:

【导入相关jar包】新建web项目工程mss,Spring+Struts2+mybatis整合,除了Spring和Struts的jar包外(可以在我的资源中下载),我们还需导入mybatis的几个想jar包:

\

三大框架整合后jar包:

\\

【配置web.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
32
33
34
35
36
37
38
39
40
41
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemalocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

    <!-- struts启动配置 -->
    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
        </filter-class>
    </filter>
    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!-- spring启动加载配置 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springConfig/applicationContext-*.xml
        </param-value>
    </context-param>
    <listener>
        <listener-class>
            org.springframework.web.context.ContextLoaderListener
        </listener-class>
    </listener>

    <!-- log4j相关配置 -->
    <context-param>
        <param-name>log4jConfigLocation</param-name>
        <param-value>/WEB-INF/classes/log4j.properties</param-value>
    </context-param>
    <context-param>
        <param-name>log4jRefreshInterval</param-name>
        <param-value>60000</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.util.Log4jConfigListener
        </listener-class>
    </listener>
</web-app>

【Spring公共配置 applicationContext-common.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<?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: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-3.0.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <aop:aspectj-autoproxy proxy-target-class="true" />
    
    <!-- 读取配置文件jdbc.properties -->
    <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
        <property name="location" value="classpath:jdbc.properties"/>
    </bean>
    
    <!--  数据库连接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName">
           <value>${jdbc_driver}</value>
        </property>
        <property name="url">
            <value>${jdbc_url}</value>
        </property>
        <property name="username">
            <value>${jdbc_user}</value>
        </property>
        <property name="password">
            <value>${jdbc_password}</value>
        </property>
        <property name="maxActive" value="100"></property>
        <property name="maxIdle" value="30"></property>
        <property name="maxWait" value="500"></property>
        <property name="defaultAutoCommit" value="true"></property>
    </bean>

    <!-- 事务配置 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 实体映射类-->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="typeAliasesPackage" value="com.lgs.pojo" />
    </bean>

</beans>

数据库配置文件jdbc.properties:
\

【struts2公共配置】

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd"><struts>
    
    <constant name="struts.configuration.xml.reload" value="true"/>
    <constant name="struts.action.extension" value="action,do,webwork" />
    <constant name="struts.custom.i18n.resources" value="messages"></constant>
    <constant name="struts.enable.DynamicMethodInvocation" value="true" />
    <constant name="struts.devMode" value="true" />
    <constant name="struts.multipart.maxSize" value="100971520"></constant>
    <constant name="struts.i18n.encoding" value="UTF-8"></constant>
    <constant name="struts.objectFactory.spring.autoWire" value="name"></constant>
    
    <!-- 将struts2交给spring管理-->
    <constant name="struts.objectFactory" value="spring"></constant>
    
    
    <include file="strutsConfig/struts-user.xml"></include>
</struts>

【创建数据表结构】:项目中我们使用的是mysql数据库,在里面新建了一个user表:

\

【搭建项目结构】:这里我使用了三层架构:Action-->Service-->Dao(实体类)

编写user实体类:

?
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
package com.lgs.pojo;

import java.io.Serializable;

public class User implements Serializable {

    /**
     *
     */
    private static final long serialVersionUID = 1L;

    private String id;
    private String userName;
    private String password;
    private String email;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    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;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

编写我们的dao层UserDao:

?
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
package com.lgs.dao;

import java.util.List;

import com.lgs.pojo.User;



public interface UserDao {
    /**
     * 添加用户
     * @param user
     */
    public void addUser(User user);
    
    /**
     * 列出所有用户
     * @return
     */
    public List<User> queryUsers();
    
    /**
     * 删除用户
     * @param id
     */
    public void delUser(String id);
}

使用mybatis,我们得配置xml文件,将实体类User与表user映射,也将UserDao中的方法进行映射实现,这样我们不需要写UserDaoImpl,因为对数据库的操作也在这个xml中进行:UserDao.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
32
33
34
35
36
37
38
39
40
<?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.lgs.dao.UserDao">

    <!-- User实体类、User表映射,注意实体类User和表名应该一致,字段下面可配置 -->
    <resultMap id="UserMap" type="com.lgs.pojo.User">
        <result property="id" column="ID" />
        <result property="userName" column="USERNAME" />
        <result property="password" column="PASSWORD" />
        <result property="email" column="EMAIL" />
    </resultMap>

    <!-- 将UserDao中的方法进行配置,id=方法名称,parameterType=参数类型,resultMap返回的结果,当用户使用UserDao中的方法时,mybaties自己会找相应配置文件中的对数据库的操作 -->
    <insert id="addUser" parameterType="User">
        INSERT INTO USER(
        ID,
        USERNAME,
        PASSWORD,
        EMAIL
        )
        VALUES (
        #{id},
        #{userName},
        #{password},
        #{email}
        )
    </insert>
    
    <!-- 返回一个上面的 resultMap实例,这里的resultMap要与上面的配置的resultMap中的id一致-->
    <select id="queryUsers" resultMap="UserMap" >
        SELECT * FROM USER
    </select>
    
    <!-- 删除信息 -->
    <delete id="delUser" parameterType="string">
        DELETE FROM USER WHERE ID = #{id}
    </delete>
    
</mapper>

编写我们的Service和ServiceImpl类,操作Dao层:UserService、UserServiceImpl

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package com.lgs.service;

import java.util.List;

import com.lgs.pojo.User;


public interface UserService {
    /**
     * 添加用户
     * @param user
     */
    public void addUser(User user);
    
    /**
     * 列出所有的用户
     * @return
     */
    public List<User> queryUsers();
    
    /**
     * 删除用户
     * @param id
     */
    public void delUser(String id);
}

?
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
package com.lgs.serviceimpl;

import java.util.List;

import com.lgs.dao.UserDao;
import com.lgs.pojo.User;
import com.lgs.service.UserService;



public class UserServiceImpl implements UserService{
//注入UserDao到service层  
 private UserDao userDao;
    
    public UserDao getUserDao() {
        return userDao;
    }

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    /**
     * 添加用户
     */
    public void addUser(User user) {
        userDao.addUser(user);
    }

    /**
     * 列出所有用户
     */
    public List<User> queryUsers() {
        List<User> userList = userDao.queryUsers();
        return userList;
    }

    /**
     * 删除用户
     */
    public void delUser(String id) {
        userDao.delUser(id);
    }

    

}

编写Action,操作Service,UserAction

?
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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package com.lgs.action;

import java.util.List;
import java.util.Random;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;


import org.apache.log4j.Logger;
import org.apache.struts2.ServletActionContext;


import com.lgs.pojo.User;
import com.lgs.service.UserService;
import com.opensymphony.xwork2.ActionSupport;

/**
 * 用户操作Action
 * @author dell
 *
 */
public class UserAction extends ActionSupport {
    private static final long serialVersionUID = 1L;
    private static Logger logger = Logger.getLogger(UserAction.class);
    //注入service到action层
    public UserService userService;

    public UserService getUserService() {
        return userService;
    }

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    private String id;
    private String userName;
    private String password;
    private String email;

    /**
     * 添加用户信息
     *
     * @return
     */
    public String addUser() {
        User user = new User();
        try {
            String iid =new Random().nextInt(100)+"";
            user.setId(iid);
            user.setUsername(userName);
            user.setPassword(password);
            user.setEmail(email);
            userService.addUser(user);
        } catch (Exception e) {
            logger.error("exception in add user", e);
            return ERROR;
        }
        return SUCCESS;
    }

    /**
     * 从数据库中获得所有的用户信息
     *
     * @return
     */
    public String queryUsers() {
        try {
            List<User> userList = userService.queryUsers();
            for (int i = 0; i < userList.size(); i++) {
                System.out.println(userList.get(i).getId());
            }
            HttpServletRequest request = ServletActionContext.getRequest();
            request.setAttribute("list", userList);
            return "list";
        } catch (Exception e) {
            logger.error("Exception in queryUsers", e);
            return ERROR;
        }
    }

    /**
     * 删除用户信息
     *
     * @return
     */
    public String delUser() {
        try {
            userService.delUser(id);
        } catch (Exception e) {
            logger.error("Exception in delUser", e);
            return ERROR;
        }
        return SUCCESS;
    }

    public void setId(String id) {
        this.id = id;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public void setEmail(String email) {
        this.email = email;
    }

}

整体代码结构:

其中,跟mybatis相关最大的一个就是UserDao.xml文件了,我们的所有对数据库的操作和方法都可以在里面进行相应的配置和参数设置,只要将相应的名称设置和匹配好,mybatis就能够自动调用
【配置我们自己的spring xml文件:applicationContext-user.xml】,其中mybatis和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
<?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: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-3.0.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop-3.0.xsd">

    <!-- 操作User类的spring配置文件 -->
    <!-- 配置User中的Dao类,使mybaties能够配置User与数据库打交道 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.lgs.dao" /><!-- 必须保证可以同时扫描UserDao类和UserDao.xml文件 -->
    </bean>
    <!-- 配置userService,注意 userDao名称要与UserServiceImpl中的UserDao属性名称一样-->
    <bean id="userService" class="com.lgs.serviceimpl.UserServiceImpl">
        <property name="userDao" ref="userDao" />
    </bean>
    <!-- 配置Action,注意userService名称要与UserAction中的UserService属性名称一样 -->
    <bean id="userAction" class="com.lgs.action.UserAction">
        <property name="userService" ref="userService" />
    </bean>

</beans>



【配置自己的Struts xml:struts-user.xml】

?
1
2
3
4
5
6
7
8
9
10
11
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
    <package name="user" extends="struts-default" namespace="/">
          <action name="userAction" class="com.lgs.action.UserAction">
              <result name="success">success.jsp</result>
              <result name="error">error.jsp</result>
              <result name="list">UserList.jsp</result>
          </action>
          
    </package>
</struts>

【项目中我们用到了log4j,配置log4j.properties】

\

首页index.jsp:

<pre name="code" class="html"><%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->
  </head>
  
  <body>
    <a href="userAction!queryUsers.do">查询用户</a>
    <a href="${pageContext.request.contextPath}/add.jsp">添加用户</a>
  </body>
</html>

 

项目的基础配置基本完成,编写我们的视图层,上面Action中我们跳转到了UserList.jsp,编写我们的jsp显示页面:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<%@ page language="java" contentType="text/html; charset=UTF-8"    pageEncoding="UTF-8"%>    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html><head><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>用户列表</title></head><body><table border="1">    <c:forEach items="${list}" var="s">        <tr>            <td><c:out value="${s.userName}"></c:out></td>            <td><c:out value="${s.password}"></c:out></td>            <td><c:out value="${s.email}"></c:out></td>            <td><a href="userAction!delUser.do?id=${s.id}">删除记录</a></td>        </tr><br>    </c:forEach></table></body></html>

添加用户页面add.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'add.jsp' starting page</title>
    
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  
  <body>
   <form action="userAction!addUser.do" method="post">
   
   用户名:<input type="text" name="userName"/><br/>
   密码:<input type="text" name="password"/><br/>
   邮箱:<input type="text" name="email"/><br/>
   <input type="submit" value="提交">
   
   </form>
  </body>
</html>


好了,基础环境基本上已经搭建完成,将项目部署到Tomcat上,启动Tom家的猫,如果没报错,说明我们项目搭建成功,输入下面地址:http://localhost:8080/ssm/userAction!queryUsers.do,如果数据库中没有数据,则加入相应数据,如果显示出相应的数据库记录,说明我们项目搭建成功!
\

完整项目可在我的资源库中下载:http://download.youkuaiyun.com/detail/harderxin/7308169

相比较hibernate来说:

hibernate:要编写实体类和实体类相映射数据库表的xml文件,然后操作数据库使用hibernate封装的java类接口

mybatis:编写实体类、实体类相映射数据库表的xml文件、对数据方法操作xml文件,其对数据库的操作也在xml文件中定义,基本上使用的是纯sql语句

?
1
mybatis是半自动的,hibernate是全自动的,就是说mybatis可以配置sql语句,对于sql调优来说是比较好的,hibernate会自动生成所有的sql语句,调优不方便,hibernate用起来难度要大于mybatis。mybatis的主要思想是sql Mapping,而hibernate是OR Mapping,mybatis应用到项目中会比较直观一点,能直接看到sql,而hibernate是通过操作对象操作数据,可以很灵活的运用于不同的数据库之间

要比较hibernate与mybatis的区别,大家还可以参考博客:http://blog.youkuaiyun.com/firejuly/article/details/8190229

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值