ssm整合

    科技2025-04-19  12

    文章目录

    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> <!--全局包扫描,只扫描controller注解--> <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"> <!--全局包扫描,排除controller注解--> <context:component-scan base-package="com.javasm"> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter> </context:component-scan> <!--aop织入--> <aop:aspectj-autoproxy></aop:aspectj-autoproxy> <!--加载mybatis-spring的配置文件--> <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"> <!--加载jdbc资源文件--> <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder> <!--配置数据源对象,使用druid连接池--> <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> <!--创建全局的sqlsessionfactory对象(数据源,映射文件,别名、驼峰映射等其他配置)--> <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> <!--对mapper接口创建代理对象,加入容器--> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.javasm.*.mapper"></property> </bean> <!--配置spring的事务管理器对象(打开会话,提交会话,回滚,关闭)--> <bean class="org.springframework.jdbc.datasource.DataSourceTransactionManager" id="transactionManager"> <property name="dataSource" ref="dataSource"></property> </bean> <!--通过事务通知,把事务管理器织入到带有@Transactional注解的方法--> <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"> <!--通过ContextLoaderListener监听器在tomcat启动时,加载spring.xml文件来初始化父容器对象--> <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> <!--通过DispatcherSerlvet在tomcat启动时,加载springmvc.xml文件来初始化子容器对象,--> <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> <!--通过事务通知,把事务管理器织入到带有@Transactional注解的方法--> <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> <!-- 数据库链接URL、用户名、密码 --> <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> <!-- 生成DAO的包名和位置 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.javasm.module1.mapper" targetProject="E:\workspace\three\0804ssm\src"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 要生成那些表(更改tableName和domainObjectName就可以) --> <table tableName="myuser" domainObjectName="Myuser" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" /> <!-- <table tableName="course_info" domainObjectName="CourseInfo" enableCountByExample="false" enableUpdateByExample="false" enableDeleteByExample="false" enableSelectByExample="false" selectByExampleQueryId="false" /> --> <!-- <table tableName="course_user_info" domainObjectName="CourseUserInfo" 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对象注入分页插件配置)。 <!--创建全局的sqlsessionfactory对象(数据源,映射文件,别名、驼峰映射等其他配置)--> <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"));// 1 List<SysMenu> sysMenus = menuService.selectByInfo(sysMenu); // 把分页信息及数据装载进PageInfo对象 PageInfo<SysMenu> sysMenuPageInfo = new PageInfo<SysMenu>(sysMenus); // 2 if (sysMenus.size() != 0) { return ResponseEntity.ok(new ResponseBean(StatusEnum.SUCCESS, sysMenuPageInfo)); } else { throw new MyException(StatusEnum.ERROR); } } PageInfo属性介绍
    Processed: 0.011, SQL: 8