I am using JPA 2.1
and while persisting and retrieving the entities
from database
I could see no constructor
of the entity is called and not getters
and setters
. How does the serialization
and deserialization
take place then from DB
object to JAVA
object, if getters
, setters
and constructor
are not called
Teacher
@Entity
@Table(name="Teacher")
public class Teacher {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
int id;
@Column
String name;
public Teacher(String name) {
super();
this.name = name;
}
public Teacher()
{
System.out.println("const");
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Column
public String getName() {
System.out.println("get Name");
return name;
}
public void setName(String name) {
System.out.println("set Name");
this.name = name;
}
Main
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("persistence");
EntityManager em1 = entityManagerFactory.createEntityManager();
em1.getTransaction().begin();
Teacher t = new Teacher("wick");
em1.persist(t);
Teacher t1= em1.find(Teacher.class, 21);
em1.getTransaction().commit();
em1.close();
Hibernate and similar libraries and frameworks often don't use (and require) getters and setters for accessing the properties of an objects. Java has several methods for inspecting and manipulating objects directly. This is called reflection. The entry point for this are often the method of the class Class
from the Java Standard API. Each class in Java has an associated instance of these class which provides several methods for getting information about the class. For example the method getDeclaredFields
returns and array with data about all fields in the class. If you look into the documentation of the Field
class you see that there are several set methods which take an object (the instance of the object on which the value is set) and a value as parameters. This methods can also be used to bypass the access modifiers like private
etc.
Best
Jens
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.