mybatis学习(十一)——springmvc++spring+mybatis整合

做任何一个项目都以一个需求,这里先定义一下需求:利用三大框架查询酒店列表。

一、搭建开发环境

1、创建一个web项目

mybatis学习(十一)——springmvc++spring+mybatis整合

我这里用的是 jdk1.8+tomact7.0

2、创建hotel表

CREATE TABLE `hotel` (
`id` int(11) NOT NULL,
`hotel_name` varchar(20) NOT NULL,
`hotel_address` varchar(20) DEFAULT NULL,
`city_code` int(3) DEFAULT NULL,
`price` int(11) NOT NULL,
`creat_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
`update_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

添加一些数据

mybatis学习(十一)——springmvc++spring+mybatis整合

3、添加Springmvc+Spring+mybatis+sql的jar包,新建一个lib目录

mybatis学习(十一)——springmvc++spring+mybatis整合

二、编写配置文件

主要有以下配置文件web.xml,Springmvc的配置文件,mybatis的配置文件,数据源配置文件

这里没使用maven,不然还有pom.xml文件

1、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_3_0.xsd"
version="3.0">
<!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/config/root-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener> <!-- spring mvc -->
<servlet>
<!--前端控制器配置 -->
<servlet-name>ssm</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<!-- springmvc配置文件地址 -->
<param-value>classpath:config/springmvc-context.xml</param-value>
</init-param>
<!-- 启动优先级配置 -->
<load-on-startup>1</load-on-startup>
<async-supported>true</async-supported>
</servlet>
<servlet-mapping>
<servlet-name>ssm</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

2、springmvc-context.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:task="http://www.springframework.org/schema/task"
xmlns:jee="http://www.springframework.org/schema/jee" xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd">
<!--扫描controller组件 -->
<context:component-scan base-package="com.pjf.ssm.controller" />
<!-- 视图解析器配置 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver" />
<!-- 控制器映射器控制器适配器配置 -->
<mvc:annotation-driven></mvc:annotation-driven>
</beans>

3、mybatis-context.xml

因为是和spring的结合,这里大部分的配置都省略了,在Spring配置文件中配置。

<?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> <!-- 配置mapper 使用spring和mybatis的整合包进行扫描,这里不需要配置 必须遵循mapper.xml文件和mapper.java同名 --> <!-- 全局的setting配置 比如二级缓存的时候这里就需要配置 --> <!-- 别名的配置 -->
<typeAliases>
<package name="com.tuniu.ssm.po" />
</typeAliases> </configuration>

4、db.properties配置

在Spring配置文件之前,必须先要配置数据源

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/spring_mybatis
jdbc.name=root
jdbc.password=pjf520

5、spring配置文件 root-context.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:task="http://www.springframework.org/schema/task"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jee="http://www.springframework.org/schema/jee"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-4.3.xsd"> <!-- 配置组件扫描器 -->
<context:component-scan base-package="com.pjf.ssm.service"></context:component-scan> <context:property-placeholder location="classpath:db.properties" /> <!-- 配置数据源 dbcp -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.name}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="30" />
<property name="maxIdle" value="5" />
</bean> <!-- 配置sqlSessionFactory
dataSource 数据源配置
configLocation mybatis配置文件地址
-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:config/mybatis-context.xml"></property>
</bean> <!-- 配置mapper扫描器
basePackage mapper接口和mapper.xml文件的类全名
sqlSessionFactoryBeanName sqlsession工厂
-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- s扫描包的路径,如果有多个,中间用逗号隔开 -->
<property name="basePackage" value="com.pjf.ssm.dao"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>
</bean> <!-- 事物管理器 对mybatis操作数据库的事物控制,spring使用jdbc的事物控制 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源的配置 dataSource在orm-context.xml中配置了 -->
<property name="dataSource" ref="dataSource"></property>
</bean> <!-- 配置通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="query*" propagation="REQUIRED" />
<tx:method name="add" propagation="REQUIRED" />
<tx:method name="update" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
<tx:method name="set*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice> <!-- 配置aop -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.pjf.ssm.service.impl.*.*(..))" />
</aop:config> </beans>

三、编写代码

mybatis学习(十一)——springmvc++spring+mybatis整合

1、hotel.java

package com.pjf.ssm.po;

public class Hotel {
private int hotelId;
private String hotelName;
private String hotelAddress;
private int price; public int getHotelId() {
return hotelId;
} public void setHotelId(int hotelId) {
this.hotelId = hotelId;
} public String getHotelName() {
return hotelName;
} public void setHotelName(String hotelName) {
this.hotelName = hotelName;
} public String getHotelAddress() {
return hotelAddress;
} public void setHotelAddress(String hotelAddress) {
this.hotelAddress = hotelAddress;
} public int getPrice() {
return price;
} public void setPrice(int price) {
this.price = price;
} }

2、hotel.service接口和实现类

通过@Service("hotelService")在Spring工厂中注册,就不需要编写xml文件配置了

通过@Autowired注入hotelMapper类

package com.pjf.ssm.service;

import java.util.List;

import com.pjf.ssm.po.Hotel;

public interface HotelService {

    public List<Hotel> queryHotelList();

}
package com.pjf.ssm.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service; import com.pjf.ssm.dao.HotelMapper;
import com.pjf.ssm.po.Hotel;
import com.pjf.ssm.service.HotelService; //注册组件
@Service("hotelService")
public class HotelServiceImpl implements HotelService { // 自动注入
@Autowired
private HotelMapper hotelMapper; public List<Hotel> queryHotelList() { return hotelMapper.queryHotelList(); }
}

3、hotelMapper接口和hotelMapper.xml文件

写了个简单的查询语句,这两个文件必须保吃同名,且在同一个目录下。

package com.pjf.ssm.dao;

import java.util.List;

import com.pjf.ssm.po.Hotel;

public interface HotelMapper {

    public List<Hotel> queryHotelList();

}
<?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.pjf.ssm.dao.HotelMapper">
<resultMap id="HotelMap" type="com.pjf.ssm.po.Hotel">
<id column="id" property="hotelId" jdbcType="INTEGER" />
<result column="hotel_name" property="hotelName" jdbcType="VARCHAR" />
<result column="hotel_address" property="hotelAddress" jdbcType="VARCHAR" />
<result column="price" property="price" jdbcType="INTEGER" />
</resultMap> <select id="queryHotelList" resultMap="HotelMap">
select id,hotel_name,hotel_address,price from hotel
</select> </mapper>

4、QueryHotelController .java

package com.pjf.ssm.controller;

import java.util.ArrayList;
import java.util.List; import com.pjf.ssm.po.Hotel;
import com.pjf.ssm.service.HotelService; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
//使用Controller这个注解来标识这是一个控制器
@Controller
public class QueryHotelController {
@Autowired
private HotelService hotelService; //酒店列表查询
//@RequestMapping实现queryHotelList方法和url进行映射
//建议将url和方法名一样,一个方法对应一个url
@RequestMapping(value = "/queryHotelList", method = RequestMethod.GET)
public ModelAndView queryHotelList()throws Exception{ List<Hotel> hotelList = hotelService.queryHotelList();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("hotelList",hotelList);
modelAndView.setViewName("/WEB-INF/jsp/hotel/hotelList.jsp"); return modelAndView;
}
}

5、jsp文件编写

主要是前端的展示,不熟悉html的可以网上copy一份修改下就行了

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<!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>
<form action="${pageContext.request.contextPath }/queryHotelDetail.action" method="get"> 酒店列表:
<table border=1>
<tr>
<td>酒店id</td>
<td width=100>酒店名</td>
<td>酒店地址</td>
<td>起价</td>
<td ></td>
</tr>
<c:forEach items="${hotelList}" var="hotel">
<tr>
<td>${hotel.hotelId }</td>
<td>${hotel.hotelName }</td>
<td>${hotel.hotelAddress }</td>
<td>${hotel.price }</td>
<td ><input type="submit" value="查看详情"></td>
</tr>
</c:forEach>
</table>
</form> </body>
</html>

四、在tomact中测试

mybatis学习(十一)——springmvc++spring+mybatis整合

在tomact中添加工程ssm,然后右键点击tomact,点击debug运行,debug模式下修改文件,不需要重启tomact就可以生效

然后在前端输入地址

http://localhost:8081/ssm/queryHotelList

这里之所以是8081端口,是因为我本地之前装了tomact8.0,避免冲突所以修改了默认的8080端口,大家测试可以使用8080.

结果:

mybatis学习(十一)——springmvc++spring+mybatis整合

上一篇:不再为命名而苦恼!使用 MSTestEnhancer 单元测试扩展,写契约就够了


下一篇:Oracle与Mysql的高级查询与难点sql