在日常的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; -
} -
}
这样就写好了一个学生的实体类
本文详细介绍了在Java项目中如何规范地编写实体类(entity),包括属性定义、构造器、getter和setter方法、重写equals和hashCode方法以及实现序列化。通过一个学生实体类的例子,展示了完整的实体类编写过程。
4465

被折叠的 条评论
为什么被折叠?



