ssm中逆向工程与分页的应用

昨天对springboot中的mybatis逆向工程与分页应用进行了整理,今天对ssm项目中的逆向工程与分页进行整理。

项目运行环境:eclipse+jdk1.8+maven+tomcat

搭建ssm项目

首先新建maven project,项目Archetype选择:maven-archetype-webapp,项目新建完毕,会出现生成的index.jsp报错。

造成原因:项目没有依赖javax.servlet相关类包,这些类包在tomcat类库中

有两种解决方案:

方法一:添加依赖

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

方法二:依赖tomcat类库,前提是eclipse已经有tomcat服务器

依次 右击项目—>build path —> configure build path — >libraries — > add libraries —> Server Runtime — >选择tomcat服务器lib —> ok

项目建成依次添加依赖,代码如下:

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

<dependencies>
    <!-- 单元测试 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <!-- 解决新建jsp文件报错 -->
    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>2.5</version>
    </dependency>

    <!-- spring包 -->
    <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>

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

    <!-- 数据库 -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>5.1.37</version>
    </dependency>

    <!-- c3p0连接池 -->
    <dependency>
        <groupId>c3p0</groupId>
        <artifactId>c3p0</artifactId>
        <version>0.9.1.2</version>
    </dependency>
</dependencies>

maven install下载好依赖包。

在src/main/resources文件夹下添加文件jdbc.properties,代码如下:

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    

在src/main/resources文件夹下添加文件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>
    <!-- 配置全局属性 -->
    <settings>
        <!-- 使用jdbc的getGeneratedKeys获取数据库自增主键值 -->
        <setting name="useGeneratedKeys" value="true" />

        <!-- 使用列标签替换列别名 默认:true -->
        <setting name="useColumnLabel" value="true" />

        <!-- 开启驼峰命名转换:Table{create_time} -> Entity{createTime} -->
        <setting name="mapUnderscoreToCamelCase" value="true" />
    </settings>
</configuration>

在src/main/resources文件夹下添加文件夹spring,在spring中添加文件spring-dao.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"
    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">
    <!-- 配置整合mybatis过程 -->
    <!-- 1.配置数据库相关参数properties的属性:${url} -->
    <context:property-placeholder location="classpath:jdbc.properties"/>
    <!-- 2.数据库连接池 -->
    <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
        <!-- 配置连接池属性 -->
        <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连接池的私有属性 -->
        <property name="maxPoolSize" value="30" />
        <property name="minPoolSize" value="10" />
        <!-- 关闭连接后不自动commit -->
        <property name="autoCommitOnClose" value="false" />
        <!-- 获取连接超时时间 -->
        <property name="checkoutTimeout" value="10000" />
        <!-- 当获取连接失败重试次数 -->
        <property name="acquireRetryAttempts" value="2" />
    </bean>

    <!-- 3.配置SqlSessionFactory对象 -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
        <!-- 配置MyBaties全局配置文件:mybatis-config.xml -->
        <property name="configLocation" value="classpath:mybatis-config.xml" />
        <!-- 扫描entity包 使用别名 -->
        <property name="typeAliasesPackage" value="com.luis.entity" />
        <!-- 扫描sql配置文件:mapper需要的xml文件 -->
        <property name="mapperLocations" value="classpath:mapper/*.xml" />
    </bean>

    <!-- 4.配置扫描Dao接口包,动态实现Dao接口,注入到spring容器中 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- 注入sqlSessionFactory -->
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
        <!-- 给出需要扫描Dao接口包 -->
        <property name="basePackage" value="com.luis.mapper" />
    </bean>
</beans>

在spring中添加文spring-service.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
    http://www.springframework.org/schema/context/spring-context.xsd
    http://www.springframework.org/schema/tx
    http://www.springframework.org/schema/tx/spring-tx.xsd">
    <!-- 扫描service包下所有使用注解的类型 -->
    <context:component-scan base-package="com.luis.service" />

    <!-- 配置事务管理器 -->
    <bean id="transactionManager"
        class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!-- 注入数据库连接池 -->
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 配置基于注解的声明式事务 -->
    <tx:annotation-driven transaction-manager="transactionManager" />
</beans>

在spring中添加文spring-web.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: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">
    <!-- 配置SpringMVC -->
    <!-- 1.开启SpringMVC注解模式 -->
    <mvc:annotation-driven />

    <!-- 2.静态资源默认servlet配置 (1)加入对静态资源的处理:js,gif,png (2)允许使用"/"做整体映射 -->
    <mvc:resources mapping="/resources/**" location="/resources/" />
    <mvc:default-servlet-handler />

    <!-- 3.定义视图解析器 -->
    <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.扫描web相关的bean -->
    <context:component-scan base-package="com.luis.web" />
</beans>

修改web.xml文件,代码如下:

<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>

至此,ssm项目搭建完毕!

逆向工程与分页应用

首先导入逆向工程项目,具体使用方法参见:我的github

本文仍旧应用上篇的数据库,数据库表如下:

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‘);

运行文件生成mapper接口,实体类与xml文件。

分页已经添加依赖,可直接应用。

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

另外在spring-dao.xml文件的SqlSessionFactory的bean中添加:

<property name="plugins">
    <array>
        <bean class="com.github.pagehelper.PageInterceptor">
            <property name="properties">
                <value>
                <!-- helperDialect:有别于3.0+版本,现在必须是helperDialect,否则spring启动加载时会报错 -->
                    helperDialect=mysql
                </value>
            </property>
        </bean>
    </array>
</property>

编写service层,UserService代码如下:

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

UserServiceImpl代码如下:

@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 开始页数
     * pageSize 每页显示的数据条数
     */
    public List<User> findAllUser(int pageNum, int pageSize) {
        //将参数传给方法实现分页
        PageHelper.startPage(pageNum, pageSize);
        UserExample example = new UserExample();
        List<User> list = userMapper.selectByExample(example);
        return list;
    }
}

编写web层,UserController代码如下:

@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);
        //获取分页信息
        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";
    }
}

测试

将项目部署到tomcat,启动,访问http://localhost:8080/ssm-demo/test,运行结果:

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

逆向工程与ssm项目搭建成功!

访问http://localhost:8080/ssm-demo/list,运行结果:

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

此处遇到的坑:照着网上的很多例子添加了plugins,分页过程中出现错误:

警告: 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
九月 06, 2018 10:51:00 下午 org.springframework.web.servlet.DispatcherServlet initServletBean
严重: 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

花了很大时间,最后在https://blog.csdn.net/wangyuanjun008/article/details/79121459

找到了解决方案。将plugins改为:

<property name="plugins">
    <array>
        <bean class="com.github.pagehelper.PageInterceptor">
            <property name="properties">
                <value>
                <!-- helperDialect:有别于3.0+版本,现在必须是helperDialect,否则spring启动加载时会报错 -->
                    helperDialect=mysql
                </value>
            </property>
        </bean>
    </array>
</property>

项目测试完毕!

具体的项目代码,参见于:github

本文参考了:

https://blog.csdn.net/wangyuanjun008/article/details/79121459

原文地址:https://www.cnblogs.com/liuyi6/p/9601917.html

时间: 2024-10-29 14:15:17

ssm中逆向工程与分页的应用的相关文章

17-SSM中通过pagehelper分页的实现

SSM中通过pagehelper分页的实现 1. 在SSM框架的基础上实现,导包 <!-- 分页 --> <dependency> <groupId>com.github.pagehelper</groupId> <artifactId>pagehelper</artifactId> <version>5.1.2</version> </dependency> 2. application.xml的

创建有输出参数的存储过程并在c#中实现DataGridView分页功能

不足之处,欢迎指正! 创建有输出参数的存储过程 if exists(select * from sysobjects where name='usp_getPage1') drop procedure usp_getPage1 go create procedure usp_getPage1--存储过程名称 @count int output,--输出参数 @countIndex int=1,--参数带默认值 @countPage int=5--参数带默认值 as --一个sql语句.ROW_N

在 asp.net mvc中的简单分页算法

//第一步:建立如下分页实体类:namespace MVCPager.Helpers { /// <summary> /// 简单分页算法类 /// </summary> public class Pager { public int RecordCount { get; set; } public int PageIndex { get; set; } public int PageSize { get; set; } public int PageCount { get { r

MySQL与Oracle中的基本分页

MySQL中的基本分页: select ename from emp where xxxxx order by sal  desc limit (pageno-1)*pageSize,pageSize; Oracle中的基本分页 select tt.* from ( select t.*,rownum as  linenum from (select  * from  tbl_role) t where rownum <#{0}*#{1} )tt where linenum  >(#{0}-1

winform中DataGridView实现分页功能

http://liyaguang20111105.blog.163.com/blog/static/19929420220146283255809/ 在winform的设计中,要实现对DataGridView控件的分页功能,需要两个控件:BindingSource.BindingNavigator,根据需求可对BindingNavigator进行自由的扩展,下图的示例则是根据一般需求对分页功能的实现.红色区域是对BindingNavigator控件扩展后的效果. 具体实现过程 : //窗体构造方

ASP.NET中实现Ajax分页

在页面中指定一个div容器来接收动态生成的分页数据: 1 <div id="div_menu"> 2 </div> 使用jQuery来请求并处理Json格式数据: 1 //定义页码与页容量 2 var pageIndex = 1; 3 var pageSize = 15; 4 var pageCount = 0; 5 var recordCount = 0; 6 AjaxGetData(pageIndex, pageSize); 7 //Ajax获取数据 8 f

实现数据在前台动态显示之分页的实现(将DataSet中的数据分页显示)

在实现前台动态显示数据时有多种方法,但使用到将DataSet中的数据分页这一方法时发现很多地方都能用得到,在这里记录一下. /// <summary> /// 分页的实现(将DataSet中的数据分页显示) /// </summary> /// <param name="ds"></param> /// <returns></returns> public DataSet SplitDataSet() { Data

sf中标准的分页功能介绍

世上本无事,庸人自扰之.我喜欢一个相对比较安静的环境去学习和工作,希望在一个掉一根针的声音都能够听到的环境中,但是有时候往往相反,一片嘈杂,我改变不了周围的环境,只能改变自己,其实这些都没有什么,也许是我内心就很嘈杂,使我听到一点点声音就感觉很烦躁.上善若水,心静则情静继而人静. 言归正传: sf中标准的分页功能: sf有自己标准的分页功能,sf真是个功能相当完善的云端开发平台,其有好多自己标准的功能,今天我就根据自己的理解先介绍一下sf标准的分页功能的皮毛. 定义关联到前台的Contet值 p

PowerDesigner中逆向工程将数据库中comment赋值到name

'------------------------------------------------------------ ' '脚本功能: ' PowerDesigner中逆向工程完成后,将数据库中comment脚本 ' 赋值到PDM的name '执行方法: ' Open PDM--Tools--Execute Commands--Run Script ' '------------------------------------------------------------ Option