配置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个部分,详情可参见上面的连接。