Java Reference
In-Depth Information
real-world entity and its instances will be persisted to a database. Remember that for each entity class to
be persisted by an ORM framework, a default constructor with no argument is required.
package com.apress.springenterpriserecipes.course;
...
public class Course {
private Long id;
private String title;
private Date beginDate;
private Date endDate;
private int fee;
// Constructors, Getters and Setters
...
}
For each entity class, you must define an identifier property to uniquely identify an entity. It's a best
practice to define an auto-generated identifier because this has no business meaning and thus won't
be changed under any circumstances. Moreover, this identifier will be used by the ORM framework to
determine an entity's state. If the identifier value is null , this entity will be treated as a new and unsaved
entity. When this entity is persisted, an insert SQL statement will be issued; otherwise an update
statement will. To allow the identifier to be null , you should choose a primitive wrapper type like
java.lang.Integer and java.lang.Long for the identifier.
In your course management system, you need a DAO interface to encapsulate the data access logic.
Let's define the following operations in the CourseDao interface:
package com.apress.springenterpriserecipes.course;
...
public interface CourseDao {
public void store(Course course);
public void delete(Long courseId);
public Course findById(Long courseId);
public List<Course> findAll();
}
Usually, when using ORM for persisting objects, the insert and update operations are combined into
a single operation (e.g., store). This is to let the ORM framework (not you) decide whether an object
should be inserted or updated.
In order for an ORM framework to persist your objects to a database, it must know the mapping
metadata for the entity classes. You have to provide mapping metadata to it in its supported format.
The native format for Hibernate is XML. However because each ORM framework may have its own
format for defining mapping metadata, JPA defines a set of persistent annotations for you to define
mapping metadata in a standard format that is more likely to be reusable in other ORM frameworks.
Hibernate also supports the use of JPA annotations to define mapping metadata, so there are
essentially three different strategies for mapping and persisting your objects with Hibernate and JPA:
Using the Hibernate API to persist objects with Hibernate XML mappings
Using the Hibernate API to persist objects with JPA annotations
Using JPA to persist objects with JPA annotations
Search WWH ::




Custom Search