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 Video Library
Refcards
Trend Reports

Events

View Events Video Library

Related

  • The AI Firewall: Using Local Small Language Models (SLMs) to Scrub PII Before Cloud Processing
  • Understanding Java Signals
  • Java Bean Validation: Applying Constraints Programmatically
  • Hexagonal Architecture in the Frontend: A Real Case

Trending

  • Building Threat Intelligence Pipelines Using Python, APIs, and Elasticsearch
  • Identity in Action
  • Building AI-Powered Java Applications With Jakarta EE and LangChain4j
  • Building a Spring AI Assistant With MCP Servers: A Step-by-Step Tutorial

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.

By 
Shuhail Kadavath user avatar
Shuhail Kadavath
·
Apr. 17, 18 · Tutorial
Likes (9)
Comment
Save
Tweet
Share
17.3K 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.

Related

  • The AI Firewall: Using Local Small Language Models (SLMs) to Scrub PII Before Cloud Processing
  • Understanding Java Signals
  • Java Bean Validation: Applying Constraints Programmatically
  • Hexagonal Architecture in the Frontend: A Real Case

Partner Resources

×

Comments

The likes didn't load as expected. Please refresh the page and try again.

  • RSS
  • X
  • Facebook

ABOUT US

  • About DZone
  • Support and feedback
  • Community research

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

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

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 215
  • Nashville, TN 37211
  • [email protected]

Let's be friends:

  • RSS
  • X
  • Facebook