Spring+Spring MVC+MyBatis整合
一、准备工作
1.1导入所需jar包
1.2数据库
CREATE TABLE `t_customer` ( `id` int(32) NOT NULL AUTO_INCREMENT, `username` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `jobs` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, `phone` varchar(16) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL, PRIMARY KEY (`id`) USING BTREE ) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8;
二、编写配置文件
2.1编写db.propertise文件
#dataSource #Thu Mar 07 16:27:40 CST 2019 jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/sm jdbc.username=root jdbc.password=123456 jdbc.maxTotal=30 jdbc.maxIdle=10 jdbc.initialSize=5
2.2在src目录下创建beans.xml(applicationContext.xml)
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance" 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/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" > <context:property-placeholder location = "classpath:db.properties"/> <bean id = "dataSource" class = "org.apache.commons.dbcp2.BasicDataSource"> <property name = "driverClassName" value = "${jdbc.driver}" /> <property name = "url" value = "${jdbc.url}" /> <property name = "username" value = "${jdbc.username}" /> <property name = "password" value = "${jdbc.password}" /> <property name="maxTotal" value = "${jdbc.maxTotal}"/> <property name="maxIdle" value = "${jdbc.maxIdle}"/> <property name="initialSize" value = "${jdbc.initialSize}"/> bean> <bean id = "transactionManager" class = "org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name = "dataSource" ref = "dataSource" /> bean> <tx:annotation-driven transaction-manager = "transactionManager" /> <context:component-scan base-package="com.ssm.service"/> <bean id = "sqlSessionFactory" class = "org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref = "dataSource"/> <property name="configLocation" value = "classpath:mybatis-config.xml"/> bean> <bean class = "org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name = "basePackage" value = "com.ssm.dao"/> bean> beans>
2.3在src目录下创建mybatis-congfig.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> <package name="com.ssm.po"/> typeAliases> <mappers> mappers> configuration>
2.4在src目录下创建springmvc-config.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:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-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/context http://www.springframework.org/schema/context/spring-context-4.3.xsd"> <context:component-scan base-package = "com.ssm.controller"/>
<mvc:annotation-driven/> <bean id = "viewResolver" class = "org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="prefix" value = "/WEB-INF/jsp/">property> <property name="suffix" value = ".jsp">property> bean> beans>
2.5web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1"> <display-name>SSMdisplay-name> <welcome-file-list> <welcome-file>index.htmlwelcome-file> <welcome-file>index.htmwelcome-file> <welcome-file>index.jspwelcome-file> <welcome-file>default.htmlwelcome-file> <welcome-file>default.htmwelcome-file> <welcome-file>default.jspwelcome-file> welcome-file-list> <context-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:beans.xmlparam-value> context-param> <listener> <listener-class> org.springframework.web.context.ContextLoaderListener listener-class> listener> <filter> <filter-name>encodingfilter-name> <filter-class> org.springframework.web.filter.CharacterEncodingFilter filter-class> <init-param> <param-name>encodingparam-name> <param-value>UTF-8param-value> init-param> filter> <filter-mapping> <filter-name>encodingfilter-name> <url-pattern>*.actionurl-pattern> filter-mapping> <servlet> <servlet-name>springmvcservlet-name> <servlet-class> org.springframework.web.servlet.DispatcherServlet servlet-class> <init-param> <param-name>contextConfigLocationparam-name> <param-value>classpath:springmvc-config.xmlparam-value> init-param> <load-on-startup>1load-on-startup> servlet> <servlet-mapping> <servlet-name>springmvcservlet-name> <url-pattern>/url-pattern> servlet-mapping> web-app>
三、测试整合
3.1在src目录下创建com.ssm.po包,并创建Customer类
Customer.java
package com.ssm.po; public class Customer { private Integer id; private String username; private String jobs; private String phone; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getJobs() { return jobs; } public void setJobs(String jobs) { this.jobs = jobs; } public String getPhone() { return phone; } public void setPhone(String phone) { this.phone = phone; } @Override public String toString() { return "Customer [id=" + id + ", username=" + username + ", jobs=" + jobs + ", phone=" + phone + "]"; } }
3.2在src目录下创建com.ssm.dao包,并创建接口文件CustomerDao.java和映射文件CustomerDao.xml
CustomerDao.java
package com.ssm.dao; import com.ssm.po.Customer; public interface CustomerDao { public Customer findCustomerById(Integer id); }
CustomerDao.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.ssm.dao.CustomerDao" > <select id = "findCustomerById" parameterType = "Integer" resultType = "com.ssm.po.Customer"> select * from t_customer where id = #{id} select> mapper>
注:接口文件和映射文件的名称要保持一致,映射文件namespace名称要符合规范。
接口方法名和映射文件语句id,返回值类型、参数类型要保持一致。
两个文件要在同一包中。
3.3在src目录下创建com.ssm.service包,并创建接口文件CustomerService.java
package com.ssm.service; import org.springframework.stereotype.Service; import com.ssm.po.Customer; @Service public interface CustomerService { public Customer findCustomerById(Integer id); }
3.4在src目录下创建com.ssm.service.Impl包,并在其中创建CustoemrService接口的实现类CustomerServiceImpl.java
CustomerService.java
package com.ssm.service.Impl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import com.ssm.dao.CustomerDao; import com.ssm.po.Customer; import com.ssm.service.CustomerService; @Service //标记当前类,通过扫描注册 @Transactional public class CustomerServiceImpl implements CustomerService{ @Autowired //按类型自动装配 private CustomerDao customerDao; @Override public Customer findCustomerById(Integer id) { return this.customerDao.findCustomerById(id); } }
3.5在src目录下创建com.ssm.controller包,并创建CustomerController类
CustomerController.java
package com.ssm.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import com.ssm.po.Customer; import com.ssm.service.CustomerService; @Controller //标注为控制类,自动扫描 public class CustomerController { @Autowired //按类型自动装配 private CustomerService customerService; @RequestMapping("/findCustomerById") public String findCustomerById(Integer id, Model model) { Customer customer = customerService.findCustomerById(id); model.addAttribute("customer", customer); return "customer";//返回WEB-INF/jsp/customer.jsp } }
3.6在WEB-INF目录下创建文件夹jsp,并在其中创建customer.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Insert title heretitle> head> <body> <table border="1"> <tr> <td>idtd> <td>姓名td> <td>职业td> <td>电话td> tr> <tr> <td>${customer.id}td> <td>${customer.username}td> <td>${customer.jobs}td> <td>${customer.phone}td> tr> table> body> html>
启动服务器,添加项目。
地址栏输入:http://localhost:8080/SSM/findCustomerById?id=1
项目结构:
常见错误:
1、配置文件中书写错误,例如classpath拼写错误、文件名拼写错误(beans.xml写错了benas.xml)。
2、com.ssm.service.Impl写成了com.ssm.serviceImpl,
在beans.xml中配置的:
不会扫描com.ssm.serviceImpl.
3、com.ssm.dao中映射文件和接口文件不匹配。
4、注解导入错误:注意导入的注解多是org.springframework中的注解。
5、视图解析器前后缀配置错误,找不到路径。
7、RequestMapping("xxx")中设置路径与地址栏输入路径不一致。
8. 文件中未设置自动扫描,找不到指定类。