自学笔记--Maven项目的Spring+SpringMVC+MyBatis整合(亲测可用)

  对于一个初学者来说,在整合SSM(Spring+SpringMVC+MyBatis)框架时可能会出现各种问题,博主在经过数次的踩坑之后,总算将三大框架整合到了一起,下面就通过实现对数据库表的查询功能来看看是怎么整合的吧
  

  • 首先我们来看一下在项目中的所需要的配置文件
    mapper.xml—>MyBatis框架映射器映射文件
    spring.xml—>spring框架的配置文件
    springmvc.xml—>springmvc框架的配置文件
    conf.xml—>MyBatis框架的全局配置文件
    db.properties—>属性文件
    pom.xml—>Maven项目的配置文件
    web.xml—>web项目的配置文件

    在Maven项目中,配置文件统一存放于src/main/resources路径下

    >>.mapper.xml中配置的内容
       该文件负责将java对象与数据库表产生映射关系,如果采用动态代理方式的话,将该文件与接口放在一起,具体的配置如下:

<!-- namespace是接口的全路径,动态代理方式是基于接口的 -->
<mapper namespace="com.qhit.dao.EmployeeDao">

<!-- 为了实现自定义类型转换器 -->
    <resultMap type="employeepojos" id="pojosresult">
        <id property="id" column="id" />
        <result property="name" column="name" />
        <result property="sex" column="sex" javaType="String" jdbcType="INTEGER" />
        <result property="age" column="age" />
        <result property="address" column="address" />
        <result property="salary" column="salary" />
    </resultMap>

    <!-- 查询全部数据(测试用) -->
    <select id="selectAll" resultMap="pojosresult">
        select * from employee
    </select>
</mapper>

dao层(数据访问层)对应的内容

public interface EmployeeDao {

    // 查询全部数据
    List<EmployeePOJOs> selectAll();

}

>>.conf.xml中配置的内容
该文件是MyBatis的全局配置文件,具体的配置信息如下:

<configuration>
    <!-- 批量设置别名 -->
    <typeAliases>
        <package name="com.qhit.pojos" />
    </typeAliases>

    <!-- 配置自定义类型转换器 -->
    <typeHandlers>
        <typeHandler handler="com.qhit.converter.SexConverter"
            jdbcType="INTEGER" javaType="String" />
    </typeHandlers>

</configuration>

>>.pom.xml文件中配置的内容
简单来说.该文件是Maven用来管理项目中jar包的配置文件,具体配置如下:

  jar包配置信息的话就不贴了,小伙伴们可以根据以下jar包名称到maven仓库查找相应的jar包配置信息,如下所示:
这里写图片描述

  重点来看一下在pom.xml文件中的这条配置信息,可以防止配置文件加载不到的情况,具体配置信息如下:

<build>
        <finalName>mybatis</finalName>
        <resources>
            <resource>
                <directory>src/main/java</directory>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>
</build>

>>.web.xml文件中配置的内容

    <!-- Spring配置信息,加载Spring的配置文件 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>

    <!-- Spring配置信息,监听器的配置 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- SpringMVC的前端控制器DispatcherServlet -->
    <servlet>
        <servlet-name>springDispatcherServlet</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>springDispatcherServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <!-- 解决前后端传值时出现的乱码问题 -->
    <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>
        <servlet-name>springDispatcherServlet</servlet-name>
    </filter-mapping>

>>.db.properties文件中配置的内容

driver=oracle.jdbc.driver.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:orcl
name=数据库登录名
pass=数据库登录密码

>>.spring.xml文件中配置的内容

<!-- 加载属性文件 -->
    <context:property-placeholder location="classpath:db.properties" />

    <!-- 配置数据源 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"
        p:driverClass="${driver}" p:jdbcUrl="${url}" p:user="${name}"
        p:password="${pass}" p:maxIdleTime="1000" p:maxPoolSize="30"
        p:minPoolSize="5" p:autoCommitOnClose="false"></bean>

    <!-- MyBatis创建会话工厂 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
        p:dataSource-ref="dataSource" p:mapperLocations="classpath:com/qhit/dao/employeeMapper.xml"
        p:configLocation="classpath:conf.xml"></bean>

    <!-- MyBatis动态代理 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"
        p:basePackage="com.qhit.dao" p:sqlSessionFactoryBeanName="sqlSessionFactory"></bean>

    <!-- 注解式事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
        p:dataSource-ref="dataSource"></bean>

    <!-- 开启注解 -->
    <tx:annotation-driven transaction-manager="transactionManager" />

    <!-- 自动扫描包 -->
    <context:component-scan base-package="com.qhit.service.impl,com.qhit.controller" />

>>.springmvc.xml文件中配置的内容

 <!--            
     (1)自动注册DefaultAnootationHandlerMapping,AnotationMethodHandlerAdapter           
     (2)提供一些列:数据绑定,数字和日期的format @NumberFormat, @DateTimeFormat, xml,json默认读写支持  
      -->
    <mvc:annotation-driven />

    <!-- 加载静态资源 -->
    <mvc:default-servlet-handler />

    <!-- 自动扫描包 -->
    <context:component-scan base-package="com.qhit.service.impl,com.qhit.controller" />

    <!-- 视图解析器 -->
    <bean
        class="org.springframework.web.servlet.view.InternalResourceViewResolver" />

service层(服务层)测试代码

@Service
public class EmployeeServiceImpl implements EmployeeService {

    @Autowired
    private EmployeeDao dao;

    /*
     * @author Virus
     * 
     * @description 查询全部员工信息
     */
    @Override
    public List<EmployeePOJOs> selectAll() {
        // TODO Auto-generated method stub
        return this.dao.selectAll();
    }
}

controller层(控制层)测试代码

@Controller
@RequestMapping("/employee")
public class EmployeeController {

    @Autowired
    private EmployeeServiceImpl service;
    private ModelAndView ms;

    // 获取全部信息
    @RequestMapping("/all")
    public ModelAndView allInfo() {
        System.out.println("进来了......");
        ms = new ModelAndView();
        ms.addObject("allEmployee", this.service.selectAll());
        ms.setViewName("forward:/index.jsp");
        return ms;
    }
}

JSP页面测试代码

  • getinfo.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<jsp:forward page="employee/all" />
</body>
</html>
  • index.jsp
<%@ 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>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
<style type="text/css">
th {
    text-align: center;
}
</style>
</head>
<body>
    <table border="1">
        <tr>
            <th>编号</th>
            <th>姓名</th>
            <th>性别</th>
            <th>年龄</th>
            <th>家庭住址</th>
            <th>薪资</th>
        </tr>
        <c:forEach items="${allEmployee}" var="all">
            <tr>
                <th>${all.id }</th>
                <th>${all.name }</th>
                <th>${all.sex }</th>
                <th>${all.age }</th>
                <th>${all.address }</th>
                <th>${all.salary }</th>
            </tr>
        </c:forEach>
    </table>
</body>
</html>
  • 查询结果
    这里写图片描述

Ending……

本文还存在有很多不足之处,希望小伙伴们可以多多指教 ^_^

革命尚未成功,同志仍需努力啊!!!

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值