DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

How I Used BeanUtils for Editing a JPA Entity

Want a quick, easy way to edit JPA entities? See how one dev made use of BeanUtils to copy over relevant data from source to target.

Shuhail Kadavath user avatar by
Shuhail Kadavath
·
Apr. 17, 18 · Tutorial
Like (9)
Save
Tweet
Share
15.21K Views

Join the DZone community and get the full member experience.

Join For Free

So I was wondering how to edit an entity using Spring JPA/ Hibernate.

Below is how my model looked like: 

public class Vehicle {
    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;

    @Column(name="brand")
    private String brand;

    @Column(name="type")
    private String type;

    @Column(name="model")
    private String model;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name="owner_id",nullable=false)
    @JsonBackReference
    private Owner owner;

  //getters and setters


And this is how originally I was exposing the method for editing Vehicle:

public Vehicle editVehicleDetails(long vehicleId , Vehicle vehicle) {

    Vehicle original = vehicleRepository.findById(vehicleId).orElse(null);
    if(vehicle.getBrand()!=null) {
    original.setBrand(vehicle.getBrand());
}
//setting other attributes if not null 


In the above snippet, I am checking if the given vehicle attribute is non-null and setting it to the original. The problem with this approach is that I have to check each and every attribute for not null and then set it to the original.

So I came up with the BeanUtils for solving it. First of all, I came up a generic method to get the null fields in any object as below:

public static Set<String> getNullPropertyNames (Object source,String... extra) {
    final BeanWrapper src = new BeanWrapperImpl(source);
    java.beans.PropertyDescriptor[] pds = src.getPropertyDescriptors();

    Set<String> emptyNames = new HashSet<String>();
    for(java.beans.PropertyDescriptor pd : pds) {
        Object srcValue = src.getPropertyValue(pd.getName());
        if (srcValue == null) {
        logger.info("attribute {}",pd.getName());
        emptyNames.add(pd.getName());
        }
    }

    for(String args : extra) {
    emptyNames.add(args);
    }
    return emptyNames;
}


Here I have given a var args extra . This is to give additional functionality: Like if we want to ignore additional fields in a model, it can be provided here, which will be added to the set as well.

Now in the service layer, I used BeanUtils to copy from the source to the target.

public Vehicle editVehicleDetails(long vehicleId , Vehicle vehicle) {

    Vehicle original = vehicleRepository.findById(vehicleId).orElse(null);
    Set<String> ignoreFields = com.amoebiq.product.vehiman.controller.utils.BeanUtils.getNullPropertyNames(vehicle,"id","owner");
    BeanUtils.copyProperties(original, vehicle,ignoreFields.toArray(new String[ignoreFields.size()]));
    serviceDetailsRepository.save(service);
}


This reduced a lot of work for me, and I am using it across all my services. Hope this helps.

entity

Opinions expressed by DZone contributors are their own.

Popular on DZone

  • When AI Strengthens Good Old Chatbots: A Brief History of Conversational AI
  • Handling Automatic ID Generation in PostgreSQL With Node.js and Sequelize
  • Efficiently Computing Permissions at Scale: Our Engineering Approach
  • Explainer: Building High Performing Data Product Platform

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com
  • +1 (919) 678-0300

Let's be friends: