Fork me on GitHub

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

posted @ 2018-09-06 23:22  紫焱luis  阅读(520)  评论(0编辑  收藏  举报