简体   繁体   中英

Lombok excluding field with @ToString.Exclude is not working

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.

在此处输入图片说明

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)

@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; 
}

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.

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; 
}

In Kotlin

You could avoid using the Lombok library and define a custom annotation @ExcludeToString to exclude the redundant parameter or what you need.

GL

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