Search code examples
javaeclipsejpacode-generationdto

Is there a way (e.g. an Eclipse plugin) to automatically generate a DTO from an Entity (JPA)?


I would like a plain forward DTO generation tool that would either

  1. Generate it on the fly (e.g. cglib - create the class and DTO object on the fly)
  2. Or an Eclipse plugin that will take the Entity and generate a DTO (user will specify which tree graph to include, and for non included, will include foreign keys instead of related entities etc)

E.g. take something like this

@Entity
@Table(name="my_entity")
public class MyEntity {
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String name;

    @ManyToOne
    private RelatedEntity related;
     public RelatedEntity getRelated(){
          return related;
     }
     ...

And generate something like this :

@Entity
@Table(name="my_entity")
public class MyEntity imlpements MyEntityDTO {
    @Id @GeneratedValue(strategy=GenerationType.AUTO)
    private Long id;
    private String name;

    @ManyToOne
    private RelatedEntity related;
     //overrides MyEntity interface, it's allowed to narrow return type 
     public RelatedEntity getRelated(){
          return related;
     }
     ...

     //implements MYEntityDTO respective interfaces

     public Long getRelatedId(){return related.getId();}

And DTO interface(s):

public interface MyEntityDTO {

    public String getId();
    public String getName();
    public Long getRelatedId();
    public RelatedEntityDTO getRelated(); //RelatedEntity implements RelatedEntityDTO

    ...
}

public interface RelatedEntityDTO {
    ... 
}

If we don't want to include children in the graph, remove it from the DTO interface:

public interface MyEntityDTO {

    public String getId();
    public String getName();
    public Long getRelatedId();

    ...

I'm sure there is some eclipse plugn for it and if not, I challange someone to write one, or explain why what I want is not helpful (and provide an alternative suggestion)


Solution

  • Probably Hibernate Tools should be doing this: http://hibernate.org/subprojects/tools.html