java web中entity的實現規範
阿新 • • 發佈:2019-02-08
在日常的Java專案開發中,entity(實體類)是必不可少的,它們一般都有很多的屬性,並有相應的setter和getter方法。entity(實體類)的作用一般是和資料表做對映。所以快速寫出規範的entity(實體類)是java開發中一項必不可少的技能。
在專案中寫實體類一般遵循下面的規範:
1、根據你的設計,定義一組你需要的私有屬性。
2、根據這些屬性,建立它們的setter和getter方法。(eclipse等整合開發軟體可以自動生成。具體怎麼生成?請自行百度。)
3、提供帶引數的構造器和無引數的構造器。
4、重寫父類中的eauals()方法和hashcode()方法。(如果需要涉及到兩個物件之間的比較,這兩個功能很重要。)
5、實現序列化並賦予其一個版本號。
下面是我寫的一個實體類(entity)例子:具體的細節都用註釋標註了。
1 class Student implements Serializable{
2 /** 3 * 版本號
4*/
5 private static final long serialVersionUID = 1L;
6 //定義的私有屬性
7 private int id;
8 private String name;
9 private int age;
10 private double score;
11 //無引數的構造器
12 public Student(){
13
14 }
15 //有引數的構造器
16 public Student(int id,String name,int age, double score){
17 this.id = id;
18 this.name = name;
19 this.age = age;
20 this.score = score;
21 }
22 //建立的setter和getter方法
23 publicint getId() {
24 return id;
25 }
26 publicvoid setId(int id) {
27 this.id = id;
28 }
29 public String getName() {
30 return name;
31 }
32 publicvoid setName(String name) {
33 this.name = name;
34 }
35 publicint getAge() {
36 return age;
37 }
38 publicvoid setAge(int age) {
39 this.age = age;
40 }
41 publicdouble getScore() {
42 return score;
43 }
44 publicvoid setScore(double score) {
45 this.score = score;
46 }
47 //由於id對於學生這個類是唯一可以標識的,所以重寫了父類中的id的hashCode()和equals()方法。
48 @Override
49 publicint hashCode() {
50 final int prime = 31;
51 int result = 1;
52 result = prime * result + id;
53 return result;
54 }
55 @Override
56 publicboolean equals(Object obj) {
57 if (this == obj)
58 return true;
59 if (obj == null)
60 return false;
61 if (getClass() != obj.getClass())
62 return false;
63 Student other = (Student) obj;
64 if (id != other.id)
65 return false;
66 return true;
67 }
68
69 }
一個學生的Java實體類就基本完成了。