hibernate update从前端到后端的部分或全部字段更新

在Struts2框架中,我们在前端提交表单的时候,会在后端创建一个对象并设置get和set方法,前端则name="对象.xxx"来获取值。有的时候我们会选择更新部分字段,但是其他字段又不能为空,可以这样操作。

创建两个两个对象A(前端用于接收值)和B(后端用于给A补全值)

1.从前端获取需要修改的值(对象A可能是某些字段是空的,需要补全值)

2.根据对象A的id从数据库中获取对象B(这个对象是A在数据库中未被修改的副本)

3.对象补全值需要用到一个方法,讲解一下这个方法怎么用:BbsUserinfo是对象名(这里是举例说明,以自己的bean为主),sourceBean是数据源(被提取的对象),targetBean(用于合并的对象),sourceBean的值会覆盖targetBean的值,所以这里的sourceBean为A,targetBean为B。这个方法的具体实现在次就不做介绍了。

public BbsUserinfo change(BbsUserinfo sourceBean, BbsUserinfo targetBean) {
	        Class sourceBeanClass = sourceBean.getClass();
	        Class targetBeanClass = targetBean.getClass();
	        
	        Field[] sourceFields = sourceBeanClass.getDeclaredFields();
	        Field[] targetFields = sourceBeanClass.getDeclaredFields();
	        for(int i=0; i<sourceFields.length; i++){
	            Field sourceField = sourceFields[i]; 
	            Field targetField = targetFields[i];  
	            sourceField.setAccessible(true);
	            targetField.setAccessible(true);
	            try {
	                if( !(sourceField.get(sourceBean) == null) &&  !"serialVersionUID".equals(sourceField.getName().toString())){
	                    targetField.set(targetBean,sourceField.get(sourceBean));
	                }
	            } catch (IllegalArgumentException | IllegalAccessException e) {
	                e.printStackTrace();
	            }
	        }
	      return targetBean;
	    
	}
用这个方法更新值非常灵活,几乎不用管后台,前端可以根据自己的需求修改值,不懂的可以评论留言。

猜你喜欢

转载自blog.csdn.net/ck784101777/article/details/80743381
今日推荐