Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lombok excluding field with @ToString.Exclude is not working

Tags:

java

lombok

I'm using Lombok to remove boilerplate code. I'm attempting to print out an entity to the console but I'm getting a StackOverflowError. The entity has a bidirectional relationship with another entity, so I want to exclude this entity from the toString method.

My entity looks like this:

@Entity
@Data
public class Foo {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long fooId;

    private String name;

    @ManyToOne
    @JoinColumn(name = "barId")
    @EqualsAndHashCode.Exclude
    @ToString.Exclude
    private Bar bar; 
}

This is my first time attempting to use @ToString.Exclude and it doesn't appear to be behaving. Am I using it incorrectly? I just want to print out fooId and name when I call toString on the Foo object.

Edit

I'm familiar with alternate approaches to excluding or including fields from a top level @ToString annotation. I'm attempting to avoid that. I just want to use @Data at the class level, and annotate the fields that should be excluded.

Edit 2

Still replicating on a simplified class. Lombok version 1.18.8.

enter image description here

like image 940
The Gilbert Arenas Dagger Avatar asked May 22 '19 19:05

The Gilbert Arenas Dagger


4 Answers

Works for me. lombok:1.18.8

import lombok.Data;
import lombok.ToString;

@Data
public class MyClass {
    public static void main(String args[]) {
        MyClass myClass = new MyClass();
        System.out.println("ToString::" + myClass);
    }

    private String a = "ABC";

    @ToString.Exclude
    private String b = "DEF";

}

Output: ToString::MyClass(a=ABC)

like image 160
Subir Kumar Sao Avatar answered Sep 28 '22 11:09

Subir Kumar Sao


@ToString takes an argument exclude, that can be used to exclude fields from to string.

@ToString(exclude = {"bar"})

@Entity
@ToString(exclude = {"bar"})
public class Foo {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long fooId;

    private String name;

    @ManyToOne
    @JoinColumn(name = "barId")
    @EqualsAndHashCode.Exclude
    private Bar bar; 
}
like image 44
ifelse.codes Avatar answered Sep 28 '22 11:09

ifelse.codes


You will have to update the lombok installed in your eclipse (download the new lombok.jar, run java -jar lombok.jar and restart Eclipse). At least that solved it for me.

like image 24
Robert Mikes Avatar answered Sep 28 '22 12:09

Robert Mikes


lombok : 1.18.12

@Exclude works for me. @Exclude is nothing but @ToString.Exclude only. @Exclude annotation is defined inside @ToString annotation.

@Entity
@Data
public class Foo {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private long fooId;

    private String name;

    @ManyToOne
    @JoinColumn(name = "barId")
    @EqualsAndHashCode.Exclude
    @Exclude
    private Bar bar; 
}
like image 36
ALS Avatar answered Sep 28 '22 13:09

ALS