问题
I am trying to use ORMLite for database persistence in Android project. It looks all good from examples. Once I start to use it, I found I do not completely understand its requirement and behavior.
Let's say I have a class called Bone which I would like to persist.
@DatabaseTable(tableName = "bones")
public class Bone{
// user defined
@DatabaseField(dataType = DataType.STRING)
private String color;
@DatabaseField
private double length;
@DatabaseField
private int quantity;
// db assigned
@DatabaseField(generatedId = true)
private int id;
public Bone(){
}
// constructors
public Bone(String color, int quantity) {
this(color, quantity, 0);
}
public Bone(String color, int quantity, int id) {
this.color = color;
this.quantity = quantity;
this.id = id;
}
public Bone(Bone old, int id){
this.color = old.color;
this.length = old.length;
this.quantity = old.quantity;
this.id = id;
}
public String getColor() {
return color;
}
public double getLength() {
return length;
}
public int getQuantity() {
return quantity;
}
public void setLength(double length) {
this.length = length;
}
public int getId() {
return id;
}
}
What are the requirements for the names of getters and setters of its fields? Does their names make any difference? Can I use one without getter and setter?
Besides no arg constructor, any other constructor is needed?
Please help.
回答1:
1) What are the requirements for the names of getters and setters of its fields? Does their names make any difference? Can I use one without getter and setter?
There are no requirements for getters and setters. By default ORMLite uses reflection to build the entity fields directly.
If you set the useGetSet = true field of the @DatabaseField annotation then you do neet get/set methods. See the javadocs for the format.
2) Besides no arg constructor, any other constructor is needed?
No. You only need an accessible no-arg constructor for ORMLite to instantiate the object prior to the reflection work.
来源:https://stackoverflow.com/questions/16780874/do-i-need-getters-and-setters-and-extra-entity-constructors