• 移动商城第三篇【搭建Mybatis和Spring环境、编写Dao、Service在Core模块】


    Mybatis和Spring环境搭建

    由于我们的所编写的dao层、service代码可能前台和后台都需要用到的,因此我们把环境搭建在core模块中

    逆向工程

    首先,我们要做的就是品牌管理,我们首先来看看原型界面的的品牌管理

    这里写图片描述

    涉及到的数据库表在我们的powerdesigner中就已经定义过了

    这里写图片描述

    我们来看一下对应数据库表的数据

    这里写图片描述

    添加逆向工程插件

    
        <build>
            <finalName>zhongfucheng</finalName>
            <plugins>
                <plugin>
                    <groupId>org.mybatis.generator</groupId>
                    <artifactId>mybatis-generator-maven-plugin</artifactId>
                    <version>1.3.2</version>
                    <configuration>
                        <verbose>true</verbose>
                        <overwrite>true</overwrite>
                    </configuration>
                </plugin>
            </plugins>
        </build>

    编写逆向工程文件

    <?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>
        <!-- 制定mysql的驱动包的路径 千万别放中文路径下 -->
        <classPathEntry location="F:传智168期JAVA传智168期JAVA移动商城shoprepositoryshoprepository
    epositorycomoracleojdbc1410.2.0.2.0ojdbc14-10.2.0.2.0.jar" />
    
        <!-- 配置数据源和生成的代码所存放的位置 -->
        <context id="context1">
    
            <commentGenerator>
                <!-- 是否取消注释 -->
                <property name="suppressAllComments" value="true" />
                <!-- 是否生成注释代时间戳 -->
                <property name="suppressDate" value="true" />
            </commentGenerator>
            <jdbcConnection driverClass="oracle.jdbc.OracleDriver"
                connectionURL="jdbc:oracle:thin:@127.0.0.1:1521:ZHONGFUCHENG" userId="zhongfucheng"
                password="zhong" />
            <!-- 所生成的实体类的位置默认资源包src -->
            <javaModelGenerator targetPackage="com.rl.ecps.model" targetProject="src/main/java" />
            <!-- 所生成的sqlMap的影射文件的位置,默认资源包src -->
            <sqlMapGenerator targetPackage="com.rl.ecps.sqlMap" targetProject="src/main/java" />
    
            <!-- 为哪些表生成代码 tableName:表名 schema:不用填写 -->
            <table schema="" tableName="eb_brand" enableCountByExample="false"
                enableUpdateByExample="false" enableDeleteByExample="false"
                enableSelectByExample="false" selectByExampleQueryId="false"
            >
            </table>
        </context>
    </generatorConfiguration>
    

    生成的文件:

    这里写图片描述

    sqlMapping映射文件也算是一种资源文件把,因此我把它移到resources中了

    这里写图片描述

    编写Mybatis配置文件

    sqlMapConfig.xml

    
    <!DOCTYPE configuration
    PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
    "http://mybatis.org/dtd/mybatis-3-config.dtd">
    <configuration>
        <mappers>
            <mapper resource="sqlMap/EbBrandMapper.xml"/>
        </mappers>
    </configuration>
    

    创建beans.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:tx="http://www.springframework.org/schema/tx"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
    
        <!--开启注解-->
        <context:component-scan base-package="com.rl.ecps"/>
    
        <!--配置连接池-->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="driverClassName" value="oracle.jdbc.OracleDriver"></property>
            <property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:ZHONGFUCHENG"></property>
            <property name="username" value="zhongfucheng"></property>
            <property name="password" value="zhong"></property>
        </bean>
    
    
        <!--配置sessionFactory-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"></property>
            <property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
        </bean>
    
    
        <!--配置事务管理器-->
        <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"></property>
        </bean>
    
        <!--配置事务具体方法-->
        <tx:advice id="txAdive" transaction-manager="txManager">
            <tx:attributes>
                <tx:method name="save*" propagation="REQUIRED"/>
                <tx:method name="update*" propagation="REQUIRED"/>
                <tx:method name="add*" propagation="REQUIRED"/>
                <tx:method name="modify*" propagation="REQUIRED"/>
                <tx:method name="delete*" propagation="REQUIRED"/>
                <tx:method name="remove*" propagation="REQUIRED"/>
                <tx:method name="select*" read-only="true"/>
                <tx:method name="get*" read-only="true"/>
            </tx:attributes>
        </tx:advice>
    
        <!--配置切面-->
        <aop:config>
            <aop:advisor advice-ref="txAdive" pointcut="execution(* com.rl.ecps.service..*.*(..))"/>
        </aop:config>
    
    </beans>

    添加log4j

    log4j.properties

    
    log4j.rootLogger=DEBUG, Console
    #Console
    log4j.appender.Console=org.apache.log4j.ConsoleAppender
    log4j.appender.Console.layout=org.apache.log4j.PatternLayout
    log4j.appender.Console.layout.ConversionPattern=%d [%t] %-5p [%c] - %m%n
    log4j.logger.java.sql.ResultSet=INFO
    log4j.logger.org.apache=INFO
    log4j.logger.java.sql.Connection=DEBUG
    log4j.logger.java.sql.Statement=DEBUG
    log4j.logger.java.sql.PreparedStatement=DEBUG
    

    Dao层

    编写Dao接口

    
    interface EbBrandDao {
    
    
        void saveBrand(EbBrand brand);
    
        EbBrand getBrandById(Long brandId);
    
        void updateBrand(EbBrand brand);
    
        void deleteBrand(Long brandId);
    
        List<EbBrand> selectBrand();
    
        List<EbBrand> selectBrandByName(String brandName);
    }
    

    编写Dao实现

    
    /**
     * 继承SqlSessionDaoSupport能够得到sessionFactory的引用,非常方便!
     */
    @Repository
    public class EbBrandDaoImpl extends SqlSessionDaoSupport implements EbBrandDao {
    
        String nameSpace = "com.rl.ecps.sqlMap.EbBrandMapper.";
    
        public void saveBrand(EbBrand brand) {
    
            this.getSqlSession().insert(nameSpace + "insert", brand);
        }
        public EbBrand getBrandById(Long brandId) {
            return this.getSqlSession().selectOne(nameSpace + "selectByPrimaryKey", brandId);
        }
        public void updateBrand(EbBrand brand) {
    
            /**
             * updateByPrimaryKeySelective和updata的区别:
             *  一个是动态SQL,一个是静态SQL。这里就使用动态SQL比较好。因为是更新操作
             */
            this.getSqlSession().update(nameSpace + "updateByPrimaryKeySelective", brand);
        }
        public void deleteBrand(Long brandId) {
    
            this.getSqlSession().delete(nameSpace + "deleteByPrimaryKey", brandId);
        }
        public List<EbBrand> selectBrand() {
            return this.getSqlSession().selectList(nameSpace+"selectBrand");
        }
        public List<EbBrand> selectBrandByName(String brandName) {
            return this.getSqlSession().selectList(nameSpace+"selectBrandByName", brandName);
        }
    }

    mybatis插件只有最后两个方法没有帮我们自动生成,其他的SQL语句都自动生成了。

    
      <select id="selectBrand" resultMap="BaseResultMap">
        select * from eb_brand
      </select>
    
      <select id="selectBrandByName" resultMap="BaseResultMap" parameterType="string">
          select * from eb_brand t where t.brand_name = #{brandName}
      </select>
    
    

    编写Service

    Service接口

    
    public interface EbBrandService {
        void saveBrand(EbBrand brand);
    
        EbBrand getBrandById(Long brandId);
    
        void updateBrand(EbBrand brand);
    
        void deleteBrand(Long brandId);
    
        List<EbBrand> selectBrand();
    
        List<EbBrand> selectBrandByName(String brandName);
    }

    Service实现

    
    package com.rl.ecps.service.impl;
    
    import com.rl.ecps.dao.EbBrandDao;
    import com.rl.ecps.dao.impl.EbBrandDaoImpl;
    import com.rl.ecps.model.EbBrand;
    import com.rl.ecps.service.EbBrandService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    
    import java.util.List;
    
    /**
     * Created by ozc on 2017/8/26.
     */
    
    @Service
    public class EbBrandServiceImpl implements EbBrandService {
    
    
        @Autowired
        private EbBrandDao brandDao;
    
        public void saveBrand(EbBrand brand) {
            brandDao.saveBrand(brand);
    
        }
    
        public EbBrand getBrandById(Long brandId) {
            return brandDao.getBrandById(brandId);
        }
    
        public void updateBrand(EbBrand brand) {
    
            brandDao.updateBrand(brand);
    
        }
        public void deleteBrand(Long brandId) {
    
            brandDao.deleteBrand(brandId);
    
        }
        public List<EbBrand> selectBrand() {
            return brandDao.selectBrand();
        }
        public List<EbBrand> selectBrandByName(String brandName) {
            return brandDao.selectBrandByName(brandName);
        }
    
    }
    

    测试Service

    在idea中,我们新建一个test目录

    这里写图片描述

    对着我们的serviceImpl使用快捷键ctrl+shift+t

    这里写图片描述

    idea就会帮我们自动把想要测试的方法把相关的目录创建出来了

    这里写图片描述

    我们在插入数据的时候,记得要改写SQL语句,因为默认是没有主键的。下面就是我们把在主键列上使用自动增长

    
    <insert id="insert" parameterType="com.rl.ecps.model.EbBrand" >
    
        <selectKey keyProperty="brandId" order="BEFORE" resultType="long">
          select seqbrandid.nextval from dual
        </selectKey>
    
    
        insert into EB_BRAND (BRAND_ID, BRAND_NAME, BRAND_DESC, 
          IMGS, WEBSITE, BRAND_SORT
          )
        values (#{brandId,jdbcType=DECIMAL}, #{brandName,jdbcType=VARCHAR}, #{brandDesc,jdbcType=VARCHAR}, 
          #{imgs,jdbcType=VARCHAR}, #{website,jdbcType=VARCHAR}, #{brandSort,jdbcType=DECIMAL}
          )
      </insert>

    插入成功

    这里写图片描述

  • 相关阅读:
    【机器学习】浅谈协方差
    python {}.format
    【机器学习】准确率、精确率、召回率
    【声纹识别】 EER
    【机器学习】 最形象的入门
    逻辑卷-LVM
    RAID及软RAID的实现
    输入数字or 字符串,统计重复次数---字典统计练习
    Python-数据结构之dict(字典*****)
    POJ 3204 网络流的必须边
  • 原文地址:https://www.cnblogs.com/zhong-fucheng/p/7554337.html
Copyright © 2020-2023  润新知