0

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());
....
Patrick Derckx
  • 173
  • 2
  • 14
  • You can use mapstruct, a lib that will get rid of the copy boilerplate code. – daniu May 19 '21 at 18:06
  • https://stackoverflow.com/questions/15117403/dto-pattern-best-way-to-copy-properties-between-two-objects – sham May 19 '21 at 18:11
  • That is what project LomBok is all about and one of the reasons it is so widely used. [Start Here](https://www.baeldung.com/intro-to-project-lombok) – Randy Casburn May 19 '21 at 18:24
  • Actually I was already interested in using project Lombok for my project (due to other reasons). So I had a look into the article but I can’t find how project Lombok will help me? Did I missed anything? @Casburn – Patrick Derckx May 20 '21 at 19:49
  • Mapstruct is an option, but nothing is wrong with writing mappers manually. When mapping manually, you don't need to keep in mind if mapstruct can do it's magic or not. Another option is to dump JPA for jdbc so you can reuse your code domain in the infrastructure layer. Personally, I prefer to map things manually and I also prefer working without JPA. – Nico Van Belle May 25 '21 at 12:29

2 Answers2

1

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

sham
  • 422
  • 4
  • 18
0

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);
Patrick Derckx
  • 173
  • 2
  • 14