Reverse Engineering and Paging Application in ssm

Posted by phpnoobie on Fri, 10 May 2019 19:39:24 +0200

Yesterday, the mybatis reverse engineering and paging applications in spring boot were sorted out. Today, the reverse engineering and paging applications in ssm project are sorted out.
Project running environment: eclipse+jdk1.8+maven+tomcat

Building ssm project

First, create a new maven project, project Archetype selection: maven-archetype-webapp, project completion, there will be generated index.jsp error.
Cause: The project does not rely on javax.servlet related class packages, which are in the tomcat class library
There are two solutions:
Method 1: Adding dependencies

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>servlet-api</artifactId>
    <version>2.5</version>
</dependency>

Method 2: Depending on the tomcat class library, if eclipse already has a tomcat server
Right-click the project in turn - > build path - > configure build path - > Libraries - > Add Libraries - > Server Runtime - > select tomcat server lib - > OK
Dependencies are added successively when the project is completed. The code is as follows:

<properties>
    <spring.version>4.3.7.RELEASE</spring.version>
</properties>

<dependencies>
    <!-- unit testing -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <!-- Solve new problems jsp Document error reporting -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>

    <!-- spring package -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-beans</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-tx</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
        <scope>test</scope>
    </dependency>

    <!-- mybatis -->
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>3.4.2</version>
    </dependency>

    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>1.3.1</version>
    </dependency>

    <!--  paging -->
    <dependency>
        <groupId>com.github.pagehelper</groupId>
        <artifactId>pagehelper</artifactId>
        <version>5.1.2</version>
    </dependency>

    <!-- data base -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.37</version>
    </dependency>

    <!-- c3p0 Connection pool -->
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>
</dependencies>

maven install downloads dependency packages.
Add the file jdbc.properties under the src/main/resources folder, as follows:

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://127.0.0.1:3306/test?useUnicode=true&characterEncoding=utf8
jdbc.username=root
jdbc.password=123456    

Add the file mybatis-config.xml under the src/main/resources folder, as follows:

<?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>
    <!-- Configure global properties -->
    <settings>
        <!-- Use jdbc Of getGeneratedKeys Getting database self-increasing primary key values -->
        <setting name="useGeneratedKeys" value="true" />

        <!-- Replace column aliases by default with column labels:true -->
        <setting name="useColumnLabel" value="true" />

        <!-- Open Hump Naming Conversion:Table{create_time} -> Entity{createTime} -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
</configuration>

Add the folder spring under the src/main/resources folder and the file spring-dao.xml in spring, as follows:

<?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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd">
    <!-- Configuration integration mybatis process -->
    <!-- 1.Configure database related parameters properties Properties: ${url} -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!-- 2.Database connection pool -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- Configure connection pool properties -->
        <property name="driverClass" value="${jdbc.driver}" />
        <property name="jdbcUrl" value="${jdbc.url}" />
        <property name="user" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <!-- c3p0 Private properties of connection pools -->
        <property name="maxPoolSize" value="30" />
        <property name="minPoolSize" value="10" />
        <!-- Not automatically after closing the connection commit -->
        <property name="autoCommitOnClose" value="false" />
        <!-- Get connection timeout -->
        <property name="checkoutTimeout" value="10000" />
        <!-- Number of retries when connection acquisition fails -->
        <property name="acquireRetryAttempts" value="2" />
    </bean>
    
    <!-- 3.To configure SqlSessionFactory object -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- Injecting database connection pool -->
        <property name="dataSource" ref="dataSource" />
        <!-- To configure MyBaties Global Profile:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <!-- scanning entity Packages use aliases -->
        <property name="typeAliasesPackage" value="com.luis.entity" />
        <!-- scanning sql configuration file:mapper Needed xml file -->
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>

    <!-- 4.Configuration scan Dao Interface package, dynamic implementation Dao Interface, injected into spring Container -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- injection sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <!-- Give the need to scan Dao Interface package -->
        <property name="basePackage" value="com.luis.mapper" />
    </bean>
</beans>

Add spring-service.xml to spring, the code is as follows:

<?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
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- scanning service All types of annotations used under the package -->
    <context:component-scan base-package="com.luis.service" />

    <!-- Configuring Transaction Manager -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- Injecting database connection pool -->
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- Configuring annotation-based declarative transactions -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

Add spring-web.xml to spring, the code is as follows:

<?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:mvc="http://www.springframework.org/schema/mvc"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd
    http://www.springframework.org/schema/context
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/mvc
    http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
    <!-- To configure SpringMVC -->
    <!-- 1.open SpringMVC Annotation mode -->
    <mvc:annotation-driven />

    <!-- 2.Static resource default servlet To configure (1)Add processing of static resources: js,gif,png (2)Permitted use"/"Making global mapping -->
    <mvc:resources mapping="/resources/**" location="/resources/" /> 
    <mvc:default-servlet-handler />

    <!-- 3.Define View Parser -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property> 
        <property name="suffix" value=".jsp"></property>
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView" />
    </bean>
    <!-- 4.scanning web Dependent bean -->
    <context:component-scan base-package="com.luis.web" />
</beans>

Modify the web.xml file with the following code:

<web-app>
    <servlet>
        <servlet-name>spring-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/spring-*.xml</param-value>
        </init-param>
    </servlet>

    <servlet-mapping>
        <servlet-name>spring-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
        <welcome-file>index.html</welcome-file>
    </welcome-file-list>
</web-app>

So far, the ssm project has been completed!

Reverse Engineering and Paging Application

Firstly, the reverse engineering project is imported. See the specific use method for reference: My github
This paper still applies the database of the previous part. The table of the database is as follows:

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` bigint(20) NOT NULL,
  `name` varchar(255) NOT NULL,
  `age` int(4) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;

INSERT INTO `user` VALUES ('1', 'wanger', '22');
INSERT INTO `user` VALUES ('2', 'zhangsan', '18');
INSERT INTO `user` VALUES ('3', 'lisi', '23');
INSERT INTO `user` VALUES ('4', 'wangwu', '21');

Running file generates mapper interface, entity class and xml file.
Paging has added dependencies that can be applied directly.

<dependency>
    <groupId>com.github.pagehelper</groupId>
    <artifactId>pagehelper</artifactId>
    <version>5.1.2</version>
</dependency>

Additionally, in the SqlSessionFactory bean of the SPRING-DAO.XML file, add:

<property name="plugins">
    <array>
        <bean class="com.github.pagehelper.PageInterceptor">
            <property name="properties">
                <value>
                <!-- helperDialect: Different from 3.0+Version, now must be helperDialect,otherwise spring Error reporting when starting load -->
                    helperDialect=mysql
                </value>
            </property>
        </bean>
    </array>
</property>

Write the service layer, UserService code as follows:

public interface UserService {
    User selectByName(String name);
    List<User> findAllUser(int pageNum, int pageSize);
}

The UserService Impl code is as follows:

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    public User selectByName(String name) {
        UserExample example = new UserExample();
        Criteria criteria = example.createCriteria();
        criteria.andNameEqualTo(name);
        List<User> users = userMapper.selectByExample(example);
        if (users != null && users.size() > 0) {
            return users.get(0);
        }
        return null;
    }

    /**
     * pageNum Start page number
     * pageSize Number of data bars displayed per page
     */
    public List<User> findAllUser(int pageNum, int pageSize) {
        //Paging by passing parameters to the method
        PageHelper.startPage(pageNum, pageSize);
        UserExample example = new UserExample();
        List<User> list = userMapper.selectByExample(example);
        return list;
    }
}

Write the web layer, UserController code as follows:

@Controller
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @ResponseBody
    @RequestMapping("/test")
    public String querUserByName() {
        User user = userService.selectByName("wanger");
        System.out.println(user.toString());
        return "index";
    }
    
    @RequestMapping("/list")
    public String querUser() {
        List<User> list = userService.findAllUser(1, 2);
        //Getting Paging Information
        PageInfo<User> pageInfo = new PageInfo<User>(list);
        System.out.println(list.toString());
        System.out.println("total:" + pageInfo.getTotal());
        System.out.println("pages:" + pageInfo.getPages());
        System.out.println("pageSize:" + pageInfo.getPageSize());
        return "index";
    }
}

test

Deploy the project to tomcat, start, visit http://localhost:8080/ssm-demo/test, run the results:

User [id=1, name=wang1er, age=22]

Reverse Engineering and ssm Project Build Successfully!
Visit http://localhost:8080/ssm-demo/list and run the results:

Page{count=true, pageNum=1, pageSize=2, startRow=0, endRow=2, total=4, pages=2, reasonable=false, pageSizeZero=false}
total:4
pages:2
pageSize:2

The pit encountered here: plugins are added to many examples on the Internet, and errors occur during paging:

warning: Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in file [E:\code\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ssm-demo\WEB-INF\classes\spring\spring-dao.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.Object[]' to required type 'org.apache.ibatis.plugin.Interceptor[]' for property 'plugins'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'com.github.pagehelper.PageHelper' to required type 'org.apache.ibatis.plugin.Interceptor' for property 'plugins[0]': no matching editors or conversion strategy found
//September 06, 2018 10:51 p.m. org. spring framework. web. servlet. Dispatcher Servlet init Servlet Bean
//Serious: Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sqlSessionFactory' defined in file [E:\code\eclipse-workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\ssm-demo\WEB-INF\classes\spring\spring-dao.xml]: Initialization of bean failed; nested exception is org.springframework.beans.ConversionNotSupportedException: Failed to convert property value of type 'java.lang.Object[]' to required type 'org.apache.ibatis.plugin.Interceptor[]' for property 'plugins'; nested exception is java.lang.IllegalStateException: Cannot convert value of type 'com.github.pagehelper.PageHelper' to required type 'org.apache.ibatis.plugin.Interceptor' for property 'plugins[0]': no matching editors or conversion strategy found

It took a lot of time and ended up at https://blog.csdn.net/wangyuanjun008/article/details/79121459
A solution has been found. Change plugins to:

<property name="plugins">
    <array>
        <bean class="com.github.pagehelper.PageInterceptor">
            <property name="properties">
                <value>
                <!-- helperDialect: Different from 3.0+Version, now must be helperDialect,otherwise spring Error reporting when starting load -->
                    helperDialect=mysql
                </value>
            </property>
        </bean>
    </array>
</property>

The project test is finished!
Specific project code, see: github

This article refers to:
https://blog.csdn.net/wangyuanjun008/article/details/79121459

Topics: Java Spring xml Mybatis JDBC