Java entity classes-the use and learning of entity classes

1. Preface (Extension of Project Code)

In a developed android project, the Entity class
Insert picture description here
is used. SecurityDomain is an architecture template that can be ignored. The remaining four Entity classes are expanded according to actual functional requirements. The four entity classes in the project are in (1) the corresponding Fragment class (2) Repository (3) Used in VehicleViewModel.
These four Entity classes contain construction methods. The is and set methods are written for the function of the switch, and the get and set methods are written for the function of setting options.

set and get are completely self-defined, which means setting initial values ​​and obtaining values. You can also modify it to other characters. But it is better to use set and get, because you can understand the meaning of the code you write through words, which is easier to read.

Here is an example of CommonEntity that contains is, set, and get methods. Take a look at the code:

public class CommonEntity {
    
    
    private int drivingMode;
    private int lampMode = -1;
    private boolean epbRelease;
    private boolean escSwitch;
    private boolean autoHoldSwitch;

    public CommonEntity(int drivingMode, int lampMode, boolean epbRelease, boolean escSwitch, boolean autoHoldSwitch) {
    
    
        this.drivingMode = drivingMode;
        this.lampMode = lampMode;
        this.epbRelease = epbRelease;
        this.escSwitch = escSwitch;
        this.autoHoldSwitch = autoHoldSwitch;
    }

    public boolean isEscSwitch() {
    
    
        return escSwitch;
    }

    public void setEscSwitch(boolean escSwitch) {
    
    
        this.escSwitch = escSwitch;
    }

    public boolean isAutoHoldSwitch() {
    
    
        return autoHoldSwitch;
    }

    public void setAutoHoldSwitch(boolean autoHoldSwitch) {
    
    
        this.autoHoldSwitch = autoHoldSwitch;
    }


    public boolean isEpbRelease() {
    
    
        return epbRelease;
    }

    public void setEpbRelease(boolean epbRelease) {
    
    
        this.epbRelease = epbRelease;
    }

    public int getDrivingMode() {
    
    
        return drivingMode;
    }

    public void setDrivingMode(int drivingMode) {
    
    
        this.drivingMode = drivingMode;
    }

    public int getLampMode() {
    
    
        return lampMode;
    }

    public void setLampMode(int lampMode) {
    
    
        this.lampMode = lampMode;
    }
}

After designing these four entity classes, I became curious about the specific functions and related knowledge of the entity classes, so I went to find related articles to understand them carefully. After studying, I found that the Entity class I wrote is relatively simple, and I have a deeper understanding of the specific content of the entity class (Entity).

2. Many understandings of entity classes

Many understandings of java entity classes:

A. Is the attribute class, which is usually defined in the model layer.
B. The general entity class corresponds to a data table, and the attributes correspond to the fields in the data table.
Benefits:
1. Encapsulate the object entity, embodying OO thinking.
2. Attributes can judge and filter the field definition and status.
3. After the relevant information is encapsulated with an entity class, we can pass the entity class as a parameter in the program, which is more convenient.
C. To put it bluntly, it is to allow programmers to not write SQL statements when operating on the database
. D. It is a database table to generate a class.
This is convenient for database operations.
Writing less code to improve efficiency allows programmers to focus on the logical relationship
E. entity class is to operate on one table all written in a class.
F. often define some entity classes in Java development, the definition of these classes is good or bad will directly affect the quality and ease of writing code
G . Entity classes are all instance objects. The instance object opens up a reference space for the object in the heap area of ​​the jvm, and makes the reference point to an instance. The class declaration just opens up a reference to the object in the jvm stack. Did not let the reference do any pointing.
For example: 1.String
str;
2.String str = new String ("dgfgg");
1 is just a reference, indicating that str should point to an instance of the String type, but not str Make a specific point with the instance of the heap area. That is to say, it has not pointed to a certain instance.
And the 2 defines a reference (str) and makes a specific point to str, and the content it points to is new later. String instance.

Summary: The entity is the O/R Mapping mapping in Java, that is, a table in the database is mapped to a corresponding Java class, and there is also a mapping file. Given a more complex entity relationship (such as one-to-one, one-to-many, many-to-many), you should skillfully write entity classes!!

Three, the role of entity classes

The entity class is actually commonly known as POJO , this class generally does not implement the interface under the special framework, and is only used as a data container for persistent storage of data in the program.

POJO (Plain Old Java Objects) simple Java objects

Its general format is

public class A{
    
    
      private String id;
      public String getId(){
    
    
           return this.id;
      }
      public void setId(String id){
    
    
           this.id = id;
      }
}

In fact, the meaning of writing this way lies in encapsulation . ID is a member variable of class A, also called attribute. Under normal circumstances, it has the ability to read and write. If we set id to private, it cannot be directly operated externally. At the same time, through set The method provides a method for externally changing its value, and also enables the outside world to read the value of the member variable through the get method.

I mentioned POJO here. I was reading the Alibaba Java Development Manual recently , and I added a little bit about the naming convention of the POJO programming specification:
Insert picture description here

Fourth, the writing specifications of entity classes

In the daily development of Java projects, entities (entity classes) are indispensable. They generally have many properties and corresponding setter and getter methods. The role of entity (entity class) is generally to map with the data table. So quickly writing a standardized entity (entity class) is an indispensable skill in java development.

Writing entity classes in the project generally follows the following specifications:
1. The name of the entity class should be the same as the name of the database table as far as possible.
2. Realize serialization , that is, realize the java.io.Serializable interface .
3. The entity class has properties and methods. The properties correspond to the fields of the table in the database. There are mainly getter and setter methods, namely:
(1) According to your design, define a set of private properties you need.
(2) Based on these properties, create their setter and getter methods.
4. Provide a constructor (method) without parameters.
5. Provide a constructor (method) with parameters.
6. The entity class should also have an attribute serialVersionUID, which gives it a version number. For example: private static final long serialVersionUID = -6125297654796395674L;
7. Override the eauals() method and hashcode() method in the parent class. (If you need to involve comparison between two objects, these two functions are very important.)
8. The attribute is generally of private type, and the method is public . The set method of the attribute corresponding to the ID field automatically generated by the database should be private .

An entity class (entity) example: specific details have been annotated.

class Student implements Serializable{
    
    
    /**
     * 版本号
     */
    private static final long serialVersionUID = 1L;
    //定义的私有属性
    private int id;
    private String name;
    private int age;
    private double score;
    //无参数的构造器
    public Student(){
    
    
        
    }
    //有参数的构造器
    public Student(int id,String name,int age, double score){
    
    
        this.id = id;
        this.name = name;
        this.age = age;
        this.score = score;
    }
    //创建的setter和getter方法
    public int getId() {
    
    
        return id;
    }
    public void setId(int id) {
    
    
        this.id = id;
    }
    public String getName() {
    
    
        return name;
    }
    public void setName(String name) {
    
    
        this.name = name;
    }
    public int getAge() {
    
    
        return age;
    }
    public void setAge(int age) {
    
    
        this.age = age;
    }
    public double getScore() {
    
    
        return score;
    }
    public void setScore(double score) {
    
    
        this.score = score;
    }
    //由于id对于学生这个类是唯一可以标识的,所以重写了父类中的id的hashCode()和equals()方法。
    @Override
    public int hashCode() {
    
    
        final int prime = 31;
        int result = 1;
        result = prime * result + id;
        return result;
    }
    @Override
    public boolean equals(Object obj) {
    
    
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Student other = (Student) obj;
        if (id != other.id)
            return false;
        return true;
    }
    
}

Five, the necessity of serialization

In Java, everything is an object. In a distributed environment, it is often necessary to pass Objects from one end of the network or device to the other end. This requires a protocol that can transmit data at both ends. The Java serialization mechanism was created to solve this problem.

Java object serialization not only retains the data of an object , but also recursively saves the data of each object referenced by the object .

Java serialization technology allows you to write the state of an object into a Byte stream, and read the data in the Byte stream from other places to reconstruct an identical object. This mechanism allows you to propagate objects through the network , and you can persist objects to databases, files, and other systems at any time . The serialization mechanism of Java is the technical foundation of RMI, EJB and other technologies. Purpose: Use the serialization of the object to save the current working state of the application, and it will automatically restore to the state of the last execution when it is restarted next time.

Serialization is a mechanism for processing object streams . The so-called object stream is to stream the content of the object. You can read and write the streamed objects, and you can also transfer the streamed objects between networks . Serialization is to solve the problems caused by reading and writing the object stream.

For an object that exists in the Java virtual machine, its internal state is only kept in memory. After the JVM is stopped, these states are lost. In many cases, the internal state of the object needs to be persisted . When it comes to persistence, the most direct way is to save it to the file system or database . This approach generally involves custom storage formats and tedious data conversion . Object-Relational Mapping (Object-relationalmapping) is a typical relational database for persistent objects embodiment , there are many objects in the database object stored directly . The object serialization mechanism (objectserialization) is a built-in method of object persistence in the Java language , which can easily convert between active objects and byte arrays (streams) in the JVM . In addition to the simple implementation of persistence , another important use of the serialization mechanism is in remote method calls to shield developers from the underlying implementation details .

Reference: https://blog.csdn.net/qijingwang/article/details/80353829

Guess you like

Origin blog.csdn.net/ambitionLlll/article/details/111192094