2

Say I have a model with a many to many or many to one relationship. This model would like this:

@Entity
public class A {
  // other fields ...

  @OneToMany(...)
  private List<B> bEntities = new ArrayList<>();

}

There would be no reason to have a setter for this list but we would need a getter to be able to modify the list:

public List<B> getBEntities() { return bEntities; }

In this case, however, SpotBug is complaining about

EI_EXPOSE_REF: A.getBEntities() may expose internal representation by returning A.bEntities

I could map out the entire CRUD relationship into the model, like:

addB();
findBById();
// and so on and so forth

but not only would that still expose B entities, but also be out of the responsibility of the model as far as I understand. What is the proper way of doing this? Should I just suppress the warning for JPA managed entities?

5
  • possible duplicate? stackoverflow.com/questions/14124683/… Commented Oct 20 at 12:51
  • Not sure it would help the warning, but a get method could return an immutable copy of the list, and an add method could verify a B's key value is null. Commented Oct 20 at 14:58
  • @MartinFrank They don't really talk about the proper way or a solution to this in relation to JPA entities particularly. Commented Oct 20 at 15:16
  • @AndrewS Yes but if I return a immutable list, it breaks JPA's tracking and also I would have to model the whole list interface inside the model to provide full functionality. Commented Oct 20 at 15:18
  • @ÖzgürGüzeldereli the warning adresses a common clean code violation: martinfowler.com/bliki/TellDontAsk.html doesnt matter if you use entities or model classes Commented Oct 21 at 9:45

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.