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
ssm中逆向工程與分頁的應用