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

相关文章

C#中async await异步关键字用法和异步的底层原理全解析

《C#中asyncawait异步关键字用法和异步的底层原理全解析》:本文主要介绍C#中asyncawait异步关键字用法和异步的底层原理全解析,本文给大家介绍的非常详细,对大家的学习或工作具有一... 目录C#异步编程一、异步编程基础二、异步方法的工作原理三、代码示例四、编译后的底层实现五、总结C#异步编程

如何解决idea的Module:‘:app‘platform‘android-32‘not found.问题

《如何解决idea的Module:‘:app‘platform‘android-32‘notfound.问题》:本文主要介绍如何解决idea的Module:‘:app‘platform‘andr... 目录idea的Module:‘:app‘pwww.chinasem.cnlatform‘android-32

python3 gunicorn配置文件的用法解读

《python3gunicorn配置文件的用法解读》:本文主要介绍python3gunicorn配置文件的使用,具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑完全的地方,望不吝赐教... 目录python3 gunicorn配置文件配置文件服务启动、重启、关闭启动重启关闭总结python3 gun

kali linux 无法登录root的问题及解决方法

《kalilinux无法登录root的问题及解决方法》:本文主要介绍kalilinux无法登录root的问题及解决方法,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,... 目录kali linux 无法登录root1、问题描述1.1、本地登录root1.2、ssh远程登录root2、

MySQL 中的 LIMIT 语句及基本用法

《MySQL中的LIMIT语句及基本用法》LIMIT语句用于限制查询返回的行数,常用于分页查询或取部分数据,提高查询效率,:本文主要介绍MySQL中的LIMIT语句,需要的朋友可以参考下... 目录mysql 中的 LIMIT 语句1. LIMIT 语法2. LIMIT 基本用法(1) 获取前 N 行数据(

SpringBoot应用中出现的Full GC问题的场景与解决

《SpringBoot应用中出现的FullGC问题的场景与解决》这篇文章主要为大家详细介绍了SpringBoot应用中出现的FullGC问题的场景与解决方法,文中的示例代码讲解详细,感兴趣的小伙伴可... 目录Full GC的原理与触发条件原理触发条件对Spring Boot应用的影响示例代码优化建议结论F

C#中DrawCurve的用法小结

《C#中DrawCurve的用法小结》本文主要介绍了C#中DrawCurve的用法小结,通常用于绘制一条平滑的曲线通过一系列给定的点,具有一定的参考价值,感兴趣的可以了解一下... 目录1. 如何使用 DrawCurve 方法(不带弯曲程度)2. 如何使用 DrawCurve 方法(带弯曲程度)3.使用Dr

C++ vector的常见用法超详细讲解

《C++vector的常见用法超详细讲解》:本文主要介绍C++vector的常见用法,包括C++中vector容器的定义、初始化方法、访问元素、常用函数及其时间复杂度,通过代码介绍的非常详细,... 目录1、vector的定义2、vector常用初始化方法1、使编程用花括号直接赋值2、使用圆括号赋值3、ve

MySQL中FIND_IN_SET函数与INSTR函数用法解析

《MySQL中FIND_IN_SET函数与INSTR函数用法解析》:本文主要介绍MySQL中FIND_IN_SET函数与INSTR函数用法解析,本文通过实例代码给大家介绍的非常详细,感兴趣的朋友一... 目录一、功能定义与语法1、FIND_IN_SET函数2、INSTR函数二、本质区别对比三、实际场景案例分

Pyserial设置缓冲区大小失败的问题解决

《Pyserial设置缓冲区大小失败的问题解决》本文主要介绍了Pyserial设置缓冲区大小失败的问题解决,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面... 目录问题描述原因分析解决方案问题描述使用set_buffer_size()设置缓冲区大小后,buf