文章目录
springMVC与spring整合spring和mybatis整合spring的事务管理器逆向工程mybatis Generator分页插件mybatis pageHelper
springMVC与spring整合
springMVC是子容器,控制层框架,放Controller对象。
spring是父容器,平台性质的框架,放其他所有对象。
子容器持有父容器,可以调用父容器中的bean对象。
整合玩法1(不推荐):所有的bean全部放在springMVC容器对象。可以用,但springMVC框架的职责不清晰,它替代了spring的职责。
整合玩法2:把Controller对象,放springMVC容器,其他仍然放spring容器。aop切面一般都是织入到service对象。一个service方法是一个完整的业务逻辑,该方法可能会发起多个表的操作。
1.通过ContextLoaderListener监听器在tomcat启动时,加载spring.xml文件来初始化父容器对象,并且把父容器对象保存到了全局ServletContext对象。 2.通过DispatcherSerlvet在tomcat启动时,加载springmvc.xml文件来初始化子容器对象,并且从ServletCotnext中获取到监听器创建的父容器对象,子容器持有了父容器对象。持有的目的是为了获取父容器中的bean对象。 3.springMVC.xml中配置包扫描,仅识别Controller注解; 4.spring.xml配置包扫描,排除Controller注解。
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:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<mvc:annotation-driven></mvc:annotation-driven>
<mvc:default-servlet-handler></mvc:default-servlet-handler>
<context:component-scan base-package="com.javasm" use-default-filters="false">
<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:include-filter>
</context:component-scan>
<mvc:cors>
<mvc:mapping path="/**" allow-credentials="true" allowed-headers="*" allowed-methods="*" allowed-origins="*"/>
</mvc:cors>
</beans>
spring.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: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 https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.javasm">
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
</context:component-scan>
<aop:aspectj-autoproxy></aop:aspectj-autoproxy>
<import resource="classpath:mybatis-spring.xml"></import>
</beans>
spring和mybatis整合
加mybatis的环境,mysql驱动;Druid连接池;mybatis与spring整合包;spring-jdbc;spring-tx配置连接池bean对象。配置mybatis的核心对象SqlSessionFactory到容器中。jdbc.properties
jdbc.url = jdbc:mysql://127.0.0.1:3306/test?characterEncoding=UTF8&useSSL=true
jdbc.name = root
jdbc.pass = root
jdbc.driver = com.mysql.jdbc.Driver
mybatis-spring.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"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<bean class="com.alibaba.druid.pool.DruidDataSource" id="dataSource" init-method="init" destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.name}"></property>
<property name="password" value="${jdbc.pass}"></property>
</bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean" id="sessionFactory">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath:com/javasm/*/mapper/*.xml"></property>
<property name="configLocation" value="classpath:mybatis.xml"></property>
</bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.javasm.*.mapper"></property>
</bean>
<bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven></tx:annotation-driven>
</beans>
mybatis.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>
<settings>
<setting name="logImpl" value="STDOUT_LOGGING"/>
<setting name="mapUnderscoreToCamelCase" value="true"></setting>
</settings>
<typeAliases>
<package name="com.javasm"></package>
</typeAliases>
</configuration>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener
</listener-class>
</listener>
<context-param>
<param-name>contextConfigLocation
</param-name>
<param-value>classpath:spring.xml
</param-value>
</context-param>
<servlet>
<servlet-name>dispatcherServlet
</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<init-param>
<param-name>contextConfigLocation
</param-name>
<param-value>classpath:springmvc.xml
</param-value>
</init-param>
<load-on-startup>1
</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet
</servlet-name>
<url-pattern>/
</url-pattern>
</servlet-mapping>
<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>
</web-app>
spring的事务管理器
配置DataSourceTransactionManager事务管理器对象;做aop配置。声明式事务
事务注解
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:annotation-driven></tx:annotation-driven>
aop配置事务通知(了解)
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="insert*" propagation="REQUIRED"/>
<tx:method name="update*" propagation="REQUIRED"/>
<tx:method name="edit*" propagation="REQUIRED"/>
<tx:method name="del*" propagation="REQUIRED"/>
<tx:method name="delete*" propagation="REQUIRED"/>
<tx:method name="select*" read-only="true" propagation="SUPPORTS"></tx:method>
<tx:method name="*" rollback-for="Exception"></tx:method>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:pointcut id="servicePointcut" expression="execution(* com.javasm.*.service.*.*(..))"></aop:pointcut>
<aop:advisor advice-ref="txAdvice" pointcut-ref="servicePointcut"></aop:advisor>
</aop:config>
编程式事务
逆向工程mybatis Generator
mybatis Generator:通过该组件来从数据库表生成实体类,mapper接口,与映射文件的方法。导入jar包:
mybatis-generator-core-1.3.2.jarmysql-connector-java-5.1.34.jar generator.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="DB2Tables" targetRuntime="MyBatis3">
<commentGenerator>
<property name="suppressAllComments" value="true" />
</commentGenerator>
<jdbcConnection driverClass="com.mysql.jdbc.Driver" connectionURL="jdbc:mysql://localhost:3306/test" userId="root" password="root">
</jdbcConnection>
<javaTypeResolver>
<property name="forceBigDecimals" value="false" />
</javaTypeResolver>
<javaModelGenerator targetPackage="com.javasm.module1.entity" targetProject="E:\workspace\three\0804ssm\src">
<property name="enableSubPackages" value="true" />
<property name="trimStrings" value="true" />
</javaModelGenerator>
<sqlMapGenerator targetPackage="com.javasm.module1.mapper" targetProject="E:\workspace\three\0804ssm\src">
<property name="enableSubPackages" value="true" />
</sqlMapGenerator>
<javaClientGenerator type="XMLMAPPER" targetPackage="com.javasm.module1.mapper" targetProject="E:\workspace\three\0804ssm\src">
<property name="enableSubPackages" value="true" />
</javaClientGenerator>
<table tableName="myuser" domainObjectName="Myuser" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" />
</context>
</generatorConfiguration>
Generator.java
public class Generator {
public static void main(String
[] args
) throws Exception
{
List
<String> warnings
= new ArrayList<String>();
boolean overwrite
= true;
URL resource
= Generator
.class.getClassLoader().getResource("generator.xml");
String path
= resource
.getPath();
File configFile
= new File(path
);
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
);
}
}
目录结构
分页插件mybatis pageHelper
添加分页插件的jar包;
jsqlparser-0.9.5.jarpagehelper-5.0.0.jar 配置分页插件(mybatis-spring.xml中factorybean对象注入分页插件配置)。
<bean id="sessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="mapperLocations" value="classpath:com/javasm/*/mapper/*.xml"></property>
<property name="configLocation" value="classpath:mybatis.xml"></property>
<property name="plugins">
<array>
<bean class="com.github.pagehelper.PageInterceptor" id="pageInterceptor">
<property name="properties">
<value>reasonable=true
</value>
</property>
</bean>
</array>
</property>
</bean>
正常编写查询mapper在handler中加入分页条件
@PostMapping("selectMenu")
public ResponseEntity
selectMenu(@RequestBody Map
<String, Object> map
) throws InvocationTargetException
, IllegalAccessException
{
SysMenu sysMenu
= new SysMenu();
BeanUtils
.populate(sysMenu
, map
);
PageHelper
.startPage((Integer
) map
.get("pageNum"), (Integer
) map
.get("pageSize"));
List
<SysMenu> sysMenus
= menuService
.selectByInfo(sysMenu
);
PageInfo
<SysMenu> sysMenuPageInfo
= new PageInfo<SysMenu>(sysMenus
);
if (sysMenus
.size() != 0) {
return ResponseEntity
.ok(new ResponseBean(StatusEnum
.SUCCESS
, sysMenuPageInfo
));
} else {
throw new MyException(StatusEnum
.ERROR
);
}
}
PageInfo属性介绍