beanutils用法,解决hibernate映射弊端

2023-12-10 08:32

本文主要是介绍beanutils用法,解决hibernate映射弊端,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

Common BeanUtils组件方便了对JavaBean的使用。其中的一些类方法,使我们使用JavaBean得到了便利。

 

使用Common BeanUtils组件需要三个Jar包,分别是

commons-beanutils-1.8.0-BETA.jar

commons-logging-1.1.1.jar

commons-logging-api-1.1.1.jar


 

下面用四个例子说明该组件的三个优点。

 

例子一:

创建三个Java文件,分别为

Address.java

Profile.java

User.java

 

在写一个类文件递进调用函数,命名:BeanUtilsExample1.java,源码:

import java.util.Map;
import java.util.HashMap;
import java.util.GregorianCalendar;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.PropertyUtils;

public class BeanUtilsExample1 {
    
private User prepareData() {
        Profile profile 
= new Profile();
        profile.setEmail(
"shiyangxt@126.com");
        profile.setBirthDate(
new GregorianCalendar(3212910).getTime());
        Map
<String, String> phone = new HashMap<String, String>();
        phone.put(
"home""11011011");
        phone.put(
"office""82826905");
        profile.setPhone(phone);
        Address[] address 
= new Address("中国""北京""100120""天安门北大街888号"),
                
new Address("中国""广州""100120""石牌村666号") }
;
        profile.setAddress(address);

        User user 
= new User();
        user.setUserId(
new Long(123456789));
        user.setUsername(
"shiyang");
        user.setPassword(
"12345");
        user.setProfile(profile);
        
return user;
    }


    
public static void main(String[] args) {
        BeanUtilsExample1 example 
= new BeanUtilsExample1();
        User user 
= example.prepareData();
        
try {
            System.
out.println("输出对象的属性值---------------------------------");
            System.
out.println(BeanUtils.getProperty(user, "userId"));
            System.
out.println(BeanUtils.getProperty(user, "username"));//返回字符型
            System.out.println(PropertyUtils.getProperty(user, "username"));//返回对象类型
            System.out.println(BeanUtils.getProperty(user, "profile.email"));//重点
            System.out
                    .println(BeanUtils.getProperty(user, 
"profile.birthDate"));//重点
            System.out.println(BeanUtils.getProperty(user,
                    
"profile.phone(home)"));//重点
            System.out.println(BeanUtils.getProperty(user,
                    
"profile.phone(office)"));//重点
            System.out.println(BeanUtils.getProperty(user,
                    
"profile.address[0].city"));//重点
            System.out.println(BeanUtils.getProperty(user,
                    
"profile.address[1].city"));//重点

            User user2 
= new User();
            BeanUtils.copyProperties(user2, user);
            
//两层拷贝,基本类型复制值,对于引用类型(除String,封装类型外)复制地址值。
            System.out.println("输出复制属性的属性值-------------------------------");
            System.
out.println(BeanUtils.getProperty(user, "username"));
            System.
out
                    .println(BeanUtils.getProperty(user, 
"profile.birthDate"));//重点
            System.out.println(BeanUtils.getProperty(user,
                    
"profile.phone(home)"));//重点
            System.out.println(BeanUtils.getProperty(user,
                    
"profile.address[0].addr"));//重点

            System.
out.println("输出复制属性修改以后的属性值---------------------");
            BeanUtils.setProperty(user2, 
"userId"new Long(8888888));
            PropertyUtils.setProperty(user2, 
"username""ahah");
            BeanUtils.setProperty(user2, 
"profile.email""shiyangxt@126.com");//重点
            BeanUtils.setProperty(user2, "profile.birthDate",//重点
                    new GregorianCalendar(190025).getTime());
            BeanUtils.setProperty(user2, 
"profile.address[0]"new Address(
                    
"中国""深圳""600600""深北大道111号"));//重点
            System.out.println(BeanUtils.getProperty(user2, "userId"));
            System.
out.println(BeanUtils.getProperty(user2, "username"));
            System.
out.println(BeanUtils.getProperty(user2, "profile"));
            System.
out.println(BeanUtils.getProperty(user2, "profile.email"));//重点
            System.out.println(BeanUtils
                    .getProperty(user2, 
"profile.birthDate"));//重点
            System.out.println(BeanUtils.getProperty(user2,
                    
"profile.address[0].city"));//重点

            System.
out.println("与被复制属性值的对象的比较-------------------------------");
            System.
out.println(BeanUtils.getProperty(user, "userId"));
            System.
out.println(BeanUtils.getProperty(user, "username"));
            System.
out.println(BeanUtils.getProperty(user, "profile"));
            System.
out.println(BeanUtils.getProperty(user, "profile.email"));//重点
            System.out
                    .println(BeanUtils.getProperty(user, 
"profile.birthDate"));//重点
            System.out.println(BeanUtils.getProperty(user,
                    
"profile.address[0].city"));//重点
        }
 catch (Exception e) {
            e.printStackTrace();
        }

    }

}

从中可以看出,

调用一个属性中的方法,只需要加一个“.”即可。精简了操作。

还可以拷贝属性,但要注意是二层拷贝。

还要注意BeanUtils和PropertyUtils的区别。


例子二:

动态创建属性

文件名:BeanUtilsExample2,源码:

import java.util.GregorianCalendar;
import org.apache.commons.beanutils.LazyDynaBean;
import org.apache.commons.beanutils.BeanUtils;

public class BeanUtilsExample2 {
    
//动态创建属性
    public static void main(String args[]) throws Exception {

        LazyDynaBean hh 
= new LazyDynaBean();
        hh.
set("country""中国");
        hh.
set("city""北京");
        hh.
set("postCode""100120");
        hh.
set("addr""aaaaaaa");

        LazyDynaBean bb 
= new LazyDynaBean();
        bb.
set("phone""home""11011011");
        bb.
set("phone""office""111111");
        bb.
set("email""sh@126.com");
        bb.
set("address"0, hh);
        bb.
set("birthDate"new GregorianCalendar(1990329).getTime());

        LazyDynaBean tt 
= new LazyDynaBean();
        tt.
set("userId"new Long(8888888));
        tt.
set("gggg""施杨");
        tt.
set("password""sgsgsgsg");
        tt.
set("dddd", bb);

        System.
out.println(BeanUtils.getProperty(tt, "gggg"));
        System.
out.println(BeanUtils.getProperty(tt, "dddd.birthDate"));
        System.
out.println(BeanUtils.getProperty(tt,
                
"dddd.address[0].addr"));
        System.
out
                .println(BeanUtils.getProperty(tt, 
"dddd.phone(office)"));
    }

}

例子三:

连接Mysql数据库

文件名BeanUtilsExample3.java源码:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.ResultSetDynaClass;

public class BeanUtilsExample3 {
    
public static void main(String args[]) throws Exception {
        Connection conn 
= getConnection();
        PreparedStatement ps 
= conn
                .prepareStatement(
"select id,title,time from guestbook2 order by id desc");
        ResultSet rs 
= ps.executeQuery();

        ResultSetDynaClass rsdc 
= new ResultSetDynaClass(rs);//重点,二次封装,对连接对象有依赖
        Iterator itr = rsdc.iterator();
        
while (itr.hasNext()) {
            DynaBean bean 
= (DynaBean) itr.next();
            System.
out.print(bean.get("id"+ "\t");
            System.
out.print(bean.get("title"+ "\t");
            System.
out.println(bean.get("time"));
        }

        conn.close();
    }


    
private static Connection getConnection() {
        String url 
= "jdbc:mysql://localhost:3306/guestbook";
        String username 
= "root";
        String password 
= "hicc";
        Connection conn 
= null;
        
try {
            Class.forName(
"com.mysql.jdbc.Driver");
            conn 
= DriverManager.getConnection(url, username, password);
        }
 catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
 catch (SQLException e) {
            e.printStackTrace();
        }

        
return conn;
    }

}

例子四:

文件BeanUtilsExample4.java,源码:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Iterator;
import org.apache.commons.beanutils.DynaBean;
import org.apache.commons.beanutils.RowSetDynaClass;

public class BeanUtilsExample4 {
    
public static void main(String args[]) throws Exception {
        Connection conn 
= getConnection();
        PreparedStatement ps 
= conn
                .prepareStatement(
"select id,title,time from guestbook2 order by id desc");
        ResultSet rs 
= ps.executeQuery();

        RowSetDynaClass rsdc 
= new RowSetDynaClass(rs);
        
//重点,与ResultSetDynaClass的区别
        conn.close();//重点,关闭连接后仍能读取
        Iterator itr = rsdc.getRows().iterator();
        
while (itr.hasNext()) {
            DynaBean bean 
= (DynaBean) itr.next();
            System.
out.print(bean.get("id"+ "\t");
            System.
out.print(bean.get("title"+ "\t");
            System.
out.println(bean.get("time"));
        }

    }


    
private static Connection getConnection() {
        String url 
= "jdbc:mysql://localhost:3306/guestbook";
        String username 
= "root";
        String password 
= "hicc";
        Connection conn 
= null;
        
try {
            Class.forName(
"com.mysql.jdbc.Driver");
            conn 
= DriverManager.getConnection(url, username, password);
        }
 catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
 catch (SQLException e) {
            e.printStackTrace();
        }

        
return conn;
    }

}


这篇关于beanutils用法,解决hibernate映射弊端的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/476572

相关文章

JDK21对虚拟线程的几种用法实践指南

《JDK21对虚拟线程的几种用法实践指南》虚拟线程是Java中的一种轻量级线程,由JVM管理,特别适合于I/O密集型任务,:本文主要介绍JDK21对虚拟线程的几种用法,文中通过代码介绍的非常详细,... 目录一、参考官方文档二、什么是虚拟线程三、几种用法1、Thread.ofVirtual().start(

IDEA和GIT关于文件中LF和CRLF问题及解决

《IDEA和GIT关于文件中LF和CRLF问题及解决》文章总结:因IDEA默认使用CRLF换行符导致Shell脚本在Linux运行报错,需在编辑器和Git中统一为LF,通过调整Git的core.aut... 目录问题描述问题思考解决过程总结问题描述项目软件安装shell脚本上git仓库管理,但拉取后,上l

解决docker目录内存不足扩容处理方案

《解决docker目录内存不足扩容处理方案》文章介绍了Docker存储目录迁移方法:因系统盘空间不足,需将Docker数据迁移到更大磁盘(如/home/docker),通过修改daemon.json配... 目录1、查看服务器所有磁盘的使用情况2、查看docker镜像和容器存储目录的空间大小3、停止dock

idea npm install很慢问题及解决(nodejs)

《ideanpminstall很慢问题及解决(nodejs)》npm安装速度慢可通过配置国内镜像源(如淘宝)、清理缓存及切换工具解决,建议设置全局镜像(npmconfigsetregistryht... 目录idea npm install很慢(nodejs)配置国内镜像源清理缓存总结idea npm in

idea突然报错Malformed \uxxxx encoding问题及解决

《idea突然报错Malformeduxxxxencoding问题及解决》Maven项目在切换Git分支时报错,提示project元素为描述符根元素,解决方法:删除Maven仓库中的resolv... 目www.chinasem.cn录问题解决方式总结问题idea 上的 maven China编程项目突然报错,是

Java8 Collectors.toMap() 的两种用法

《Java8Collectors.toMap()的两种用法》Collectors.toMap():JDK8中提供,用于将Stream流转换为Map,本文给大家介绍Java8Collector... 目录一、简单介绍用法1:根据某一属性,对对象的实例或属性做映射用法2:根据某一属性,对对象集合进行去重二、Du

在Ubuntu上打不开GitHub的完整解决方法

《在Ubuntu上打不开GitHub的完整解决方法》当你满心欢喜打开Ubuntu准备推送代码时,突然发现终端里的gitpush卡成狗,浏览器里的GitHub页面直接变成Whoathere!警告页面... 目录一、那些年我们遇到的"红色惊叹号"二、三大症状快速诊断症状1:浏览器直接无法访问症状2:终端操作异常

mybatis直接执行完整sql及踩坑解决

《mybatis直接执行完整sql及踩坑解决》MyBatis可通过select标签执行动态SQL,DQL用ListLinkedHashMap接收结果,DML用int处理,注意防御SQL注入,优先使用#... 目录myBATiFBNZQs直接执行完整sql及踩坑select语句采用count、insert、u

Python中isinstance()函数原理解释及详细用法示例

《Python中isinstance()函数原理解释及详细用法示例》isinstance()是Python内置的一个非常有用的函数,用于检查一个对象是否属于指定的类型或类型元组中的某一个类型,它是Py... 目录python中isinstance()函数原理解释及详细用法指南一、isinstance()函数

Python中的sort方法、sorted函数与lambda表达式及用法详解

《Python中的sort方法、sorted函数与lambda表达式及用法详解》文章对比了Python中list.sort()与sorted()函数的区别,指出sort()原地排序返回None,sor... 目录1. sort()方法1.1 sort()方法1.2 基本语法和参数A. reverse参数B.