JPA Notes

JPA
The Java Persistence API (JPA) is the Java standard for mapping Java objects to a relational database. 


  • The basic unit of persistence in JPA is the entity
  •  Every entity class should have an @Entity marker and primary key column identifier field, indicated by @Id.
  • you are not required to specify table names and column names that an entity is mapped. JPA will take default values as same as entitiy class having.
  • To override default values, you can use mapping matadata.

@Table on the entity class -> the table name explicit
@Column on the field->maps particular column.
@JoinColumn on the field ->override the name of the foreign key column for relationship references.

Ex:
An example of two mapped entities are the Pet and Owner classes shown in Listings 1 and 2.

Listing 1 - Pet entity class

@Entity
@Table(name="PET_INFO")
public class Pet {
@Id
@Column(name="ID")
int licenseNumber;
String name;
PetType type;
@ManyToOne
@JoinColumn(name="OWNER_ID")
Owner owner;
...
}
Listing 2 - Owner entity class
@Entity
public class Owner {
@Id
int id;
String name;
@Column(name="PHONE_NUM")
String phoneNumber;
@OneToOne
Address address;
@OneToMany(mappedBy="owner")
List<Pet> pets;
...
}

In a bidirectional relationship pair,
@OneToMany relationship in Owner to Pet and
@ManyToOne relationship back from Pet to Owner,

only one foreign key is required in one of the tables to manage both sides of the relationship. As a general rule, the side that does not have the foreign key in it specifies a mappedBy attribute in the relationship annotation and specifies the field in the related entity that maps the foreign key.


The possible mapping annotations that can be used are:
@Basic      @Enumerated  @ManyToOne  @Temporal
@Embedded   @Lob         @OneToMany  @Transient
@EmbeddedId @ManyToMany  @OneToOne
@AttributeOverride(s)    @PrimaryKeyJoinColumn(s)
@AssociationOverride(s)  @SecondaryTable(s)
@Column                  @SequenceGenerator
@DiscriminatorColumn     @Table  
@JoinColumn(s)           @TableGenerator  
@JoinTable
@Entity          @IdClass             @MappedSuperclass
@Embeddable      @Inheritance         @OrderBy
@GeneratedValue  @DiscriminatorValue  @Version
@Id              @MapKey

No comments:

Post a Comment

JAVA NOTES

  click here  👉  Interview  Preparation : complete notes sql queries notes ============================================================ Con...