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

相关文章

使用TomCat,service输出台出现乱码的解决

《使用TomCat,service输出台出现乱码的解决》本文介绍了解决Tomcat服务输出台中文乱码问题的两种方法,第一种方法是修改`logging.properties`文件中的`prefix`和`... 目录使用TomCat,service输出台出现乱码问题1解决方案问题2解决方案总结使用TomCat,

解决Spring运行时报错:Consider defining a bean of type ‘xxx.xxx.xxx.Xxx‘ in your configuration

《解决Spring运行时报错:Considerdefiningabeanoftype‘xxx.xxx.xxx.Xxx‘inyourconfiguration》该文章主要讲述了在使用S... 目录问题分析解决方案总结问题Description:Parameter 0 of constructor in x

解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题

《解决IDEA使用springBoot创建项目,lombok标注实体类后编译无报错,但是运行时报错问题》文章详细描述了在使用lombok的@Data注解标注实体类时遇到编译无误但运行时报错的问题,分析... 目录问题分析问题解决方案步骤一步骤二步骤三总结问题使用lombok注解@Data标注实体类,编译时

Java循环创建对象内存溢出的解决方法

《Java循环创建对象内存溢出的解决方法》在Java中,如果在循环中不当地创建大量对象而不及时释放内存,很容易导致内存溢出(OutOfMemoryError),所以本文给大家介绍了Java循环创建对象... 目录问题1. 解决方案2. 示例代码2.1 原始版本(可能导致内存溢出)2.2 修改后的版本问题在

大数据小内存排序问题如何巧妙解决

《大数据小内存排序问题如何巧妙解决》文章介绍了大数据小内存排序的三种方法:数据库排序、分治法和位图法,数据库排序简单但速度慢,对设备要求高;分治法高效但实现复杂;位图法可读性差,但存储空间受限... 目录三种方法:方法概要数据库排序(http://www.chinasem.cn对数据库设备要求较高)分治法(常

Vue项目中Element UI组件未注册的问题原因及解决方法

《Vue项目中ElementUI组件未注册的问题原因及解决方法》在Vue项目中使用ElementUI组件库时,开发者可能会遇到一些常见问题,例如组件未正确注册导致的警告或错误,本文将详细探讨这些问题... 目录引言一、问题背景1.1 错误信息分析1.2 问题原因二、解决方法2.1 全局引入 Element

linux报错INFO:task xxxxxx:634 blocked for more than 120 seconds.三种解决方式

《linux报错INFO:taskxxxxxx:634blockedformorethan120seconds.三种解决方式》文章描述了一个Linux最小系统运行时出现的“hung_ta... 目录1.问题描述2.解决办法2.1 缩小文件系统缓存大小2.2 修改系统IO调度策略2.3 取消120秒时间限制3

C#使用HttpClient进行Post请求出现超时问题的解决及优化

《C#使用HttpClient进行Post请求出现超时问题的解决及优化》最近我的控制台程序发现有时候总是出现请求超时等问题,通常好几分钟最多只有3-4个请求,在使用apipost发现并发10个5分钟也... 目录优化结论单例HttpClient连接池耗尽和并发并发异步最终优化后优化结论我直接上优化结论吧,

在MyBatis的XML映射文件中<trim>元素所有场景下的完整使用示例代码

《在MyBatis的XML映射文件中<trim>元素所有场景下的完整使用示例代码》在MyBatis的XML映射文件中,trim元素用于动态添加SQL语句的一部分,处理前缀、后缀及多余的逗号或连接符,示... 在MyBATis的XML映射文件中,<trim>元素用于动态地添加SQL语句的一部分,例如SET或W

解决systemctl reload nginx重启Nginx服务报错:Job for nginx.service invalid问题

《解决systemctlreloadnginx重启Nginx服务报错:Jobfornginx.serviceinvalid问题》文章描述了通过`systemctlstatusnginx.se... 目录systemctl reload nginx重启Nginx服务报错:Job for nginx.javas