简体   繁体   中英

Lombok EqualsAndHashCode with inheritance

I want to use lombok:EqualsAndHashCode considering only Id, setted on Item class, on top of a hierarchical strucure. These are my classes: 1.Process:

@Data
@Entity
@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
@ToString(callSuper = true)
public class Process extends ResourceWithFlows {

  @OneToOne
  private Cost cost;
  private UUID referenceProduct; //flowBaseId
  private UUID processBaseId;
  private UUID processTemplateId;
  private boolean paretoApplied;

  //ref
  @ManyToOne
  @JoinColumn(name = "fk_equipment")
  private Equipment equipment;

  @ManyToOne
  @JoinColumn(name = "fk_production_line")
  private ProductionLine productionLine;

  @ManyToOne
  @JoinColumn(name = "fk_company")
  private Company company;

  @ManyToOne
  @JoinColumn(name = "fk_supply_chain")
  private SupplyChain supplyChain;

}

2.ResourceWithFlows:

@Data
@Entity
@EqualsAndHashCode(callSuper = true, onlyExplicitlyIncluded = true)
@ToString(callSuper = true)
public class ResourceWithFlows extends Resource {
    @OneToMany
    @JoinColumn(name = "fk_flow")
    private Set<Flow> flows;
    @OneToMany
    @JoinColumn(name = "fk_elementary_flow")
    private Set<ElementaryFlow> elementaryFlows;
    
}

3.Item:

@Data
@Entity
@EqualsAndHashCode(onlyExplicitlyIncluded = true)
@Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public class Item {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @EqualsAndHashCode.Include
    private UUID id;
    private String name;
    private LocalDateTime creationDate;
    @Lob
    private String description;
    @OneToOne
    private AuthUser creatorUser;

    @PrePersist
    void creationDate () {
        this.creationDate = LocalDateTime.now();;
    }

}

Is it correct or is there another way to compare by Id the children of item like Process? I used callSuper=true and onlyExplicitlyIncluded=true in the children, setting @EqualsAndHashCode.Include on id attribute of the parent Item, but I'm not sure It's correct.

What you did does work, but seems completely unnecessary given your requirement. If you're only going to identify objects using the id field in the topmost class, there is no need to apply @EqualsAndHashCode everywhere down the hierarchy. The methods generated in Item will work for all subclasses.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM