SSM——查询_分页
Posted 蓉啊
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SSM——查询_分页相关的知识,希望对你有一定的参考价值。
项目结构:
项目截图:
第一步:配置pom.xml文件导入相应的包
<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/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.ssm</groupId> <artifactId>ssm-crud</artifactId> <version>0.0.1-SNAPSHOT</version> <packaging>war</packaging> <!-- 引入项目依赖的jar包 --> <!-- 1.SpringMVC和Sping --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc --> <dependencies> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!-- 2.Spring-JDBC --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-jdbc --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.3.7.RELEASE</version> </dependency> <!-- Spring-test 单元测试--> <!-- https://mvnrepository.com/artifact/org.springframework/spring-test --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.3.7.RELEASE</version> <scope>test</scope> </dependency> <!-- 3.Spring 面向切面编程 --> <!-- https://mvnrepository.com/artifact/org.springframework/spring-aspects --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>4.3.7.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.8.RELEASE</version> </dependency> <!-- 4.Mybatis --> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.4.2</version> </dependency> <!-- https://mvnrepository.com/artifact/org.mybatis.generator/mybatis-generator-core --> <dependency> <groupId>org.mybatis.generator</groupId> <artifactId>mybatis-generator-core</artifactId> <version>1.3.5</version> </dependency> <!-- 5.Mybatis整合Spring的适配包 --> <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis-spring --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.3.1</version> </dependency> <!-- 数据库连接池 驱动 --> <!-- https://mvnrepository.com/artifact/c3p0/c3p0 --> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.2</version> </dependency> <!-- 配置c3p0必要的包 --> <!-- https://mvnrepository.com/artifact/com.mchange/mchange-commons-java --> <dependency> <groupId>com.mchange</groupId> <artifactId>mchange-commons-java</artifactId> <version>0.2.3.4</version> </dependency> <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.27</version> </dependency> <!-- 其他包 jstl servlet-api junit --> <!-- https://mvnrepository.com/artifact/jstl/jstl --> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <!-- <dependency> <groupId>javax.servlet</groupId> <artifactId>servlet-api</artifactId> <version>2.5</version> <scope>provided</scope> </dependency> --> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.0.1</version> <scope>provided</scope> </dependency> <!-- https://mvnrepository.com/artifact/junit/junit --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> <scope>test</scope> </dependency> <!-- 引入分页插件 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.0.0</version> </dependency> </dependencies> <build/> </project>
第二步:配置Spring,SpringMVC以及Mybatis的配置文件
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"> <!-- 1.启动Spring的容器 --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!--②负责启动spring容器的监听器,它将使用①处的上下文参数获得spring配置文件地址--> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 2.SpringMVC的前端控制器 拦截所有请求 --> <servlet> <servlet-name>dispatch</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <!-- 未指定SpringMVC的配置文件,所以在与web同级文件下建立一个与servlet-name同名+servlet的xml文件 --> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:dispatch-servlet.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatch</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 3.字符编码过滤器 放在所有过滤器前--> <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> <init-param> <param-name>forceRequestEncoding</param-name> <param-value>true</param-value> </init-param> <init-param> <param-name>forceResponseEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>CharacterEncodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 4.使用REST风格的URI --> <!-- 配置org.springframework.web.filter.HiddenHttpMethodFilter:可以把PUT请求转为DELETE或POST请求 --> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <!-- 过滤所有请求 --> <url-pattern>/*</url-pattern> </filter-mapping> <!-- 使页面ajax成功发put请求 在Spring MVC过滤器-HiddenHttpMethodFilter中我们提到, jsp或者说html中的form的method值只能为post或get,我们可以通过HiddenHttpMethodFilter获取put表单中的参数-值, 而在Spring3.0中获取put表单的参数-值还有另一种方法,即使用HttpPutFormContentFilter过滤器。 HttpPutFormContentFilter过滤器的作为就是获取put表单的值,并将之传递到Controller中标注了method为RequestMethod.put的方法中。 --> <filter> <filter-name>HttpPutFormContentFilter</filter-name> <filter-class>org.springframework.web.filter.HttpPutFormContentFilter</filter-class> </filter> <filter-mapping> <filter-name>HttpPutFormContentFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping> </web-app>
applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> <!--Spring的配置文件 :主要配置和逻辑业务有关的--> <!-- 扫描包 --> <context:component-scan base-package="com.ssm"> <!-- 不扫描@Controller注解 --> <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 引入外部配置文件 --> <context:property-placeholder location="classpath:dbconfig.properties"/> <!-- ==================数据源,事务控制 ========================--> <bean id="pooledDataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"> <property name="jdbcUrl" value="${jdbc.jdbcUrl}"></property> <property name="driverClass" value="${jdbc.jdbcdriverClass}"></property> <property name="user" value="${jdbc.user}"></property> <property name="password" value="${jdbc.password}"></property> </bean> <!-- ========================配置和Mybatis的整合 =============================--> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <!-- 指定Mybatis全局配置文件的位置 --> <property name="configLocation" value="classpath:mybatis-config.xml"></property> <property name="dataSource" ref="pooledDataSource"></property> <!-- 指定mybatis.mapper文件的位置 --> <property name="mapperLocations" value="classpath:mapper/*.xml"></property> </bean> <!-- 配置扫描器,将mybatis接口的实现加入到ioc容器中 --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- 扫描所有dao接口的实现,加入到ioc容器 --> <property name="basePackage" value="com.ssm.dao"></property> </bean> <!-- ==================事务控制==================== --> <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <!-- 控制数据源 --> <property name="dataSource" ref="pooledDataSource"></property> </bean> <!-- 开启使用xml配置形式的事务 --> <aop:config> <!-- 切入点表达式 --> <aop:pointcut expression="execution(* com.ssm.service.*.*(..))" id="txPoint"/> <!-- 配置事务增强 --> <aop:advisor advice-ref="txAdvice" pointcut-ref="txPoint"/> </aop:config> <!-- 配置事务增强,事务如何切入 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <!-- 所有方法都是事务方法 --> <tx:method name="*"></tx:method> <!--以get开头的所有方法--> <tx:method name="get*" read-only="true"></tx:method> </tx:attributes> </tx:advice> <!-- Spring配置文件的核心点:数据源,与mybatis的整合,事务控制 --> <!-- 配置一个可以批量的执行sqlSession --> <bean id="sqlSession" class="org.mybatis.spring.SqlSessionTemplate"> <constructor-arg name="sqlSessionFactory" ref="sqlSessionFactory"></constructor-arg> <!-- 执行器类型,批量-batch --> <constructor-arg name="executorType" value="BATCH"></constructor-arg> </bean> </beans>
给数据源配置的数据库配置文件dbconfig.properties
jdbc.jdbcUrl=jdbc:mysql://localhost:3306/ssm jdbc.jdbcdriverClass=com.mysql.jdbc.Driver jdbc.user=root jdbc.password=123
SpringMVC的配置文件dispatch-servlet.xml,本来这个文件应该在WEB-INF下的,在后面搭载上tomcat后报错找不到此文件,所以放到类路径下来了。
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:tx="http://www.springframework.org/schema/tx" xsi:schemaLocation=" http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-mvc-4.3.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd"> <!--SpringMVC的配置文件 :主要包含网站跳转的控制,配置--> <context:component-scan base-package="com.ssm" use-default-filters="false"> <!-- 扫描@Controller注解 不扫描用exclude --> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" /> </context:component-scan> <!-- 配置视图解析器 方便页面返回 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- spring中加入jstl标签库 --> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"></property> <!-- 前缀 --> <property name="prefix" value="/WEB-INF/views/"></property> <!-- 后缀 --> <property name="suffix" value=".jsp"></property> </bean> <!-- 两个标准配置 --> <!-- 将SpringMVC不能处理的请求交给tomcat --> <mvc:default-servlet-handler></mvc:default-servlet-handler> <!-- 能支持SpringMVC更高级的一些功能 JSR303的校验,快捷的ajax,映射动态请求--> <mvc:annotation-driven></mvc:annotation-driven> </beans>
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> <!-- 开启自动驼峰命名规则(camel case)映射, 即从经典数据库列名 A_COLUMN 到经典 Java 属性名 aColumn 的类似映射。 --> <settings> <setting name="mapUnderscoreToCamelCase" value="true" /> </settings> <!-- 类型别名 自定义别名name为类所在的包路径--> <typeAliases> <package name="com.ssm.bean"></package> </typeAliases> <!-- 分页的配置 --> <plugins> <!-- com.github.pagehelper为PageHelper类所在包名 --> <plugin interceptor="com.github.pagehelper.PageInterceptor"> <!-- 使用下面的方式配置参数,后面会有所有的参数介绍 --> <!-- <property name="param1" value="value1"/> --> </plugin> </plugins> </configuration>
第三步:配置一个mbg.xml文件与pom.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/ssm" userId="root" password="123"> </jdbcConnection> <javaTypeResolver > <property name="forceBigDecimals" value="false" /> </javaTypeResolver> <!-- 指定javabean生成的位置 --> <javaModelGenerator targetPackage="com.ssm.bean" targetProject=".\\src\\main\\java"> <property name="enableSubPackages" value="true" /> <property name="trimStrings" value="true" /> </javaModelGenerator> <!-- 指定sql映射文件生成的位置 --> <sqlMapGenerator targetPackage="mapper" targetProject=".\\src\\main\\resources"> <property name="enableSubPackages" value="true" /> </sqlMapGenerator> <!-- 指定dao接口生成的位置,mapper接口 --> <javaClientGenerator type="XMLMAPPER" targetPackage="com.ssm.dao" targetProject=".\\src\\main\\java"> <property name="enableSubPackages" value="true" /> </javaClientGenerator> <!-- 指定每个表的 生成策略--> <table tableName="emp" domainObjectName="Employee" > </table> <table tableName="dept" domainObjectName="Department" > </table> </context> </generatorConfiguration>
第四步:建立一个MBGTest.java的文件运行后会自动生成bean,dao包下的文件,以及mapper下的xml文件
package com.ssm.test; import java.io.File; import java.io.IOException; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; import org.mybatis.generator.api.MyBatisGenerator; import org.mybatis.generator.config.Configuration; import org.mybatis.generator.config.xml.ConfigurationParser; import org.mybatis.generator.exception.InvalidConfigurationException; import org.mybatis.generator.exception.XMLParserException; import org.mybatis.generator.internal.DefaultShellCallback; //自动生成了bean下的文件以及dao下的,还有mapper下的xml文件 public class MBGTest { public static void main(String[] args) throws IOException, XMLParserException, InvalidConfigurationException, SQLException, InterruptedException { List<String> warnings = new ArrayList<String>(); boolean overwrite = true; File configFile = new File("mbg.xml"); 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); } }
第五步:因为是两个表的查询,所以需要在生成的文件中添加多表查询的功能。
DepartmentMapper.java中
//====================新定义的两个查询,多表联查======================== List<Employee> selectByExampleWithDept(EmployeeExample example); Employee selectByPrimaryKeyWithDept(Integer empId); //===========================================================
EmployeeMapper.xml
<!-- ===========新增多表查询============= --> <sql id="WithDept_Column_List"> e.emp_id, e.emp_name, e.gender, e.email, e.d_id,d.dept_id,d.dept_name </sql> <resultMap id="WithDeptResultMap" type="com.ssm.bean.Employee"> <id column="emp_id" jdbcType="INTEGER" property="empId" /> <result column="emp_name" jdbcType="VARCHAR" property="empName" /> <result column="gender" jdbcType="CHAR" property="gender" /> <result column="email" jdbcType="VARCHAR" property="email" /> <result column="d_id" jdbcType="INTEGER" property="dId" /> <!-- 指定联合查询的部门字段的封装 --> <association property="department" javaType="com.ssm.bean.Department"> <id column="dept_id" jdbcType="INTEGER" property="deptId" /> <result column="dept_name" jdbcType="VARCHAR" property="deptName" /> </association> </resultMap> <!-- 带条件的多表查询 --> <select id="selectByExampleWithDept" resultMap="WithDeptResultMap"> select <if test="distinct"> distinct </if> <include refid="WithDept_Column_List" /> FROM emp e LEFT JOIN dept d ON e.d_id=d.dept_id <if test="_parameter != null"> <include refid="Example_Where_Clause" /> </if> <if test="orderByClause != null"> order by ${orderByClause} </if> </select> <!-- 按主键多表查询 --> <select id="selectByPrimaryKeyWithDept" resultMap="WithDeptResultMap"> select <include refid="WithDept_Column_List" /> FROM emp e LEFT JOIN dept d ON e.d_id=d.dept_id where emp_id = #{empId,jdbcType=INTEGER} </select> <!-- =================================================== -->
EmployeeService.java
package com.ssm.service; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import com.ssm.bean.Employee; import com.ssm.dao.EmployeeMapper; //业务逻辑组件 @Service public class EmployeeService { @Autowired//自动注入 EmployeeMapper employeeMapper; public List<Employee> getAll(){ return employeeMapper.selectByExampleWithDept(null); } }
EmployeeController.java
package com.ssm.controller; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import com.github.pagehelper.PageHelper; import com.github.pagehelper.PageInfo; import com.ssm.bean.Employee; import com.ssm.service.EmployeeService; //处理员工crud @Controller public class EmployeeController { @Autowired EmployeeService employeeService; @RequestMapping("/emps") // 默认值为第一页数据 public String getEmps( @RequestParam(value = "pn", defaultValue = "1") Integer pn, Model model) { // 引入PageHelper分页插件 // 在查询之前只需要调用 pn=第几页,5=每页多少条 PageHelper.startPage(pn, 3); // startPage后紧跟的查询就是一个分页查询 List<Employee> emps = employeeService.getAll(); // pageinfo包装查询后的结果,只需要pageinfo交给页面,封装了详细的信息 // 5=传入分页连以上是关于SSM——查询_分页的主要内容,如果未能解决你的问题,请参考以下文章