2、基本工程搭建(2)(案例筆記)

一、框架整合

1.1 思路

其實思路和我們之前整合的方式一樣,這里當作復習。

1.1.1 dao 層

  • 整合mybatisspring,需要用到的依賴:mybatisjarmysql驅(qū)動,數(shù)據(jù)庫連接池druidmybatisspring的整合包,spring
  • 配置文件:
    1、mybatis的配置文件SqlMapConfig.xml
    2、spring的配置文件:applicationContext-dao.xml
    數(shù)據(jù)源、數(shù)據(jù)庫連接池、SqlSessionFactory(整合包中)、mappper文件掃描器(整合包)

1.1.2 Service層

  • 使用的jarspringjar
  • 配置文件:
    添加到springmvc容器applicationContext-service.xml,其中需要配置掃描器(掃描帶@Service注解的類)
    事務(wù)(applicationContext-transaction.xml),一個事務(wù)管理器,配置切面aop、通知tx

1.1.3 表現(xiàn)層

  • 相關(guān)依賴包
    需要springmvcspring的包。
  • 配置文件: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的配置文件默認在: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> -->
        <!-- 默認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文件。這是因為maven工程的src/main/java包中會忽略非java文件。也就是mapper包中的xml文件被忽略了。此時我們需要修改taotao-manager-dao中的pom文件,添加如下內(nèi)容:

<!-- 如果不添加此節(jié)點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文件。測試結(jié)果為:

1

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

推薦閱讀更多精彩內(nèi)容