|
Do you need help with your Java programming?
Click here for instant help with your Java code. |
A Simple Java Persistence API Entity
An Entity is much like a regular Java Bean. It has private properties that can be accessed through public get and set methods, and can be treated as such (a regular bean). The things that make this ordinary class an Enity are the annotations that enables the bean to be managed by the EJB container. This is what a class could look like without the annotations: |
public class Product { private long productId; private String productName; public long getProductId() { return productId; } public void setProductId(long productId) { this.productId = productId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } } |
This is what a class could look like WITH the annotations: |
import javax.persistence.Entity; import javax.persistence.Id; /** * * @author www.javadb.com */ @Entity public class Product { @Id private Long productId; private String productName; public Long getProductId() { return productId; } public void setProductId(Long productId) { this.productId = productId; } public String getProductName() { return productName; } public void setProductName(String productName) { this.productName = productName; } } |
The @Entity annotation is required to tell the EJB container that this class can be used to store information. The @Id annotation tells what unique identifier the instance can be selected on. This reflects the primary key in the database. In the case that the primary key spans multiple columns in the table, a composite primary key is required and the @Id fields may be replaced by a single field that is annotated @EmbeddedId. |
| Do you know your Java? | |
| Take a Ten-Question-Java-Quiz! | |
Search for code examples on this site
