I'm new in Java Objects and my question is:
When I debugged my code only the ID was set to 5 all other variables were null.
Person person5 = new Person();
person5.setID(5);
person5.getAge();
@Id @Column(name = "ID")
private Integer id;
@Column(name = "AGE")
private Integer age;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
What am I doing wrong? Can somebody help me?
Person person5 = new Person(); person5.setID(5); person5.getAge();
Person person5 = new Person(); person5.setID(5); person5.getAge();
person5.setAge(X)
this question is very common and you should visit some tutorial pages. stackoverflow isn't one.
Person person5 = new Person();
You created a new Person
person5.setID(5);
You decided that the ID of the newly created person will be 5.
person5.getAge();
Since you haven't explicitly told Java to change the age of the person from what was set by the constructor, it will tell you what it was told, which is nothing .
Now I want that in my Object person5 are all information the person with the ID 5 has, is in the object person5
At this point, Java knows nothing about which person5 you are talking about. If you want it to have all the attributes of a similar person, you'll have to tell Java to either set all those attributes into your object or create a new one using values (from DB presumably).
It is better to clear up doubts on OOPS before getting into deeper concepts like DB connectivity.
Seems you are using JPA. Then, the correct way of retrieving information from the database is not simply new-ing an object and setting the id, you would have to fetch it from the database, through EntityManager
:
final Person person5 = em.find(Person.class, 5);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.