一欲芹、框架整合
1.1 思路
其實(shí)思路和我們之前整合的方式一樣菱父,這里當(dāng)作復(fù)習(xí)颈娜。
1.1.1 dao 層
- 整合
mybatis
和spring
浙宜,需要用到的依賴:mybatis
的jar
粟瞬,mysql
驅(qū)動,數(shù)據(jù)庫連接池druid
俗批,mybatis
和spring
的整合包岁忘,spring
区匠。 - 配置文件:
1辱志、mybatis
的配置文件SqlMapConfig.xml
2揩懒、spring
的配置文件:applicationContext-dao.xml
數(shù)據(jù)源挽封、數(shù)據(jù)庫連接池辅愿、SqlSessionFactory
(整合包中)点待、mappper
文件掃描器(整合包)
1.1.2 Service層
- 使用的
jar
:spring
的jar
- 配置文件:
添加到springmvc
容器applicationContext-service.xml
,其中需要配置掃描器(掃描帶@Service
注解的類)
事務(wù)(applicationContext-transaction.xml
)状原,一個事務(wù)管理器颠区,配置切面aop
毕莱、通知tx
。
1.1.3 表現(xiàn)層
- 相關(guān)依賴包
需要springmvc
和spring
的包蛹稍。 - 配置文件:
springmvc.xml
配置適配器稳摄、映射器厦酬、視圖解析器瘫想。配置注解驅(qū)動(替代適配器和映射器)国夜。配置一個視圖解析器。配置包掃描器筹裕,掃描Controller
注解朝卒。
1.1.4 web.xml
在web.xml
中配置springmvc
的前端控制器抗斤,spring
的監(jiān)聽器字符編碼等丈咐。
注意:不管是那一層的配置文件棵逊,都應(yīng)該放在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">
<!-- 數(shù)據(jù)庫連接池 -->
<!-- 加載配置文件 -->
<context:property-placeholder location="classpath:properties/*.properties" />
<!-- 數(shù)據(jù)庫連接池 -->
<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">
<!-- 數(shù)據(jù)庫連接池 -->
<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
說明:相關(guān)表和數(shù)據(jù)這里就不給出了,網(wǎng)上可以找到今布。
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>
事務(wù)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">
<!-- 配置事務(wù) -->
<!-- 事務(wù)管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 數(shù)據(jù)源 -->
<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 表現(xiàn)層
其中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>
<!-- 注解驅(qū)動 -->
<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監(jiān)聽器 -->
<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的配置文件默認(rèn)在: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>
說明:到此靴庆,相關(guān)的整合工作就完成了炉抒。
二端礼、測試
2.1 逆向工程生成相關(guān)代碼
新建一個工程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>
<!-- 數(shù)據(jù)庫連接的信息 -->
<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> -->
<!-- 默認(rèn)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"/>
<!-- 從數(shù)據(jù)庫返回的值被清理前后的空格 -->
<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>
<!-- 指定數(shù)據(jù)庫表 -->
<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 需求
根據(jù)商品id
查詢商品信息娜睛,返回json
數(shù)據(jù)卦睹。
2.2.2 dao層
查詢的表tb_item
结序,±罚可以直接使用逆向工程生成的代碼返敬。這里我們直接利用逆向工程生成的代碼救赐。
2.2.3 service層
接收一個商品id
,調(diào)用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();
//創(chuàng)建查詢條件
Criteria criteria = example.createCriteria();
criteria.andIdEqualTo(itemId);
List<TbItem> list = itemMapper.selectByExample(example);
//判斷l(xiāng)ist中是否為空
TbItem item = null;
if(list != null && list.size() > 0){
item = list.get(0);
}
return item;
}
}
2.2.4 Controller層
接收一個商品id
苗沧,調(diào)用service
返回一個商品的pojo
待逞,直接響應(yīng)pojo
网严。要返回json
數(shù)據(jù)需要使用@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
訪問會出現(xiàn)異常org.apache.ibatis.binding.BindingException
担扑。這表示找不到相關(guān)的mapper
文件涌献,我們在工程的classes
目錄中發(fā)現(xiàn)沒有mapper
文件。這是因?yàn)?code>maven工程的src/main/java
包中會忽略非java
文件枢劝。也就是mapper
包中的xml
文件被忽略了您旁。此時我們需要修改taotao-manager-dao
中的pom
文件轴捎,添加如下內(nèi)容:
<!-- 如果不添加此節(jié)點(diǎn)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
等文件也復(fù)制(默認(rèn)只復(fù)制src/main/resources
中的文件)腻格。此時classes
目錄中就會有mapper
文件产弹。測試結(jié)果為: