简体   繁体   中英

Loading an Object with getter and setter

I'm new in Java Objects and my question is:

  • I have the class Person
  • I am creating a new Object person5
  • I'm setting the ID to 5
  • Now I want that in my Object person5 are all information the person with the ID 5 has, are in the object person5
  • Then i want to get the age of the person5

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?

  1. You dont show us your getter and setter function
  2. replace your code with Person person5 = new Person(); person5.setID(5); person5.getAge(); Person person5 = new Person(); person5.setID(5); person5.getAge();
  3. you didnt set an age for the person. neither in the constructor nor as 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM