本篇使用自定义工具类进行批量处理对象
---将批量源对象的属性值注入到实际需要的目标类对象(属性名相同,类型不同)中
项目使用maven构建war工程: spring+spring MVC+Mybatis
回顾知识点:
事务:--->为什么在使用AOP时需要使用spring-aspects 依赖(不导入会报异常:切入点pointcut找不到依赖)
Aop是一种横向抽取,简单的这样理解:比如当应用程序调用你业务逻辑组件(比如DAO)的方法时,该方法首先会被拦截,Aspect首先开始事物边界,接着方法开始执行,
方法执行完后,Spring会提交事物,你的业务逻辑组件完全不知道自己处于事物管理中
AOP是面向切面的编程
在Spring里,只有面向方法的切面。
比如你有一个方法A和方法B,你希望在A执行前执行方法B,但不能把B的代码贴到A中
因为和A类似的方法有很多,如果你全都贴过去的话,工作量大并且是重复的工作
这个时候你就定义了A为切面,B为处理程序。Spring 会在你调用A方法时自动执行B方法
实际过程是Spring 为含有A方法的类生成了一个代理类,该类也有一个叫A的方法但其实现却是 B+A的实现
你调用A的时候,调用的对象是代理对象,但是你并不知道。
事务的编程正是上述情况的典型
事务处理代码是B(提交,回滚),事务执行代码是A(增删改查)
在Spring 中已经内置了事务处理代码,也就是B,所以我们写A方法,然后配置事务就可以了。
使用AOP而忘记导入spring-aspects 依赖时会报下述异常:
Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'transactionManager' defined in file [G:\javaEEWeb_Eclipse\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\MyWebPro\WEB-INF\classes\applicationContext-tran.xml]: BeanPostProcessor before instantiation of bean failed; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.aop.support.DefaultBeanFactoryPointcutAdvisor#0':Cannot create inner bean '(inner bean)#77799cbb' of type[org.springframework.aop.aspectj.AspectJExpressionPointcut] while setting bean property 'pointcut'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#77799cbb': Failed to introspect bean class [org.springframework.aop.aspectj.AspectJExpressionPointcut] for lookup method metadata: could not find class that it depends on; nested exception isjava.lang.NoClassDefFoundError: org/aspectj/weaver/reflect/ReflectionWorld$ReflectionWorldException
---------------------------------------------------------------------------------------
实际开发中数据库中的表数据往往和实际表示层页面中的数据不太相同,比如下面这张申请贷款的用户表,
id : 用户id
username: 用户名
submitDate: 提交日期
certiType: 申请贷款的证件类型,表中存的是0,1,2 0 身份证,1 护照, 2 其他
result: 审核结果, 表中存的是0或1 0 未通过, 1通过
vid: 审核人id 表中存的是审核人id (关联表) ,而我们需要在页面中展示的是审核人姓名
效果预览:
数据库中数据:
而在页面中展示的是;
---------------------------------------------------------------------------------------------
项目结构:
数据库中:
两张表
user表:
verifier表:
两张表有关联关系. user表通过外键vid和verifier进行关联.
web工程中:
pom.xml中需要导入的依赖:
pojo之User:
package com.qx.pojo;
import java.util.Date;
public class User {
private Integer id; //id
private String username; //用户名
private Date submitDate; //提交日期
private String certiType; //证件类型 //数据库中存的是字符串0,2,3
private int result; //审核结果 //数据库中存的是Integer类型 0或1
private Integer vid; //审核人id
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public Date getSubmitDate() {
return submitDate;
}
public void setSubmitDate(Date submitDate) {
this.submitDate = submitDate;
}
public String getCertiType() {
return certiType;
}
public void setCertiType(String certiType) {
this.certiType = certiType;
}
public int getResult() {
return result;
}
public void setResult(int result) {
this.result = result;
}
public Integer getVid() {
return vid;
}
public void setVid(Integer vid) {
this.vid = vid;
}
}
pojo之Verifier
package com.qx.pojo;
public class Verifier {
private Integer vid;
private String vname;
public Integer getVid() {
return vid;
}
public void setVid(Integer vid) {
this.vid = vid;
}
public String getVname() {
return vname;
}
public void setVname(String vname) {
this.vname = vname;
}
}
配置文件之 db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql:///mywebpro?characterEncoding=utf-8
jdbc.user=root
jdbc.password=root
配置文件之mybatis.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>
<plugins>
<!--
3.4.2版本pagehelper
<plugin interceptor="com.github.pagehelper.PageHelper">
<property name="dialect" value="mysql"/>
</plugin>
-->
<!--5.0版本pagehelper -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<property name="helperDialect" value="mysql"/>
</plugin>
</plugins>
</configuration>
<?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-4.3.xsd">
<context:component-scan base-package="com.qx"></context:component-scan>
<!-- 导入配置文件 -->
<context:property-placeholder location="classpath:conf/db.properties"/>
<!-- dataSource -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.user}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- 配置工厂 -->
<bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:mybatis.xml"></property>
</bean>
<!-- 配置扫描mapper文件 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.qx.mapper"></property>
</bean>
</beans>
配置文件之applicationContext-tran.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:aop="http://www.springframework.org/schema/aop"
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/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 事务管理器 -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 约定优于编码 设置事务详情 -->
<tx:method name="get*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="find*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="select*" read-only="true" propagation="SUPPORTS"/>
<tx:method name="add*"/>
<tx:method name="save*"/>
<tx:method name="insert*"/>
<tx:method name="delete*"/>
<tx:method name="update*"/>
</tx:attributes>
</tx:advice>
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.qx..service..*.*(..))"/>
</aop:config>
</beans>
配置文件之 sping-MVC.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-4.3.xsd
http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<!-- 虽在applicationContext.xml中配置过了,最好还是在此处再配一次,防止找不到 -->
<context:component-scan base-package="com.qx"></context:component-scan>
<!-- 不需要配置id,因为用不到 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- <property name="prefix" value="/"></property> -->
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置resource标签,此标签内部的地址不会被拦截 -->
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
<mvc:annotation-driven></mvc:annotation-driven>
</beans>
web.xml中的配置
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
<display-name>MyWebPro</display-name>
<!-- needed for ContextLoaderListener -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:app*.xml</param-value>
</context-param>
<!-- Bootstraps the root web application context before servlet initialization -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- The front controller of this Spring Web application, responsible for handling all application requests -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring-MVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Map all requests to the DispatcherServlet for handling -->
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
utils之UserMutate
package com.qx.utils;
public class UserMutate {
private Integer id; //id
private String username; //用户名
/*需转换*/
private String submitDate; //提交日期
/*需转换 "0"->身份证, "1"->护照, "2"->其他*/
private String certiType; //证件类型
/*需转换 0->未通过, 1->通过 */
private String result; //审核结果
/*需要转换 审核人id-->审核人name*/
private String vid; //审核人id
//getter and setter 方法 (必须要有)
@Override
public String toString() {
return "UserMutate [id=" + id + ", username=" + username + ", submitDate=" + submitDate + ", certiType="
+ certiType + ", result=" + result + ", vid=" + vid + "]";
}
}
utils之自定义转换器接口MyConvert
package com.qx.utils;
public interface MyConvert<S,T> {
public T convert(S source);
}
utils之自定义操作bean的工具类MyBeanUtils(采用了反射技术)(重点)
package com.qx.utils;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MyBeanUtils {
private static Map<String, MyConvert> convertMap=new HashMap<>();
// 参1:变量名 参2:给变量名对应的转换器
/**
*
* @param name 变量名(即 key) the name must be as same as the propertyName
* @param myConvert 该变量名对应的转换器(即value)
*/
public static void addConvert(String name,MyConvert myConvert) {
convertMap.put(name, myConvert);
};
/**
* 转换批量对象
* @param sources 转换前的原始数据
* @param tClass 转换后的目表类
* @return
*/
public static <T> List<T> populateBean(List sources,Class<T> tClass) throws Exception{
List<T> list=new ArrayList<>();//创建存放目标的集合
//中间转换数据
for (int i = 0; i < sources.size(); i++) {//遍历转换前的原始数据
Object o = sources.get(i);
T newInstance = tClass.newInstance();//转换后的用于存放数据的对象
Field[] declaredFields = tClass.getDeclaredFields();//从目标中取出所有的字段
for (Field field : declaredFields) { //遍历字段
String name = field.getName(); //找到每个字段的名字,这个刚好在原始内容中都存在
/*在原始的类中查找当前同名的属性,o.getclass()得到的是原始类型 不是Object.class*/
PropertyDescriptor propertyDescriptor=new PropertyDescriptor(name, o.getClass());
if (propertyDescriptor!=null) {
Method readMethod = propertyDescriptor.getReadMethod();//获取get方法
Object invoke = readMethod.invoke(o);//调用get方法从当前正在需要转换的对象上面获取值
MyConvert myConvert = convertMap.get(name);//根据当前的字段名去转换器中查询是否有转换器
if (myConvert!=null) {
invoke=myConvert.convert(invoke);
}
//field.setAccessible(true);//首先设置允许访问私有变量
//field.set(newInstance, invoke);//赋值
PropertyDescriptor targetPro=new PropertyDescriptor(name, tClass);//从目标类上面找这个属性,这里建议使用set放个赋值
if (targetPro!=null) {
Method writeMethod = targetPro.getWriteMethod();//获取set方法
writeMethod.invoke(newInstance, invoke);//为目标类型对象的属性赋值
}
}
}
list.add(newInstance);
}
//convertMap.clear();//注意 转换器应该在所有的数据遍历完成后清除(若多用户共享该map则不能清除)
return list;
}
}
mapper之UserMapper接口
package com.qx.mapper;
import java.util.List;
import com.qx.pojo.User;
public interface UserMapper {
// 查询所有
public List<User> findAll();
}
mapper之UserMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.qx.mapper.UserMapper">
<select id="findAll" parameterType="com.qx.pojo.User" resultType="com.qx.pojo.User">
select * from user;
</select>
</mapper>
mapper之VerfierMapper接口
package com.qx.mapper;
public interface VerifierMapper {
//根据审核人id查询审核人名字
public String findVerifierNameById(Integer id);
}
mapper之VerfierMapper.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd" >
<mapper namespace="com.qx.mapper.VerifierMapper">
<select id="findVerifierNameById" parameterType="integer" resultType="string">
select vname from verifier where vid=#{vid}
</select>
</mapper>
业务层之UserService接口:
package com.qx.service;
import java.util.List;
import com.qx.utils.UserMutate;
public interface UserService {
public List<UserMutate> findAll();
}
业务层之UserServiceImpl:( 重点)
package com.qx.service;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.qx.mapper.UserMapper;
import com.qx.mapper.VerifierMapper;
import com.qx.pojo.User;
import com.qx.utils.MyBeanUtils;
import com.qx.utils.MyConvert;
import com.qx.utils.UserMutate;
@Service
public class UserServiceImpl implements UserService{
@Autowired
private UserMapper userMapper;
@Autowired
private VerifierMapper verifierMapper;
@Override
public List<UserMutate> findAll() {
//从数据库中查询出所有用户
List<User> users = userMapper.findAll();
//设置转换器
//Date--->String
MyConvert<Date, String> submitDateConvert=new MyConvert<Date, String>() {
@Override
public String convert(Date source) {
// TODO Auto-generated method stub
if (source!=null) { //此处可不判空,因为数据库中要求,此项非空,对于没要求非空的必须判空
SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy-MM-dd");
return simpleDateFormat.format(source);
}
return "";
}
};
//String--->String 即 0-->身份证,1-->护照,2-->其他
MyConvert<String, String> certiTypeConvert=new MyConvert<String, String>() {
@Override
public String convert(String source) {
// TODO Auto-generated method stub
switch (source) {
case "0":
return "身份证";
case "1":
return "护照";
case "2":
return "其他";
default:
break;
}
return "";
}
};
//Integer--->String 即 0-->未通过, 1-->通过
MyConvert<Integer, String> resultConvert=new MyConvert<Integer, String>() {
@Override
public String convert(Integer source) {
// TODO Auto-generated method stub
switch (source) {
case 0:
return "未通过";
case 1:
return "通过";
default:
break;
}
return "";
}
};
//Integer--->String 即 审核人id--->审核人姓名
MyConvert<Integer, String> vidConvert=new MyConvert<Integer, String>() {
@Override
public String convert(Integer source) {
// TODO Auto-generated method stub
String name = verifierMapper.findVerifierNameById(source);
return name;
}
};
//必须以属性名作为key
MyBeanUtils.addConvert("submitDate",submitDateConvert);
MyBeanUtils.addConvert("certiType", certiTypeConvert);
MyBeanUtils.addConvert("result", resultConvert);
MyBeanUtils.addConvert("vid", vidConvert);
try {
//批处理
List<UserMutate> userMutates=MyBeanUtils.populateBean(users, UserMutate.class);
System.out.println(userMutates);
return userMutates;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
}
控制层之UserController:
package com.qx.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.qx.service.UserService;
import com.qx.utils.UserMutate;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/findAll")
public ModelAndView findAllUser(){
ModelAndView mv=new ModelAndView();
List<UserMutate> userMutates = userService.findAll();
mv.addObject("usermutates", userMutates);
mv.setViewName("/userlist");
return mv;
}
}
视图层之index.jsp:
<body>
<jsp:forward page="/user/findAll.action"></jsp:forward>
</body>
视图层之userlist.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<table border="1" width="100%">
<tr>
<td>用户名</td>
<td>提交日期</td>
<td>证件类型</td>
<td>审核结果</td>
<td>审核人</td>
</tr>
<c:forEach items="${usermutates }" var="usermutate">
<tr>
<td>${usermutate.username }</td>
<td>${usermutate.submitDate }</td>
<td>${usermutate.certiType }</td>
<td>${usermutate.result }</td>
<td>${usermutate.vid }</td>
</tr>
</c:forEach>
</table>
</body>
</html>
启动tomcat, 浏览器中输入请求地址 localhost:8080/MyWebPro 回车即可看到展示的数据
项目下载地址:
https://github.com/wudinaniya/mywebpro.git