Entily

  在日常的Java项目开发中,entity(实体类)是必不可少的,它们一般都有很多的属性,并有相应的setter和getter方法。entity(实体类)的作用一般是和数据表做映射。所以快速写出规范的entity(实体类)是java开发中一项必不可少的技能。

  在项目中写实体类一般遵循下面的规范:

    1、根据你的设计,定义一组你需要的私有属性。

    2、根据这些属性,创建它们的setter和getter方法。(eclipse等集成开发软件可以自动生成。具体怎么生成?请自行百度。)

    3、提供带参数的构造器和无参数的构造器。

    4、重写父类中的eauals()方法和hashcode()方法。(如果需要涉及到两个对象之间的比较,这两个功能很重要。)

    5、实现序列化并赋予其一个版本号。

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

一个学生的Java实体类就基本完成了。

原文来自https://www.cnblogs.com/April315/p/10920603.html(讲的很明白就借鉴了)

原文地址:https://www.cnblogs.com/xiaohuomiao/p/11038946.html