3

I've written quite a lot of DAO class and using the JPA criteria API and its meta model in them, like in this example:

@Override
public EntityA findByEntityB(EntityB entityB) {
  CriteriaBuilder builder = this.getCriteriaBuilder();
  CriteriaQuery<EntityA> criteriaQuery = builder.createQuery(EntityA.class);
  Root<EntityA> root = criteriaQuery.from(EntityA.class);
  criteriaQuery.select(root);
  criteriaQuery.where(builder.and(builder.equal(root.get(EntityA_.entityB), entityB)));
  return this.findByCriteriaQuery(criteriaQuery);
}

While running static code analysis, FindBugs throws the following warning:

UWF_UNWRITTEN_PUBLIC_OR_PROTECTED_FIELD, Priorität: Normal

Unwritten public or protected field: EntityA_.entityB

No writes were seen to this public/protected field. All reads of it will return the default value. Check for errors (should it have been initialized?), or remove it if it is useless.

As I use the meta model classes in nearly all of my queries this warning is thrown very often.

Is there any useful way to avoid these warnings? As we all know the meta model classes are just generated and their attributs are never written.

I don't want to exclude the DAO classes from FindBugs sca as I want to check these to maybe find other possible bugs!

bish
  • 3,381
  • 9
  • 48
  • 69

4 Answers4

3

Here are some ideas:


1 - The setter could potentially be declared as private. There is a good chance that FindBugs doesn't check that the setter is called.

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • 1
    As it seems, that there is no programmatic way to avoid these errors, but only ignore them I add a filter in my findbugs configuration. – bish Sep 15 '17 at 14:43
1

Possible duplicate of How to suppress FindBugs warnings for fields or local variables.

You can extract a method and apply method level @SuppressFBWarnings to that method.

Anand Mattikopp
  • 332
  • 2
  • 11
  • 3
    I want to avoid this warnings, not supress / ignore them. – bish Sep 13 '17 at 06:17
  • 1
    I'm facing the same issue.I don't think it's a duplicate, it's linked to JPA meta model. I'm looking for a programmatic way to clean properly these warnings. – sofien.lpx Jan 07 '20 at 07:59
0

You can add the Setter of these fields, then it's able to remove the FindBugs error message

Yasir Shabbir Choudhary
  • 2,458
  • 2
  • 27
  • 31
0

This is the code marking the violation:

https://github.com/spotbugs/spotbugs/blob/267af9fe850a7637252a748f7ce3483fab80968c/spotbugs/src/main/java/edu/umd/cs/findbugs/detect/UnreadFields.java#L1000

After reading the code there are two suggestions:

  1. Add a @NotNull to the field (This way the field find its way into the collection writtenNonNullFields and the violation is ignored).

  2. A bad idea (but possible from the source) to place a native method in the dto class (native void hi();). But I do strongly not recommend that.

I tried both and both works fine.

Grim
  • 1,938
  • 10
  • 56
  • 123