Patrick Derckx
Patrick Derckx

Reputation: 201

Java Entity and BusinessObject without Code Duplication

I have a spring-data-jpa application and a library. The library contains a class, lets say Car.java

public class Car{
   Long id;
   String name;
   String color;
   .. getter and setter
}

In my application I need to store this object and want to use rest repositories. For that I need to annotate the class:

@Entity
@Table(name = "customerCar")
public class CarEntity{
   @Id
   Long id;
   String name;
   String color;
   .. getter and setter
}

Is there a way to do this without code duplication and/or without make a copy?

CarEntity customerCar = new CarEntity();
customerCar.setId(car.getId());
....

Upvotes: 0

Views: 141

Answers (2)

Patrick Derckx
Patrick Derckx

Reputation: 201

At least I endet in a very similar approach to @sham. I used the copy properties function of the BeanUtils Class from Spring Framework

org.springframework.beans.BeanUtils;
BeanUtils.copyProperties(car,carEntity);

Upvotes: 0

sham
sham

Reputation: 452

Use mapper framework to avoid copying boilerplate code. You can choose to use the JMapper mapping library based on the performance benchmarking mentioned below:

https://www.baeldung.com/java-performance-mapping-frameworks

Upvotes: 1

Related Questions