一、框架整合
1.1 思路
其实思路和我们之前整合的方式一样,这里当作复习。
1.1.1 dao 层
- 整合
mybatis
和spring
,需要用到的依赖:mybatis
的jar
,mysql
驱动,数据库连接池druid
,mybatis
和spring
的整合包,spring
。 - 配置文件:
1、mybatis
的配置文件SqlMapConfig.xml
2、spring
的配置文件:applicationContext-dao.xml
数据源、数据库连接池、SqlSessionFactory
(整合包中)、mappper
文件扫描器(整合包)
1.1.2 Service层
- 使用的
jar
:spring
的jar
- 配置文件:
添加到springmvc
容器applicationContext-service.xml
,其中需要配置扫描器(扫描带@Service
注解的类)
事务(applicationContext-transaction.xml
),一个事务管理器,配置切面aop
、通知tx
。
1.1.3 表现层
- 相关依赖包
需要springmvc
和spring
的包。 - 配置文件:
springmvc.xml
配置适配器、映射器、视图解析器。配置注解驱动(替代适配器和映射器)。配置一个视图解析器。配置包扫描器,扫描Controller
注解。
1.1.4 web.xml
在web.xml
中配置springmvc
的前端控制器,spring
的监听器字符编码等。
注意:不管是那一层的配置文件,都应该放在web
层下面。即工程taotao-manager-web
中的src/main/resources
中。
1.2 整合
1.2.1 dao层
taotao-manager-web/src/main/resources/mybatis/SqlMapConfig.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>
</configuration>
taotao-manager-web/src/main/resources/spring/applicationContext-dao.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 数据库连接池 -->
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:properties/*.properties" />
<!-- 数据库连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
destroy-method="close">
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="driverClassName" value="${jdbc.driver}" />
<property name="maxActive" value="10" />
<property name="minIdle" value="5" />
</bean>
<!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.taotao.mapper" />
</bean>
</beans>
taotao-manager-web/src/main/resources/propertis/db.propertis
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3305/taotao?characterEncoding=utf-8
jdbc.username=root
jdbc.password=walp1314
说明:相关表和数据这里就不给出了,网上可以找到。
1.2.2 service层
其中applicationContext-service.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 配置包扫描器,扫描service注解的类 -->
<context:component-scan base-package="com.taotao.service"></context:component-scan>
</beans>
事务applicationContext-transaction.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
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.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd">
<!-- 配置事务 -->
<!-- 事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="create*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
<tx:method name="select*" propagation="SUPPORTS" read-only="true" />
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.taotao.service.*.*(..))" />
</aop:config>
</beans>
1.2.3 表现层
其中springmvc.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd">
<!-- 配置包扫描器 -->
<context:component-scan base-package="com.taotao.controller"></context:component-scan>
<!-- 注解驱动 -->
<mvc:annotation-driven/>
<!-- 视图解析器,解析jsp视图 -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp"></property>
</bean>
</beans>
而web.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>taotao-manager</display-name>
<!-- 加载spring的容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/applicationContext-*.xml</param-value>
</context-param>
<!-- post乱码过虑器 -->
<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>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- spring监听器 -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- springmvc的前端控制器 -->
<servlet>
<servlet-name>taotao-manager</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- contextConfigLocation不是必须的, 如果不配置contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的name+"-servlet.xml" -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>taotao-manager</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
说明:到此,相关的整合工作就完成了。
二、测试
2.1 逆向工程生成相关代码
新建一个工程mybatis-generator
generatorConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE generatorConfiguration
PUBLIC "-//mybatis.org//DTD MyBatis Generator Configuration 1.0//EN"
"http://mybatis.org/dtd/mybatis-generator-config_1_0.dtd">
<generatorConfiguration>
<context id="testTables" targetRuntime="MyBatis3">
<commentGenerator>
<!-- 是否去除自动生成的注释 ture:是 false:否 -->
<property name="suppressAllComments" value="true"/>
</commentGenerator>
<!-- 数据库连接的信息 -->
<jdbcConnection driverClass="com.mysql.jdbc.Driver"
connectionURL="jdbc:mysql://localhost:3305/taotao"
userId="root"
password="walp1314">
</jdbcConnection>
<!-- oracle -->
<!-- <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:mybatis"
userId="root"
password="walp1314">
</jdbcConnection> -->
<!-- 默认false,把JDBC DECIMAL和NUMERIC类型解析为Integer,为true时解析为java.math.BigDecimal -->
<javaTypeResolver>
<property name="forceBigDecimals" value="false"/>
</javaTypeResolver>
<!-- targetProject:生成pojo类的位置 -->
<javaModelGenerator targetPackage="com.taotao.pojo"
targetProject=".\src">
<!-- enableSubPackages:是否让schame作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
<!-- 从数据库返回的值被清理前后的空格 -->
<property name="trimStrings" value="true"/>
</javaModelGenerator>
<!-- targetProject:mapper映射成文件的位置 -->
<sqlMapGenerator targetPackage="com.taotao.mapper"
targetProject=".\src">
<!-- enableSubPackages:是否让schame作为包的后缀 -->
<property name="enableSubPackages" value="false"/>
</sqlMapGenerator>
<!-- targetPackage:mapper接口生成的位置 -->
<javaClientGenerator targetPackage="com.taotao.mapper"
type="XMLMAPPER" targetProject=".\src">
<!-- enableSubPackages: 是否让schame作为包的后缀-->
<property name="enableSubPackages" value="false"/>
</javaClientGenerator>
<!-- 指定数据库表 -->
<table schema="" tableName="tb_content"></table>
<table schema="" tableName="tb_content_category"></table>
<table schema="" tableName="tb_item"></table>
<table schema="" tableName="tb_item_cat"></table>
<table schema="" tableName="tb_item_desc"></table>
<table schema="" tableName="tb_item_param"></table>
<table schema="" tableName="tb_item_param_item"></table>
<table schema="" tableName="tb_order"></table>
<table schema="" tableName="tb_order_item"></table>
<table schema="" tableName="tb_order_shipping"></table>
<table schema="" tableName="tb_user"></table>
</context>
</generatorConfiguration>
GeneratorSqlmap.java
package com.taotao.util;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import org.mybatis.generator.api.MyBatisGenerator;
import org.mybatis.generator.config.Configuration;
import org.mybatis.generator.config.xml.ConfigurationParser;
import org.mybatis.generator.internal.DefaultShellCallback;
public class GeneratorSqlmap {
public void generator() throws Exception {
List<String> warnings = new ArrayList<String>();
boolean overwrite = true;
File configFile = new File("generatorConfig.xml");
ConfigurationParser cp = new ConfigurationParser(warnings);
Configuration config = cp.parseConfiguration(configFile);
DefaultShellCallback callback = new DefaultShellCallback(overwrite);
MyBatisGenerator myBatisGenerator = new MyBatisGenerator(config, callback, warnings);
myBatisGenerator.generate(null);
}
public static void main(String[] args) {
try {
GeneratorSqlmap generatorSqlmap = new GeneratorSqlmap();
generatorSqlmap.generator();
} catch (Exception e) {
e.printStackTrace();
}
}
}
说明:将生成的mapper
拷贝到taotao-manager-dao
,将生成的pojo
拷贝到taotao-manager-pojo
。
2.2 测试
2.2.1 需求
根据商品id
查询商品信息,返回json
数据。
2.2.2 dao层
查询的表tb_item
,。可以直接使用逆向工程生成的代码。这里我们直接利用逆向工程生成的代码。
2.2.3 service层
接收一个商品id
,调用mapper
查询商品信息,返回商品的pojo
。
ItemServiceImpl.java
package com.taotao.service.impl;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.taotao.mapper.TbItemMapper;
import com.taotao.pojo.TbItem;
import com.taotao.pojo.TbItemExample;
import com.taotao.pojo.TbItemExample.Criteria;
import com.taotao.service.ItemService;
/**
* 商品查询service
* @author yj
*/
@Service
public class ItemServiceImpl implements ItemService {
@Autowired
private TbItemMapper itemMapper;
@Override
public TbItem getItemById(Long itemId) throws Exception {
//TbItem item = itemMapper.selectByPrimaryKey(itemId);
TbItemExample example = new TbItemExample();
//创建查询条件
Criteria criteria = example.createCriteria();
criteria.andIdEqualTo(itemId);
List<TbItem> list = itemMapper.selectByExample(example);
//判断list中是否为空
TbItem item = null;
if(list != null && list.size() > 0){
item = list.get(0);
}
return item;
}
}
2.2.4 Controller层
接收一个商品id
,调用service
返回一个商品的pojo
,直接响应pojo
。要返回json
数据需要使用@ResponseBody
。
注意:使用@ResponseBody
时一定要加上jsckson
的包。而uri
地址是/item/{itemId}
。
ItemController.java
package com.taotao.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.taotao.pojo.TbItem;
import com.taotao.service.ItemService;
/**
* 商品查询
* @author yj
*/
@Controller
public class ItemController {
@Autowired
private ItemService itemService;
@RequestMapping("/item/{itemId}")
@ResponseBody
private TbItem getItemById(@PathVariable Long itemId) throws Exception{
TbItem item = itemService.getItemById(itemId);
return item;
}
}
2.2.5 测试
此时启动工程,使用地址http://localhost:8080/item/635906
访问会出现异常org.apache.ibatis.binding.BindingException
。这表示找不到相关的mapper
文件,我们在工程的classes
目录中发现没有mapper
文件。这是因为maven
工程的src/main/java
包中会忽略非java
文件。也就是mapper
包中的xml
文件被忽略了。此时我们需要修改taotao-manager-dao
中的pom
文件,添加如下内容:
<!-- 如果不添加此节点mybatis的mapper.xml文件都会被漏掉。 -->
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
这表示会将此包中的xml
等文件也复制(默认只复制src/main/resources
中的文件)。此时classes
目录中就会有mapper
文件。测试结果为: