Java中(entity)實體類的書寫規范


在日常的Java項目開發中,entity(實體類)是必不可少的,它們一般都有很多的屬性,並有相應的setter和getter方法。entity(實體類)的作用一般是和數據表做映射。所以快速寫出規范的entity(實體類)是java開發中一項必不可少的技能。

  在項目中寫實體類一般遵循下面的規范:

    1、根據你的設計,定義一組你需要的私有屬性。

    2、根據這些屬性,創建它們的setter和getter方法。(eclipse等集成開發軟件可以自動生成。具體怎么生成?請自行百度。)

    3、提供帶參數的構造器和無參數的構造器。

    4、重寫父類中的eauals()方法和hashcode()方法。(如果需要涉及到兩個對象之間的比較,這兩個功能很重要。)

    5、實現序列化並賦予其一個版本號。

下面是我寫的一個實體類(entity)例子:具體的細節都用注釋標注了。

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;
    }
    
}

這樣就寫好了一個學生的實體類


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM