This article mainly introduces the detailed steps of Spring mvc integrating mybatis (crud + paging plug-in) to operate mysql. Friends in need can refer to the following
1. Web.xml configuration
We all know that the first thing to do when starting a Java ee project is to read web.xml. I also explained the web.xml of spring mvc in detail in the previous article. No. If you understand, you can look back. I will also put the source code of the project I explained on github. You can also go there to have a look. I will not introduce it here.
web.xml configuration
<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:/context.xml</param-value> </context-param> <!-- 监听器:启动服务器时,启动 spring --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- spring 核心控制器 --> <servlet> <servlet-name>dispatcherServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:external-servlet.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> <!-- 编码过滤器 --> <filter> <filter-name>encodingFilter</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>forceEncoding</param-name> <param-value>true</param-value> </init-param> </filter> <filter-mapping> <filter-name>encodingFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
2. spring (context.xml) context configuration
This configuration File can be said to be the second one to be read by the server container. Here, the basic package path scanned during spring startup, the import of the attribute file of the external configuration, and the configuration of the database that needs to be connected are configured. , the integration of mybatis and spring, the mybatis date plug-in and paging plug-in we mentioned at the beginning are also configured here, and the location of the entity package and its mapper file scanned by mybatis.
context.xml configuration
<!-- spring 扫描的基础包路径 --> <context:component-scan base-package="com.qbian" /> <!-- jdbc properties --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" p:location="classpath:jdbc.properties" /> <!-- define the datasource (这里用的是c3p0的数据看连接池,性能不是很好,可以唤其它更好的连接池[jdbc pool等])--> <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" destroy-method="close"> <property name="driverClass" value="${jdbc.driverClassName}" /> <property name="jdbcUrl" value="${jdbc.url}" /> <property name="user" value="${jdbc.username}" /> <property name="password" value="${jdbc.password}" /> </bean> <!-- define the SqlSessionFactory --> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <property name="typeAliasesPackage" value="com.qbian.**.dto" /> <property name="plugins"> <list> <!-- 配置自己实现的日期插件 --> <bean class="com.qbian.common.plugin.DatePlugin" /> <!-- 分页插件 --> <bean class="com.qbian.common.plugin.PagePlugin" /> </list> </property> </bean> <!-- scan for mappers and let them be autowired --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <property name="basePackage" value="com.qbian.**.dao" /> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /> </bean> <!-- 将多个配置文件读取到容器中,交给Spring管理 --> <bean id="configProperties" class="com.qbian.common.plugin.PropertiesConfigurer"> <property name="locations"> <list> <!--<value>classpath:redis.properties</value>--> </list> </property> </bean>
3. spring controller configuration
The location of the controller is configured here , and its supported request types and encodings.
external-servlet.xml configuration
<!-- 控制器扫描 --> <context:component-scan base-package="com.qbian.common.controller" /> <mvc:annotation-driven> <mvc:message-converters> <bean class="org.springframework.http.converter.StringHttpMessageConverter"> <property name="supportedMediaTypes"> <list> <value>text/html;charset=UTF-8</value> </list> </property> <property name="writeAcceptCharset" value="false" /> </bean> </mvc:message-converters> </mvc:annotation-driven>
The configuration information is the above three, let’s take a look at the specific code,
##four , Code explanation
1. Java code explanation, the following is not sorted, just arranged in the order displayed inEditor. (The following contents are all under the java.com.qbian package)
common | annotation | @interface Now : 插入|更新数据的日期注解。 @interface UUID :插入数据的uuid注解。 controller | ExternalController.class :核心控制器,拦截所有请求,异常处理,跨域设置等功能。 dao | interface StudentDao :使用例子,crud 共通方法。 dto | PageInfoDto.class :分页使用的基础dto对象。 ResponseDto.class :响应数据的基本模型。 entity | Student.class :使用例子,自定义注解的使用。 enums | enum MessageEnum :统一的返回状态码及描述信息。 exception | ExternalServiceException.class :自定义异常,业务相关都抛出该异常对象。 factory | BeanFactoryUtil.class :根据bean name获取spring管理的bean实例。 hadle | ExceptionHandle.class :spring自带的统一异常捕获处理。 plugin | DatePlugin.class :自定义mybatis日期插件。 PagePlugin.class :自定义mybatis分页插件。 PropertiesConfigurer.class :将外部配置的属性文件读取到 spring 容器中统一管理。 service | interface IbaseServie :基础的service接口。 BaseService.class :基础的service抽象类。 TokenService.class :鉴权token服务类。 util | CheckUtil.class :请求信息校验相关工具类。 DateUtil.class :日期相关工具类。 ResponseUtil.class :响应信息工具类。 SecondsFormatSerializer.class :java.util.Date类型转时间戳工具类。 TimestampSecondsFormatSerializer.class :java.sql.Timestamp类型转时间戳工具类。 StringUtil.class :字符串相关工具类。 other | dao | interface StudentExtDao :使用例子,业务相关crud操作。 dto | QueryStudentSexPageDto.class :根据学生性别分页查询返回对象dto。 StudentPageDto.class :根据学生性别分页查询封装的对象。 service | AddStudentService.class :插入学生数据接口。 DeleteStudentService.class :删除学生数据接口。 FindStudentService.class :查询学生数据接口。 UpdateStudentService.class :更新学生数据接口。 QueryStudentBySexService.class :根据学生性别分页查询接口。
common | dao | StudentDao.xml :对应common.dao.StudentDao接口。 other | dao | StudentExtDao.xml :对应other.dao.StudentExtDao接口。
5. Function demonstration
1. Token verification
I have written the token here in the code, 123456 Indicates that the verification is successful. Let’s test it first using the insert data interface and pass an incorrect token, as shown below: Authorization token verification2, Request parametersVerification
Let’s take a look at what values need to be verified when inserting the data interface.// 校验请求参数 CheckUtil.checkEmpty(params, "token", "sex", "age"); // 校验 token tokenService.checkUserLogin(params.getString("token")); Student student = JSONObject.parseObject(params.toJSONString(), Student.class); studentDao.insert(student); return ResponseUtil.success();
3. Insert data
Before inserting data, let’s first take a look at what data is in the database: Initialize the values in the databaseFrom above As can be seen from the figure, there is no data in the database. Let's execute the insertion interface. Test the insertion interfaceLet’s take a look at the database:After calling the insertion interfaceThe database already has data.4. Query data
Query based on the ID of the previous dataCall the query interfaceWe have also queried the data we just inserted.
5. Update data
Update the queried data:Call the update interfaceThen we query the data againAfter updating, query againYou can see that the gender and age have been updated, and the update date is also The latest.
6. Paging query
Let’s take a look at the code first:// 校验请求参数 CheckUtil.checkEmpty(params, "token", "sex", "pageNo", "pageSize"); // 校验 token tokenService.checkUserLogin(params.getString("token")); // 根据性别分页查询 Student,查询总数会自动封装到pageDto对象上 QueryStudentSexPageDto pageDto = JSONObject.parseObject(params.toJSONString(), QueryStudentSexPageDto.class); List<Student> students = studentExtDao.queryBySexWithPage(pageDto); StudentPageDto studentPageDto = new StudentPageDto(); // 查询总数会自动封装到pageDto对象上 studentPageDto.setTotalSize(pageDto.getTotalSize()); studentPageDto.setStudents(students); return ResponseUtil.success(studentPageDto);
Test data before pagination
You can see that the database currently has ten test data, including six for boys, ranging in age from 19 to 24. Okay, let’s start calling the paging query interface:
Call the paging query interface to return the results
Format the returned data:
Paging query return results sorting
This is the same as what we see when directly querying the database.
7. Delete data
The last step is to delete the data interface. We will delete the first test data.
Call the delete interface to return the result
Then we check whether it is really deleted.
Query after deletion
The data has been deleted.
Finally, the project source code is attached: github.com/Qbian61/spring-mvc-mybatis
[Related recommendations]
2. Comprehensive analysis of Java annotations
3. Alibaba Java Development Manual
The above is the detailed content of Java integrates crud and paging plug-in to operate mysql. For more information, please follow other related articles on the PHP Chinese website!