转载

从零开始写项目第一篇【搭建环境】

使用Maven搭建SSM环境

SSM需要的基础jar包有哪些??整理一下:

  • c3p0数据连接池
  • springMVC的JSON
  • springAOP
  • springCore
  • springPersitence
  • springWeb
  • myBatis
  • myBatisSpring
  • mysql
  • mybatis逆向工程插件

2017/10/24 16:00:31

我去的是: http://mvnrepository.com/ 这个网站中找jar包, 大多数使用最新的jar包

  • 本来是使用spring5来进行整合的,结果与asm冲突了,网上又没什么解决方案。
  • 最后妥协了改成3.2.2

pom.xml文件配置

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">

    <modelVersion>4.0.0</modelVersion>
    <packaging>war</packaging>

    <name>fuchengWeb</name>
    <groupId>fuchengWeb</groupId>
    <artifactId>fuchengWeb</artifactId>
    <version>1.0-SNAPSHOT</version>
    
    <!--逆向工程插件-->
    <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>
    <dependencies>


        <!--c3p0-->
        <dependency>
            <groupId>c3p0</groupId>
            <artifactId>c3p0</artifactId>
            <version>0.9.1.2</version>
        </dependency>

        <!--json-->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-core-asl</artifactId>
            <version>1.9.13</version>
        </dependency>

        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>


        <!--mybatis-spring-->

        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>

        <!--mysql-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.34</version>
        </dependency>

        <!--spring aop-->

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.8.11</version>
        </dependency>

        <dependency>
            <groupId>org.aopalliance</groupId>
            <artifactId>com.springsource.org.aopalliance</artifactId>
            <version>1.0.0</version>
        </dependency>

        <dependency>
            <groupId>net.sourceforge.cglib</groupId>
            <artifactId>com.springsource.net.sf.cglib</artifactId>
            <version>2.1.3</version>
        </dependency>

        <!--spring-core-->

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>com.springsource.org.apache.commons.logging</artifactId>
            <version>1.1.1</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>3.2.2.RELEASE</version>
            <scope>test</scope>
        </dependency>


        <!--spring-persitence-->

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-orm</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>org.springframework.transaction</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>

        <!--spring-web-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>3.2.2.RELEASE</version>
        </dependency>

        <!--mybatis-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-log4j12</artifactId>
            <version>1.7.25</version>
            <scope>test</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>1.7.25</version>
        </dependency>

        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

        <dependency>
            <groupId>org.javassist</groupId>
            <artifactId>javassist</artifactId>
            <version>3.22.0-CR2</version>
        </dependency>

        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
            <version>3.2.5</version>
        </dependency>

        <dependency>
            <groupId>org.objectweb.asm</groupId>
            <artifactId>com.springsource.org.objectweb.asm</artifactId>
            <version>2.2.3</version>
        </dependency>
    </dependencies>


</project>

如果觉得下载太慢的话,我们可以使用阿里云的私服。只要在settings下配置如下代码即可:

<mirror>
        <id>nexus-aliyun</id>
        <mirrorOf>*</mirrorOf>
        <name>Nexus aliyun</name>
        <url>http://maven.aliyun.com/nexus/content/groups/public</url>
    </mirror>

创建mysql用户和数据库

mysql用户:

  • 用户名:xxxx
  • 密码:xxxx

数据库:

  • xxxx

mybatis配置文件

myBatis-config.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="zhongfucheng.entity"/>
    </typeAliases>
</configuration>

application-context配置文件

<?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:tx="http://www.springframework.org/schema/tx"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
    http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd">

    <!--配置数据源-->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <property name="driverClass" value="com.mysql.jdbc.Driver"/>
        <property name="jdbcUrl"
                  value="jdbc:mysql://localhost:3306/xxxx?useUnicode=true&characterEncoding=UTF-8"/>
        <property name="user" value="xxxx"/>
        <property name="password" value="xxxx"/>
    </bean>

    <!-- 配置session工厂,加载mybatis配置文件 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:myBatis-config.xml"/>
        <!--配置扫描式加载SQL映射文件,那么在mybatis配置文件中就不用加载了-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>

    </bean>

    <!-- 配置事务管理器,管理数据源事务处理 -->
    <bean id="transactionManager"
          class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <!-- 配置事务通知 -->
    <tx:advice id="advice" transaction-manager="transactionManager">
        <tx:attributes>
            <!-- 默认只处理运行时异常,可加rollback-for="Exception/Throwable"等处理所有异常或包括错误 -->
            <tx:method name="insert*" propagation="REQUIRED"
                       rollback-for="Exception"/>
            <tx:method name="update*" propagation="REQUIRED"
                       rollback-for="Exception"/>
            <tx:method name="delete*" propagation="REQUIRED"
                       rollback-for="Exception"/>
            <tx:method name="*" propagation="SUPPORTS"/>
        </tx:attributes>
    </tx:advice>
    <!-- 配置切面织入的范围,后边要把事务边界定在service层 -->
    <aop:config>
        <aop:advisor advice-ref="advice"
                     pointcut="execution(* zhongfucheng.service.impl.*.*(..))"/>
    </aop:config>

    <!-- 配置SessionTemplate,已封装了繁琐的数据操作,提交事务都不用做了。 -->
    <bean id="sqlSessionTemplate" class="org.mybatis.spring.SqlSessionTemplate">
        <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"/>
    </bean>

    <!-- 自动扫描组件,要把controller去除,他们是在spring-mvc.xml中配置,如果不去除会影响事务管理。 -->
    <context:component-scan base-package="zhongfucheng">
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--使用Mapper代理-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <property name="basePackage" value="zhongfucheng.dao" />
    </bean>
</beans>

配置spring-mvc

spring-mvc.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:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:p="http://www.springframework.org/schema/p"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
    http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
    ">

    <!-- 同时开启json格式的支持 -->
    <mvc:annotation-driven></mvc:annotation-driven>

    <!-- 扫描所有的controller 但是不扫描service -->
    <context:component-scan base-package="zhongfucheng">
        <context:include-filter type="annotation"
                                expression="org.springframework.stereotype.Controller" />
        <context:exclude-filter type="annotation"
                                expression="org.springframework.stereotype.Service" />
    </context:component-scan>

    <!--视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>


</beans>

逆向生成的配置文件

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>
    <!-- 制定mysql的驱动包的路径 千万别放中文路径下 -->
    <classPathEntry
            location="X:/Users/ozc/Desktop/zhongfuchengWeb/mysql/mysql-connector-java/5.1.34/mysql-connector-java-5.1.34.jar"/>
    <!-- 配置数据源和生成的代码所存放的位置 -->
    <context id="context1">
        <commentGenerator>
            <!-- 是否取消注释 -->
            <property name="suppressAllComments" value="true"/>
            <!-- 是否生成注释代时间戳 -->
            <property name="suppressDate" value="true"/>
        </commentGenerator>
        <jdbcConnection driverClass="com.mysql.jdbc.Driver"
                        connectionURL="jdbc:mysql://localhost:3306/zhongfucheng" userId="zhongfucheng"
                        password="zhong"/>
        <!-- 所生成的实体类的位置默认资源包src -->
        <javaModelGenerator targetPackage="zhongfucheng.entity" targetProject="src/main/java"/>
        <!-- 所生成的sqlMap的影射文件的位置,默认资源包src -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>
        <!-- 配置dao接口生成信息-->
        <javaClientGenerator type="XMLMAPPER" targetPackage="zhongfucheng.dao" targetProject="src/main/java"/>
        
        <!-- 为哪些表生成代码 tableName:表名 schema:不用填写 -->
        <table schema="" tableName="EB_ORDER_DETAIL" enableCountByExample="false"
               enableUpdateByExample="false" enableDeleteByExample="false"
               enableSelectByExample="false" selectByExampleQueryId="false"
        >
        </table>
    </context>
</generatorConfiguration>

web.xml配置

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4"
         xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">


    <!--Spring监听器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicatoin-context.xml</param-value>
    </context-param>

    <!--springMVC核心分配器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-mvc.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>*.do</url-pattern>
    </servlet-mapping>

    <!--中文乱码过滤器-->
    <filter>
        <filter-name>SpringCharacterEncodingFilter</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>SpringCharacterEncodingFilter</filter-name>
        <url-pattern>*.do</url-pattern>
    </filter-mapping>
</web-app>

log4j配置文件

log4j.properties

# Rules reminder:
# DEBUG < INFO < WARN < ERROR < FATAL

# Global logging configuration
log4j.rootLogger=debug,stdout

# My logging configuration...
log4j.logger.cn.jbit.mybatisdemo=DEBUG


## Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p %d %C: %m%n

log4j.logger.org.apache.ibatis=DEBUG
## log4j.logger.org.apache.jdbc.SimpleDataSource=DEBUG
log4j.logger.org.apache.ibatis.jdbc.ScriptRunner=DEBUG
## log4j.logger.com.ibatis.sqlmap.engine.impl.SqlMapclientDelegate=DEBUG
log4j.logger.java.sql.Connection=DEBUG
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG

测试逆向工程

不知道是不是我的mysql驱动包太高了,出现了如下的问题:

The server time zone value '�й���׼ʱ��' is unrecognized or represents more than one time zone.

于是乎我就去找到了解决方案,只要在url后面加上时区就好了:

jdbc:mysql://localhost:3306/zhongfucheng?serverTimezone=UTC

随后又出现了下面的问题:

Column name pattern can not be NULL or empty

找到的解决方案,又是往后面加参数:

jdbc:mysql://localhost:3306/zhongfucheng?serverTimezone=UTC&useSSL=false&nullNamePatternMatchesAll=true

最终就成功了...

从零开始写项目第一篇【搭建环境】

...还有问题:在刚开始的时候没注意到: Mybatis Generator 生成的mapper只有insert方法

链接: http://blog.csdn.net/qq_15127715/article/details/78139228

又去查了一大堆的资料,发现还是因为mysql的驱动包太高的问题。只能往下转了。

Failed to read candidate component class错误分析:

spring 3.2不支持1.8编译环境,解决办法就是降为1.7编译环境

解决连接: http://www.cnblogs.com/cxj20160928/p/5954336.html

编写BaseMapper

/**
 * 将通用的方法抽取在BaseMapper中,那么就不用在每个单独的Mapper都要写对应的方法了。
 * @param <T>
 */
public interface BaseMapper<T> {

    int insert(T entity);

    int insertSelective(T entity);

    int deleteByPrimaryKey(String id);

    T selectByPrimaryKey(String id);

    int updateByPrimaryKeySelective(T entity);

    int updateByPrimaryKey(T entity);

}

编写BaseService

/**
 * 将通用的业务方法抽取到BaseService中,那么实现它的Service都有这些方法了。
 * @param <T>
 */
public interface BaseService<T> {

    int insert(T entity);

    int insertSelective(T entity);

    int deleteByPrimaryKey(String id);

    T selectByPrimaryKey(String id);

    int updateByPrimaryKeySelective(T entity);

    int updateByPrimaryKey(T entity);
}

BaseServiceImpl

/**
 * 使用initBaseMapper()将baseMapper实例化,service实现类是什么类型,baseMapper就是什么类型
 * 将所有的Mapper都定义出来,那么子类service就可以直接使用了
 * @param <T>
 */
public class BaseServiceImpl<T> implements BaseService<T> {

    protected BaseMapper<T> baseMapper;

    @Autowired
    protected StoreHouseMapper storeHouseMapper;

    @PostConstruct
    private void initBaseMapper() throws Exception{

        //获取泛型的信息
        ParameterizedType type =(ParameterizedType) this.getClass().getGenericSuperclass();
        Class clazz = (Class)type.getActualTypeArguments()[0];

        //拼接成“泛型”Mapper字符串
        String localField = clazz.getSimpleName().substring(0,1).toLowerCase()+clazz.getSimpleName().substring(1)+"Mapper";

        //通过反射来获取成员变量的值
        Field field=this.getClass().getSuperclass().getDeclaredField(localField);
        Field baseField = this.getClass().getSuperclass().getDeclaredField("baseMapper");

        //将baseDao来进行实例化
        baseField.set(this, field.get(this));

        System.out.println("------this:" + this);
        System.out.println("------baseMapper:" + baseMapper);
    }

    public int insert(T entity) {
        return baseMapper.insert(entity);
    }

    public int insertSelective(T entity) {
        return baseMapper.insertSelective(entity);
    }

    public int deleteByPrimaryKey(String id) {
        return baseMapper.deleteByPrimaryKey(id);
    }

    public T selectByPrimaryKey(String id) {
        return baseMapper.selectByPrimaryKey(id);
    }

    public int updateByPrimaryKeySelective(T entity) {
        return baseMapper.updateByPrimaryKeySelective(entity);
    }

    public int updateByPrimaryKey(T entity) {
        return baseMapper.updateByPrimaryKey(entity);
    }

}

测试Spring和Mybatis是否整合完成

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"/application-context.xml"})
public class TestSpringAndMybatis {

    @Autowired
    private StoreHouseService hoseService;

    @Test
    public void add() {
        StoreHouse storeHouse = hoseService.selectByPrimaryKey("1");
        System.out.println(storeHouse);

    }


}

从零开始写项目第一篇【搭建环境】

编写BaseAction

/**
 * 将所有的service实现都定义出来,controller子类使用的使用就不需要定义了。
 */
public class BaseController {
    @Autowired
    protected StoreHouseService storeHoseService;

}

StoreHouseController

@Controller
@RequestMapping("/store")
public class StoreHouseController extends BaseController {

    @RequestMapping("/getById.do")
    public void getById(String id ) {
        StoreHouse storeHouse = storeHoseService.selectByPrimaryKey(id);
        System.out.println(storeHouse);
    }
}

测试spring-mvc

在测试的时候出现了: org.apache.ibatis.binding.BindingException: Invalid bound statement (not found) 的异常。

上网上查看之后, 。因此我就将StoreHouseMapper.xml放到resouces下了。

同时,我们的application-context.xml加载配置文件和generator.xml逆向配置文件的位置也要修改。

从零开始写项目第一篇【搭建环境】 说要把生成出来的mapper.xml放在resouces目录下才能识别出来

        <!--配置扫描式加载SQL映射文件,那么在mybatis配置文件中就不用加载了-->
        <property name="mapperLocations" value="classpath:mapper/*.xml"/>
        <!-- 所生成的sqlMap的影射文件的位置,默认资源包src -->
        <sqlMapGenerator targetPackage="mapper" targetProject="src/main/resources"/>

测试JSON

测试代码:

    @RequestMapping("/getById.do")
    @ResponseBody
    public Object getById(String id ) {
        StoreHouse storeHouse = storeHoseService.selectByPrimaryKey(id);
        System.out.println(storeHouse);

        return storeHouse;

    }

从零开始写项目第一篇【搭建环境】

开发环境总结

到目前为止、SSM已整合完成。

创建web常用的目录结构。

从零开始写项目第一篇【搭建环境】
  • Intellij idea
  • Spring 3.2.2
  • Mybatis3.4.5
  • mysql 5.1.34
  • Tomcat 7.0
  • jdk1.7

花了一个晚上总结出:不能太装逼去玩新的jar包、资料太少了,非常容易出错!

想用新版本的jar包遇到了很多的麻烦

  • 使用spring5.0与asm发生冲突,无法启动Tomcat,降为3.2.2
  • 使用Mysql 6.0在逆向工程的时候出现时区、无法创建表的问题,经过一轮解决,最后生成的SqlMapper只有insert语句。随后降为5.1.34
  • 使用JDK1.8有提示过时的错误,后来在pom加入一段配置解决。
  • 在初始化Spring容器的时候,无法创建对象。Spring3.2.2与JDK1.8发生冲突。随后降为JDK1.7
    • 在Intellij idea降JDK版本需要指定4个部分,详情可参见上面的连接。
原文  http://zhongfucheng.bitcron.com/post/javaeexiang-mu/cong-ling-kai-shi-xie-xiang-mu-di-yi-pian-da-jian-huan-jing
正文到此结束
Loading...