In a Service I want to set the betrag for a BudgetGeschaeftfeld. After setting the Betrag, a method of budgetPlan which is Fetch.Eager should be called to update its own Betrag. However I get a NullPointerException
java.lang.NullPointerException: Cannot invoke "com.bm.ent.budgetplan.BudgetPlan.berechnePrognose()" because "this.budgetPlan" is null
why is this happening? and what can I do to solve it?
my Class code:
@Entity(name= "Budgetgeschaftsfeld")
@Getter
@Setter
@NoArgsConstructor
public class BudgetGeschaeftsfeld extends Budget{
@JsonIgnore
@OneToMany(
mappedBy="budgetGeschaftfeld",
cascade=CascadeType.ALL,
orphanRemoval=true,
targetEntity = BudgetMarke.class
)
private List<BudgetMarke> childBudgets= new ArrayList<>();
@JsonIgnore
@ManyToMany
@ToString.Exclude
private List<User> users= new ArrayList<>();
@JsonIgnore
@ManyToOne( fetch=FetchType.EAGER,
cascade=CascadeType.PERSIST)
@JoinColumn(name="pid")
@ToString.Exclude
private BudgetPlan budgetPlan;
public BudgetGeschaeftsfeld(String name, BudgetTyp typ, Double betrag, String kommentar) {
super(name, typ, betrag, kommentar);
}
public void setBetrag(Double betrag) {
if (this.getBudgetTyp()==BudgetTyp.DYNAMISCH) {
super.setBetrag(this.betragChildBudgets());
}else {
super.setBetrag(betrag);
}
budgetPlan.berechnePrognose();
}
CodePudding user response:
I think it's because you named a class but did not set an instance in memory of that class, because having this in your code is the same as = null
:
private BudgetPlan budgetPlan;
So when your code executes with budgetPlan.berechnePrognose();
it cannot allocate anything in the memory.
Try:
@JsonIgnore
@ManyToOne( fetch=FetchType.EAGER,
cascade=CascadeType.PERSIST)
@JoinColumn(name="pid")
@ToString.Exclude
private BudgetPlan budgetPlan = new BudgetPlant();
Disclaimer: I have no experience with all the annotations in there, so maybe I'm missing the logic of this entire code but just make sure BudgetPlan budgetPlan != null
.
CodePudding user response:
The answer was
@JsonIgnore
@ManyToOne( fetch=FetchType.Lazy,
cascade=CascadeType.PERSIST)
@JoinColumn(name="pid")
@ToString.Exclude
private BudgetPlan budgetPlan;
and then getting the budgetplan before calling the method
public void setBetrag(Double betrag) {
if (this.getBudgetTyp()==BudgetTyp.DYNAMISCH) {
super.setBetrag(this.betragChildBudgets());
}else {
super.setBetrag(betrag);
}
detBudgetPlan().berechnePrognose();
}