Java integrates crud and paging plug-in to operate mysql
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 :根据学生性别分页查询接口。2. Mybatis mapper.xml explanation (the following contents are all under the resources/com/qbian folder)
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:2, 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();Then let’s try passing the age field less:
3. Insert data
Before inserting data, let’s first take a look at what data is in the database:4. Query data
Query based on the ID of the previous dataWe have also queried the data we just inserted.
5. Update data
Update the queried data:Then we query the data again
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);Before paging query, we want to import more test data.
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!

Javadevelopmentisnotentirelyplatform-independentduetoseveralfactors.1)JVMvariationsaffectperformanceandbehavioracrossdifferentOS.2)NativelibrariesviaJNIintroduceplatform-specificissues.3)Filepathsandsystempropertiesdifferbetweenplatforms.4)GUIapplica

Java code will have performance differences when running on different platforms. 1) The implementation and optimization strategies of JVM are different, such as OracleJDK and OpenJDK. 2) The characteristics of the operating system, such as memory management and thread scheduling, will also affect performance. 3) Performance can be improved by selecting the appropriate JVM, adjusting JVM parameters and code optimization.

Java'splatformindependencehaslimitationsincludingperformanceoverhead,versioncompatibilityissues,challengeswithnativelibraryintegration,platform-specificfeatures,andJVMinstallation/maintenance.Thesefactorscomplicatethe"writeonce,runanywhere"

Platformindependenceallowsprogramstorunonanyplatformwithoutmodification,whilecross-platformdevelopmentrequiressomeplatform-specificadjustments.Platformindependence,exemplifiedbyJava,enablesuniversalexecutionbutmaycompromiseperformance.Cross-platformd

JITcompilationinJavaenhancesperformancewhilemaintainingplatformindependence.1)Itdynamicallytranslatesbytecodeintonativemachinecodeatruntime,optimizingfrequentlyusedcode.2)TheJVMremainsplatform-independent,allowingthesameJavaapplicationtorunondifferen

Javaispopularforcross-platformdesktopapplicationsduetoits"WriteOnce,RunAnywhere"philosophy.1)ItusesbytecodethatrunsonanyJVM-equippedplatform.2)LibrarieslikeSwingandJavaFXhelpcreatenative-lookingUIs.3)Itsextensivestandardlibrarysupportscompr

Reasons for writing platform-specific code in Java include access to specific operating system features, interacting with specific hardware, and optimizing performance. 1) Use JNA or JNI to access the Windows registry; 2) Interact with Linux-specific hardware drivers through JNI; 3) Use Metal to optimize gaming performance on macOS through JNI. Nevertheless, writing platform-specific code can affect the portability of the code, increase complexity, and potentially pose performance overhead and security risks.

Java will further enhance platform independence through cloud-native applications, multi-platform deployment and cross-language interoperability. 1) Cloud native applications will use GraalVM and Quarkus to increase startup speed. 2) Java will be extended to embedded devices, mobile devices and quantum computers. 3) Through GraalVM, Java will seamlessly integrate with languages such as Python and JavaScript to enhance cross-language interoperability.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

EditPlus Chinese cracked version
Small size, syntax highlighting, does not support code prompt function

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.
