0

I have an entity .

@Entity
@Table(name = "TABLE_NAME")
public class someName implements Serializable{
....
...
@ManyToOne
@JoinColumn(name="some", referencedColumnName="some_ID", updatable = false)
private Data data;
//corresponding getter and setter

public Data getData() {
    return data;
   }

public void setDataTYPE(Data data) { //this name is not in proper format
    this.data = data;
   }

}

Now when i do getData on this entity object, I get a null pointer exception although the object is not null. Code that generated the null pointer

if(someNameOBJ==null){
//Do something
}else{
 sysout(someNameOBJ.getData.getId);// It generates NPE
}

But when i changed my getter/setter to proper format (generate it from eclipse), the null pointer is gone.

public Data getData() {
   return data;
}
public void setData(Data data) { //this name is  in proper format
    this.data = data;
}

Why is the null pointer gone in this case? Does naming of getter/setter should be in proper format? If so why? I am aware of Java bean naming conventions, but what difference does a function name makes. (As I am always concerned about what a function does rather then what its name is). I am using hibernate and spring 3, java 1.6. I think it is a hibernate issue and something to do with reflection. Help me to find the root

pratim_b
  • 1,160
  • 10
  • 29

2 Answers2

0

Does naming of getter/setter should be in proper format?

Yes, Spring will search for getter/setter in proper format with variable name. Because there are many possibles ways to declared getter/setter and is depend on user, how he/she wants to give names.

But its difficult to search for all possible getter/setter method for Spring. So It use standard naming convention to access variable.

Vimal Bera
  • 10,346
  • 4
  • 25
  • 47
0

Basically, Hibernate will use gette and setter methods to reade and write data into/from database. Hibernate assumes that anything that it is writing to the database will eventually need to be read from the database.

now in first case when you try to save object into database hibernate call

public void setData(Data data)

method throw reflection(Hibernate will use reflection to access the setter) but hibernate will not get this method and save null into database (check your table) now when you call

getData()

method this will retun null value saved into database and throws Null Pointer Exception.

Ashish Jagtap
  • 2,799
  • 3
  • 30
  • 45