Friday, February 14, 2014

Defining Persistent Objects

The persistent objects can be defined either in xml file, or using annotation. The annotation method is easy to define simple relationship while defining in xml file provides more flexibility.

This article demonstrates, rather shortcut, how we can create persistence objects:

//Base Class
public abstract class BaseClass implements Interface{
@Column(name = "id")
private int id

private String unwantedField;

public int getId(){
    return id;

public void setId(int id){;

//Child Class
@Table(name = "table_name")
public class ChildClass extends BaseClass{

@Column(name = "user_name")
private String useName;

@OneToMany(cascade = CascadeType.ALL, orphanRemoval = true, fetch = FetchType.EAGER)
@JoinColumn(name = "id")
private List comments;

//Associated class
@Table(name = "another_table")
public class AnotherClass {
@Column(name = "comment_id") //this can not be "id", because "id" is referenced from ChildClass
private int id;
@JoinColumn(name = "id") //this id is child class identifier column
private ChildClass child;


In above example, we implemented one to many relationship from ChildClass to AnotherClass instances.(Getters and setters not shown above). So, the "id" in "another_table" is foreign key from the table "table_name".

[Note: Annotations should be either at properties definition or at getters(CAN'T  be mixed).]

No comments:

Post a Comment