0

I annotate with Lombok. I need to override the setter method of one of the attributes. But this is not working.

I have annotated the property with @Setter(AccessLevel.NONE) and then calling explicitly setProperty.

The bean is mention below.

@Data
@AllArgsConstructor
@Slf4j
public class TestDto
{

    private String code;

    @Setter(AccessLevel.NONE)
    private String nameCode;

    public void setNameCode(String nameCode)
    {
        log.info("  nameCode   {}", nameCode);
        this.nameCode = <Call to some method>;
    }

}

The DTO in which list of bean is getting set.

@Data
@NoArgsConstructor
@AllArgsConstructor
public class TestViewDto {
    private List<TestDto> testDtoList;
    .............Few more dto's..............................
    }

And this is been called from service below line..

travelAgentViewDto.setTestDto(repository.findTestNumber(number);

Repository interface is defined below:

public interface Repository extends JpaRepository<Address, AddressPk> {
        public List<TestDto> findTestNumber(String number);

}

The code is working fine. Only issue is when overriding the setNameCode the same is not going inside setter.

From setNameCode method the below log should print: log.info(" nameCode {}", nameCode)

In actual the call is not going there.

Michael Piefel
  • 18,660
  • 9
  • 81
  • 112
Rahul
  • 95
  • 1
  • 3
  • 14
  • Maybe the JpaRepository is using your `@AllArgsConstructor` instead of using your setter. – Shane Haw Oct 25 '19 at 11:47
  • I think JPA uses reflection or some other approach to get data from db to pojo – Ryuzaki L Oct 25 '19 at 11:48
  • Try using [delombok](https://projectlombok.org/features/delombok) to see what lombok does to your code, when you might be able to see what's going wrong. – Andreas Oct 25 '19 at 11:50

2 Answers2

5

As @Ravik mentioned, you don't need to explicitly tell lombok not to generate the setter; the fact that you wrote one means that one 'wins' and lombok won't generate that setter in the first place.

The reason you're not seeing that setter being invoked is... because JPA doesn't invoke it. You have an @AllArgsConstructor annotation; THAT is being invoked by JPA. I'm not too familiar with JPA; however, I suggest you use @NoArgsConstructor instead, thus forcing JPA to use the setters.

rzwitserloot
  • 85,357
  • 5
  • 51
  • 72
  • Quite generally, whenever setting an attribute needs special handling, use the special handling everywhere. And don’t forget serialization… – Michael Piefel Oct 26 '19 at 08:42
2

You don't need to use

 @Setter(AccessLevel.NONE)

As the annotation will hide the setter method. Instead just add the setter method and it will work.

Michael Piefel
  • 18,660
  • 9
  • 81
  • 112
Ravik
  • 694
  • 7
  • 12