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
Newsletter
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

  • Testing Asynchronous Systems, Part 3: Message Semantics, Observability, and a Test Checklist
  • Seven Failure Modes Every HTTP Client Should Handle: Lessons From Fixing 31 Bugs
  • Beyond the Wall of Charts: How Advanced Observability Displaced the Telemetry Dashboard
  • Migrating My Java Codebase to EE10

Draft This article hasn't been published, so readers can't see it.

In moderation This article is waiting for review, so readers can't see it yet.

Deleted This article has been deleted, so readers can't see it.

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
·
Apr. 17, 18 · Tutorial
Post on X (opens in a new tab) Share on LinkedIn (opens in a new tab)
17.6K Views

Join the DZone community Save articles, join the discussion, and download Refcards and Trend Reports with a free account.

Join for free Already a member? Log in

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

Loading comments

The comments didn't load

Please try again in a moment.

Likes

Loading

The next likes didn't load. Please try again.

The likes didn't load

Please try again in a moment.

See who liked this

Log in or join DZone for free to see who liked this article.

Log in Join for free
  • 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