I'm writing a TodoList application using Playframework. I want to update a task but don't know how to update with JPA (I'm just moving from PHP with Zend Framework and don't familiar with Hibernate). I have edit page with URL for example: http://localhost:9000/TaskList/edit?id=2
Its controller:
开发者_如何学编程public static void edit(Long id) {
models.TaskList selectedTask = models.TaskList.findById(id);
render(selectedTask);
}
Its model
@Entity
public class TaskList extends Model {
public String task;
public int priority;
public String category;
public String taskStatus;
public TaskList(String task, int priority, String category, String taskStatus) {
this.task = task;
this.priority = priority;
this.category = category;
this.taskStatus = taskStatus;
}
Do I need id property in the model (in database, I have id field)? If not, how to update when the model doesn't specify the id?
Thank you all.
You don't need to define an id as the id is given by play.db.jpa.Model class.
Yet, if you want to define your own id, you can replace the extends Model
by extends GenericModel
and then you redefine your own @Id field such as (this is the code of Model class):
@Id
@GeneratedValue
public Long id;
Anyway, as you can see in the previous 3 lines of code, the Id by default a generated value. So you don't care about its value as it's given by the database when you first persist your object.
Now if you want to update your object, do:
public static void edit(Long id) {
// get your object
models.TaskList selectedTask = models.TaskList.findById(id);
// modify your object
selectedTask.something = somevalue;
// update your object
selectedTask.save();
// finally render your updated selectedTask
render(selectedTask);
}
That's all ;)
精彩评论