EJB Entities

download EJB Entities

of 106

Transcript of EJB Entities

  • 8/13/2019 EJB Entities

    1/106

    Page 1

    Crayom

    Crayom EngineeringServicesPresents

    EJB 3 0 Workshop

  • 8/13/2019 EJB Entities

    2/106

    Page 2

    Domain Model

    Object Relational Mapping

    Entity Manager

    Query API and JPQL

    CrayomTopics

  • 8/13/2019 EJB Entities

    3/106

    Page 3

    Represents the entities in the system and the relationships

    between them.

    CrayomDomain Model

  • 8/13/2019 EJB Entities

    4/106

    Page 4

    Objects Data

    Behaviour

    Relationships

    Unidirectional Bidirectional

    Cardinality or Multicipity

    One to one

    One to Many

    Many to Many

    Ordinality or Optionality

    CrayomDomain Model Actors

  • 8/13/2019 EJB Entities

    5/106

    Page 5

    Lets build a data model which shows different relationship

    CrayomDomain Model Actors

    Student Country

    Language

    Address

    n

    1 n 11

    n

    Phone

    1

    n

  • 8/13/2019 EJB Entities

    6/106

    Page 6

    Object Relational Mapping

    CrayomORM

    RelationalDatabase

    OO WorldORM

    save objects

    Sql forupdate/insert

    Result Setobjects

  • 8/13/2019 EJB Entities

    7/106

    Page 7

    @Entity

    public class Student {

    protected long id;

    private String firstName;

    private String lastName;@Id

    public long getId() {

    return id;

    }

    public void setId(long id) {

    this.id = id;

    }

    CrayomMaking POJO an entityAnnotation for entity bean

    Annotation for primary key

  • 8/13/2019 EJB Entities

    8/106

    Page 8

    Default : Property based persistence

    For field based persistence make all variables public orprotected and ask the persistence provider to ignoregetters/setters. Make an indication on at least one of theinstance variable

    @Id

    public Long id;

    CrayomField v/s property based persistence

  • 8/13/2019 EJB Entities

    9/106

    Page 9

    Java primitives

    Java primitive wrappers (Integer, Double)

    String Type

    Serializable type (Predefined and User defined) (BigInteger,

    Date) Array types byte[ ], char[ ]

    Enumerated Types

    Collection Set

    Embeddable class @Embeddable

    CrayomPersistent Data types

  • 8/13/2019 EJB Entities

    10/106

    Page 10

    @Table

    name

    catalog

    schema

    @Entity

    @Table(name = "STUDENT_TABLE")

    public class Student {

    CrayomSchema Mapping

  • 8/13/2019 EJB Entities

    11/106

    Page 11

    @Column name

    unique

    nullable

    insertable

    updatable

    length precision

    scale

    @Column(name = "FIRST_NAME")public String getFirstName() {

    return firstName;}

    CrayomSchema Mapping

  • 8/13/2019 EJB Entities

    12/106

    Page 12

    @Target ({METHOD, FIELD})

    @Retention (RUNTIME)

    public @interface Column{

    String name() default ;

    boolean unique() default false;

    boolean nullable() default true;

    boolean insertable() default true;

    boolean updatable() default true;

    String columnDefinition() default ;

    String table() default ;

    int length() default 255;

    int precision() default 0;

    int scale default 0;

    }

    CrayomColumn Annotation

  • 8/13/2019 EJB Entities

    13/106

    Page 13

    A primary key is the identity of a given entity bean.

    Every entity bean must have a primary key and it must be

    unique.

    Natural keys vs Surrogate keys

    @Id

    @IdClass

    @EmbeddedId

    CrayomEntity Identity (Primary Keys)

  • 8/13/2019 EJB Entities

    14/106

    Page 14

    Identifies one or more properties that make up the primary key.

    @Id

    @GeneratedValue

    @Column(name = "STUDENT_ID")

    public String getId() {return id;

    }

    Crayom@Id

    Key generation forPrimitive Primary keys

  • 8/13/2019 EJB Entities

    15/106

    Page 15

    Generator.AUTO is by default which lets the persistence

    provider to generate the key.

    The other strategies are

    Table Generators

    Sequence Generators

    Crayom@GeneratedValue

  • 8/13/2019 EJB Entities

    16/106

    Page 16

    Creating sequence generation table

    CREATE TABLE GENERATOR_TABLE

    (PRIMARY_KEY_COLUMN VARCHAR2(80) NOT NULL,

    VALUE_COLUMN NUMBER(15) NOT NULL,

    PRIMARY KEY (PRIMARY_KEY_COLUMN));

    Inserting SequenceINSERT INTO GENERATOR_TABLE

    (PRIMARY_KEY_COLUMN , VALUE_COLUMN)

    VALUE(STUDENT_SEQUENCE,1);

    CrayomTable Generators

  • 8/13/2019 EJB Entities

    17/106

    Page 17

    A user defined table from which primary keys are generated

    @TableGenerator(name="STUDENT_GENERATOR",table="GENERATOR_TABLE",pkColumnName="PRIMARY_KEY_COLUMN",valueColumnName="VALUE_COLUMN",

    pkColumnValue="STUDENT_ID",allocationSize=10)

    @Id@GeneratedValue(strategy=GenerationType.TABLE,generator="STUDENT_GENERATOR")public long getId() {

    return id;}

    CrayomTable Generators

  • 8/13/2019 EJB Entities

    18/106

  • 8/13/2019 EJB Entities

    19/106

    Page 19

    Sequence generator especially in Oracle

    @Entity

    @SequenceGenerator(name="STUDENT_SEQUENCE",

    sequenceName="STUDENT_SEQUENCE" )

    public class Student {

    @Id

    @GeneratedValue(strategy=GenerationType.SEQUENCE,

    generator="STUDENT_SEQUENCE")protected long id;

    CrayomSequence Generators

  • 8/13/2019 EJB Entities

    20/106

    Page 20

    Used in case of Composite keys

    Primary key class must be serializable

    Must have a public no-arg constructor

    Must implement equals() and hashCode() methods.

    Crayom@IdClass annotation

  • 8/13/2019 EJB Entities

    21/106

  • 8/13/2019 EJB Entities

    22/106

    Page 22

    @Entity

    @IdClass(StudentPk.class)

    public class StudentIdClass {

    .

    @Idpublic String getFirstName() {

    return firstName;

    }

    @Id

    public String getLastName() {

    return lastName;

    }

    Crayom@IdClass annotation

  • 8/13/2019 EJB Entities

    23/106

    Page 23

    Another way of doing composite keys is to embed the primary

    key class directly into entity class

    @Embeddable

    public class StudentPkEmbedded {

    @Column(name="FIRST_NAME")

    public String getFirstName() {

    return firstName;

    }

    @Column(name="LAST_NAME")

    public String getLastName() {return lastName;

    }

    Crayom@EmbeddedId annotation

  • 8/13/2019 EJB Entities

    24/106

    Page 24

    Using the key in entity class

    @Entity

    public class StudentEmbeddedId {

    protected StudentPkEmbedded studentPk;

    @EmbeddedId

    public StudentPkEmbedded getStudentPk() {

    return studentPk;

    }

    Crayom@EmbeddedId annotation

  • 8/13/2019 EJB Entities

    25/106

    Page 25

    If the column name needs to be overridden than we can@AttributeOverrides. We may even skip @Column on Primarykey class

    @EmbeddedId

    @AttributeOverrides({

    @AttributeOverride(name="firstName",column=@Column(name="FIRSTNAME")),

    @AttributeOverride(name="lastName",

    column=@Column(name="LASTNAME"))})

    public StudentPkEmbedded getStudentPk() {

    Crayom@EmbeddedId annotation

  • 8/13/2019 EJB Entities

    26/106

    Page 26

    Annotations to fine tune the mappings

    @Transient

    @Basic and FetchType

    @Temporal

    @Lob @Enumerated

    CrayomProperty Mappings

  • 8/13/2019 EJB Entities

    27/106

  • 8/13/2019 EJB Entities

    28/106

    Page 28

    Controls when the property value is initialized.

    Fetch attribute is just a hint.

    Its not really a performance gain for basic properties.

    @Basic(fetch=FetchType.LAZY)public String getFirstName() {

    return firstName;

    }

    Crayom@Basic and FetchType

  • 8/13/2019 EJB Entities

    29/106

    Page 29

    Allows to map the property of Date or Calender

    TemporalType are

    DATE

    TIME

    TIMESTAMP

    @Temporal(TemporalType.TIMESTAMP)

    public Date getBirthDate() {

    return birthDate;

    }

    Crayom@Temporal

  • 8/13/2019 EJB Entities

    30/106

    Page 30

    Allows to map large binary or text data

    Properties are saved as

    Blob for type byte[], Byte[]

    Clob for type char[], Character[]

    @Lob

    @Basic(fetch=FetchType.LAZY)

    public byte[] getPicture() {

    return picture;

    }

    Crayom@Lob

    Good idea to fetch largeObjects lazily

  • 8/13/2019 EJB Entities

    31/106

    Page 31

    Maps Java enum types to the database

    Define the Enum

    public enum StudentType {

    CURRENT,ALUMNI

    }

    Use in entity

    @Enumerated(EnumType.STRING)

    public StudentType getStudentType() {

    return studentType;

    }

    Crayom@Enumerated

    If EnumType is omittedORDINAL is taken by default

  • 8/13/2019 EJB Entities

    32/106

    Page 32

    To map one logical entity stored in two different tables

    @Entity@Table(name = "STUDENT")

    @SecondaryTable(name="STUDENT_DETAIL",

    pkJoinColumns={@PrimaryKeyJoinColumn(name="STUDENT_DETAIL_ID")

    })

    public class Student {

    @Column(name="PERCENTAGE", table="STUDENT_DETAIL")

    public int getPercentage() {return percentage;

    }

    Crayom@SecondaryTable

  • 8/13/2019 EJB Entities

    33/106

    Page 33

    If there are more than one secondary table use@SecondaryTables annotation

    Crayom@SecondaryTables

  • 8/13/2019 EJB Entities

    34/106

    Page 34

    For embedding non entity java objects

    These objects do not have any identity and owned exclusivelyby the containing entity bean class

    Define the embedded class

    @Embeddable

    public class Address implements Serializable{

    protected String street;

    protected String city;

    Crayom@Embeddable annotation

  • 8/13/2019 EJB Entities

    35/106

    Page 35

    Use in entity class

    @Embedded

    public Address getAddress() {

    return address;

    }

    If the column name needs to be overridden

    @Embedded

    @AttributeOverrides({

    @AttributeOverride(name="street",column=@Column(name="STREET_NAME"))

    })

    public Address getAddress() {

    return address;

    }

    Crayom@Embeddable annotation

  • 8/13/2019 EJB Entities

    36/106

    Page 36

    Relationships

    @OneToOne

    @OneToMany

    @ManyToOne

    @ManyToMany

    Directionality

    Unidirectional

    Bidirectional

    CrayomEntity Relationships

  • 8/13/2019 EJB Entities

    37/106

    Page 37

    Entity relationships mapping is done to facilitate navigation inObject world. Even if not mapped, we can fetch the data quries.

    For mapping entity relationships mapping concentrate on your

    domain/object model requirements.

    CrayomEntity Relationships

  • 8/13/2019 EJB Entities

    38/106

    Page 38

    Lets make our Address as entity so that it will have its own

    table to persist data.

    @Entity

    public class Address implements Serializable{

    protected String id;

    .@Id

    @GeneratedValue

    @Column(name="ADDRESS_ID")

    public String getId() {

    return id;

    }

    Crayom@OneToOne Unidirectional

  • 8/13/2019 EJB Entities

    39/106

    Page 39

    Mapped in Student entity

    @OneToOne(cascade={CascadeType.ALL})

    @JoinColumn(name="ADDRESS_ID")

    public Address getAddress() {

    return address;

    }

    Crayom@OneToOne UnidirectionalDefines cascade type

    Student

    Student_ID

    Address_ID

    ADDRESS

    ADDRESS_ID1 1

  • 8/13/2019 EJB Entities

    40/106

    Page 40

    Sometimes we map by making primary key of tables common

    instead of using a join column

    @OneToOne(cascade={CascadeType.ALL})

    @PrimaryKeyJoinColumn

    public Address getAddress() {

    return address;

    }

    Crayom@OneToOne Unidirectional

    idi i l

  • 8/13/2019 EJB Entities

    41/106

    Page 41

    When both side of entity needs to maintain the reference of

    each other. This is facilitated for navigation only and does not affect the

    relational model.

    Crayom@OneToOne Bidirectional

    STUDENT

    STUDENT_ID

    BANK_ACCOUNT_ID

    BANK_ACCOUNT

    BANK_ACCOUNT_ID1 1

    @O T O Bidi i l

  • 8/13/2019 EJB Entities

    42/106

    Page 42

    Student entity

    @OneToOne(cascade={CascadeType.ALL})

    @JoinColumn(name="BANK_ACCOUNT_ID")

    public BankAccount getBankAccount() {

    return bankAccount;}

    Crayom@OneToOne Bidirectional

    @O T O Bidi ti l

  • 8/13/2019 EJB Entities

    43/106

    Page 43

    BankAccount entity

    @Entitypublic class BankAccount {

    protected long id;

    protected String accountNumber;

    protected Student student;

    @Id

    @GeneratedValue

    @Column(name="BANK_ACCOUNT_ID")

    public long getId() { return id; }

    @OneToOne(mappedBy="bankAccount")

    public Student getStudent() { return student; }

    Crayom@OneToOne Bidirectional

    mappedBy denotes thatthe other side is theowning entity

    @O T O Bidi ti l

  • 8/13/2019 EJB Entities

    44/106

    Page 44

    OneToOne Bidirectional in action

    Student student = new Student();

    student.setFirstName("Saurav");

    student.setLastName("Ganguly");

    BankAccount bankAccount = new BankAccount();

    bankAccount.setAccountNumber("ANMF1933");

    student.setBankAccount(bankAccount);

    studentService.saveStudent(student);

    //studentService.saveBankAccount(bankAccount);

    Crayom@OneToOne Bidirectional

    @O T O Bidi ti l

  • 8/13/2019 EJB Entities

    45/106

    Page 45

    If a bank account has to be assigned to a different student, than

    unset the bankAccount on the original student and set it into thenew student.

    For deleting a bankaccount, unset it from the student object and

    than remove it from database calling remove method on entity

    manager.

    Crayom@OneToOne Bidirectional

    @OneToMan nidi ectional

  • 8/13/2019 EJB Entities

    46/106

    Page 46

    Lets have a set of phone numbers owned by a Student.

    Crayom@OneToMany unidirectional

    STUDENT

    STUDENT_ID

    PHONE

    PHONE_ID

    STUDENT_ID

    1 0:n

    @OneToMany unidirectional

  • 8/13/2019 EJB Entities

    47/106

    Page 47

    No reference to Student object though in the data table we

    maintain the relationship in the Phone Table

    @Entitypublic class Phone implements Serializable{

    protected int id;protected String number;

    @Id@GeneratedValue@Column(name="PHONE_ID")public int getId() {

    Crayom@OneToMany unidirectional

    @OneToMany unidirectional

  • 8/13/2019 EJB Entities

    48/106

    Page 48

    Student Bean

    @OneToMany(cascade={CascadeType.ALL})public Collection getPhoneList() {

    if(phoneList == null){phoneList = new ArrayList();

    }return phoneList;}

    Crayom@OneToMany unidirectional

    @OneToMany unidirectional

  • 8/13/2019 EJB Entities

    49/106

    Page 49

    Join Table Mapping If we want the relationship data to be

    managed in a join table

    @OneToMany(cascade={CascadeType.ALL})

    @JoinTable(name="STUDENT_PHONE",

    joinColumns={@JoinColumn(name="STUDENT_ID")},

    inverseJoinColumns={@JoinColumn(name="PHONE_ID")})public Collection getPhoneList() {

    if(phoneList == null){

    phoneList = new ArrayList();

    }

    return phoneList;}

    Crayom@OneToMany unidirectional

    @ManyToOne Unidirectional

  • 8/13/2019 EJB Entities

    50/106

    Page 50

    When many entity beans refer to a single entity but the referred

    bean is unaware of the reference.

    Crayom@ManyToOne Unidirectional

    STUDENT

    STUDENT_ID

    COUNTRY_ID

    COUNTRY

    COUNTRY_ID0:n 1

    @ManyToOne Unidirectional

  • 8/13/2019 EJB Entities

    51/106

    Page 51

    Country entity bean

    @Entity

    public class Country implements Serializable{

    protected long id;

    protected String name;

    @Id

    @GeneratedValue

    @Column(name="COUNTRY_ID")

    public long getId() {

    return id;

    }

    Crayom@ManyToOne Unidirectional

    @ManyToOne Unidirectional

  • 8/13/2019 EJB Entities

    52/106

    Page 52

    Student bean

    @ManyToOne

    @JoinColumn(name="COUNTRY_ID")

    public Country getCountry() {

    return country;}

    We are not using cascade option here.

    Crayom@ManyToOne Unidirectional

    @ManyToOne Unidirectional

  • 8/13/2019 EJB Entities

    53/106

    Page 53

    Saving student

    Country country = new Country();

    country.setName("India");

    country = studentService.saveCountry(country);

    student.setCountry(country);studentService.saveStudent(student);

    Crayom@ManyToOne Unidirectional

    @ManyToOne Bidirectional

  • 8/13/2019 EJB Entities

    54/106

    Page 54

    Many to one and One to many are two sides of the same

    relationship. Lets convert Student and Country into bidirectional relationship.

    @OneToMany(mappedBy="country")

    public Collection getStudentList() {

    return studentList; }

    For persistence to work we have to call student.setCountry. If

    we just call country.getStudentList().add(student), therelationship will not change in the database.

    Always wire both side of relationship

    Crayom@ManyToOne Bidirectional

    The owning side of the Relationshipshould be ManyToOne

    @ManyToMany Unidirectional

  • 8/13/2019 EJB Entities

    55/106

    Page 55

    ManyToMany relationship happens when both side maintains

    collection based relationship. Lets take an example of Student and Language they speak.

    A student can speak many language. Similarly a language

    can be spoken by many students

    Language Entity bean

    @Entity

    public class Language implements Serializable{

    protected long id;

    protected String name;

    Crayom@ManyToMany Unidirectional

    @ManyToMany Unidirectional

  • 8/13/2019 EJB Entities

    56/106

    Page 56

    Student Bean

    @ManyToMany

    @JoinTable(name="STUDENT_LANGUAGE",

    joinColumns={@JoinColumn(name="STUDENT_ID")},

    inverseJoinColumns={@JoinColumn(name="LANGUAGE_ID")})

    public Collection getLanguageList() {

    return languageList;

    }

    Crayom@ManyToMany Unidirectional

    @ManyToMany Bidirectional

  • 8/13/2019 EJB Entities

    57/106

    Page 57

    Language Bean

    @ManyToMany(mappedBy="languageList")

    public Collection getStudentList() {

    return studentList;

    }

    For modifying the same ownership rule applies as we have seenin other bidirectional relationships.

    Crayom@ManyToMany Bidirectional

    Student side is the

    owning side.

    Mapping Collection based relationship

  • 8/13/2019 EJB Entities

    58/106

    Page 58

    The collection can be fetched in certain order. E.g if we want to

    fetch the list of languages in certain order we can say on theStudent side of relationship

    @ManyToMany

    @OrderBy(name = ASC)

    @JoinTable(name="STUDENT_LANGUAGE",

    joinColumns={@JoinColumn(name="STUDENT_ID")},

    inverseJoinColumns={@JoinColumn(name="LANGUAGE_ID")})

    public List getLanguageList() {

    return languageList;

    }

    For descending order use name=DESC

    CrayomMapping Collection based relationship

    ORM again

  • 8/13/2019 EJB Entities

    59/106

    Page 59

    Mismatch between Relational and OO world References v/s Primary Key

    Inheritance

    Polymorphism

    CrayomORM again

    Mapping inheritance

  • 8/13/2019 EJB Entities

    60/106

    Page 60

    Single Table per class hierarchySingle table has all propertiesof every class in the hierarchy.

    Table per concrete classEach subclass has a table having all

    the properties of super class also.

    Table per subclassEach class is mapped in its own table.

    There is separate table for super class and subclass.

    CrayomMapping inheritance

    Mapping inheritance

  • 8/13/2019 EJB Entities

    61/106

    Page 61

    Lets map a simple domain model for this:

    Crayomapp g e ta ce

    User

    Name(String)

    Employee

    rank(String)

    Customer

    creditLimit(double)

    Single Table per class hierarchy

  • 8/13/2019 EJB Entities

    62/106

    Page 62

    Single table strategy

    Uses Discriminator column User Entity

    @Entity

    @Inheritance(strategy=InheritanceType.SINGLE_TABLE)

    @DiscriminatorColumn(name="DISCRIMINATOR",

    discriminatorType=DiscriminatorType.STRING)

    @DiscriminatorValue("USER")

    @Table(name="BASIC_USER")

    public class User implements Serializable{

    protected long id;

    protected String name;

    Crayomg p y

    Single Table per class hierarchy

  • 8/13/2019 EJB Entities

    63/106

    Page 63

    Customer Entity

    There is no id field

    @Entity

    @DiscriminatorValue("CUST")public class Customer extends User{

    protected double creditLimit;

    Crayomg p y

  • 8/13/2019 EJB Entities

    64/106

    Single Table per class hierarchy

  • 8/13/2019 EJB Entities

    65/106

    Page 65

    Advantages

    Simplest to implement.

    Only one table to deal with.

    Performance wise better than all strategies because no joins

    or sub-selects need to be performed.

    Disadvantages:

    Most of the column of table are nullable so the NOT NULL

    constraint cannot be applied.

    Tables are not normalized.

    Crayomg p y

    Table per concrete class

  • 8/13/2019 EJB Entities

    66/106

    Page 66

    A database table is defined for each concrete class

    User entity

    @Entity

    @Inheritance(strategy=InheritanceType.TABLE_PER_CLASS)

    @Table(name="BASIC_USER")public class User implements Serializable{

    protected long id;

    protected String name;

    Not mandatory to support this strategy

    Crayomp

    Table per concrete class

  • 8/13/2019 EJB Entities

    67/106

    Page 67

    Advantage:

    Possible to define NOT NULL constraints on the table.

    Disadvantage:

    Tables are not normalized.

    To support polymorphism either container has to do multipletrips to database or use SQL UNION kind of feature.

    Crayom

    Table per subclass

  • 8/13/2019 EJB Entities

    68/106

    Page 68

    Each subclass has its own table

    User entity

    @Entity

    @Inheritance(strategy=InheritanceType.JOINED)

    @Table(name="BASIC_USER")public class User implements Serializable{

    protected long id;

    protected String name;

    Crayom

    Table per subclass

  • 8/13/2019 EJB Entities

    69/106

    Page 69

    Employee entity

    @Entity

    @PrimaryKeyJoinColumn(name="EMPLOYEE_ID")

    public class Employee extends User{

    protected String rank;

    CrayomIf different columnname is desired.

    Table per subclass

  • 8/13/2019 EJB Entities

    70/106

    Page 70

    Advantage:

    Tables are normalized.

    Able to define NOT NULL constraint.

    Disadvantage:

    Does not perform as well as SINGLE_TABLE strategy

    Crayom

    Mapping inheritance

  • 8/13/2019 EJB Entities

    71/106

    Page 71

    CrayomFeature Single Table Table per

    subclassTable per

    concrete class

    Table Support Mandatory columnmay be nullable.

    Table grows withsubclasses

    Mapped tables arenormalized

    One table for eachclass in the entityhierarchy

    Uses discriminatorcolumn

    Yes Yes No

    SQL for retrieval Simple SELECT SELECT clause joiningmultiple table

    One SELECT for eachtable or UNIONSELECT

    Insert and Update Single INSERT orUPDATE

    Multiple INSERT orUPDATE. One for rootclass and one for eachinvolved subclasses.

    One INSERT orUPDATE for eachsubclass

    Polymorphicrelationship

    Good Good Poor

    Support in EJB 3JPA

    Mandatory Mandatory Optional

    Nonentity Base class

  • 8/13/2019 EJB Entities

    72/106

    Page 72

    Inheriting from a non entity super class.

    Lets say we want to put Audit information in all tables

    @MappedSuperclass

    public class Audit {

    protected Date updateDate;

    protected Date createDate;

    .

    Crayom

    Nonentity Base class

  • 8/13/2019 EJB Entities

    73/106

    Page 73

    User entity bean

    @Entity

    @Inheritance(strategy=InheritanceType.JOINED)

    @Table(name="BASIC_USER")

    @AttributeOverride(name="createDate",column=@Column(name="CREATE_DATE"))

    public class User extends Audit implements Serializable{

    .

    CrayomIf column name needs

    to be overridden

    CrayomEntity Manager

  • 8/13/2019 EJB Entities

    74/106

    Page 74

    RelationalDatabase

    OO World

    EntityManager

    save objects

    Sql forupdate/insert

    Result Setobjects

    CrayomLife cycle of an Entity

  • 8/13/2019 EJB Entities

    75/106

    Page 75

    new managed Removed

    Detached

    Persisted

    new() persist()

    merge/refreshOut of scope/Serialized/ clones

    find()query

    remove()

    CrayomPersistence Context

  • 8/13/2019 EJB Entities

    76/106

    Page 76

    Entity manager delegates the task of managing entities to

    Persistence Context. Transaction Scoped Entity ManagerEntities attached during a

    transaction are automatically detached at the end of transaction.

    Extended Entity ManagerEntities are managed beyond

    transaction boundaries.

    CrayomEntity Manager

  • 8/13/2019 EJB Entities

    77/106

    Page 77

    Container Managed Entity Manager

    @Stateless

    public class StudentService{

    @PersistenceContext(unitName=ejbBasics)

    private EntityManager entityManager;

    public Student save Student(String firstName,String lastName){

    Student student = new Student();

    student.setFirstName(firstName);

    student.setLastName(lastName);

    entityManager.persist(student);return student;

    CrayomEntity Manager

  • 8/13/2019 EJB Entities

    78/106

    Page 78

    Application Managed Entity Manager

    @PersistenceUnit

    private EntityManagerFactory entityManagerFactory;

    private EntityManager entityManager;

    ..

    entityManager = entityManagerFactory.createEntityManager();

    CrayomEntity Manager - Persisting

  • 8/13/2019 EJB Entities

    79/106

    Page 79

    Inserts the entity into database.

    Based on the cascading policy the other related entities mightbe persisted.

    public Student saveStudent(Student student){

    entityManager.persist(student);return student;

    }

    CrayomEntity Manager Finding entities

  • 8/13/2019 EJB Entities

    80/106

    Page 80

    Entities can be located by its primary key.

    Two different methods that allow to find an entity by primary key:

    T find(class entityClass, Object primaryKey)

    T getReference(Class entityClass, Object primaryKey)

    find() method returns null if the entity is not found in thedatabase.

    getReference() throws EntityNotFoundException

    CrayomEntity Manager Updating entities

  • 8/13/2019 EJB Entities

    81/106

    Page 81

    If the entity is fetched, the entity bean remains managed by the

    persistence context until the context is closed. Any change inthe entity state is synchronized automatically

    public void updateStudent(long primaryKey,String name){

    Student student = entityManager.find(Student.class,

    primaryKey);

    student.setFirstName("Mithun");

    }

    Update the entity. Synchronization willbe taken care by PersistenceContext

    CrayomEntity Manager Merging entities

  • 8/13/2019 EJB Entities

    82/106

    Page 82

    To merge state changes of detached entity back into

    persistence context managed entity. We can fetch a student entity in client and than make local

    changes in client. The changes can be merged back by calling

    merge method

    public Student updateStudent(Student student){

    Student mergedStudent = entityManager.merge(student);

    }

    If the entity manager is not managing the student entity, it will

    create a new managed student entity and return it back. If the entity manager is managing the student entity, it will copy

    the changes into the managed entity.

    CrayomEntity Manager Removing entities

  • 8/13/2019 EJB Entities

    83/106

    Page 83

    Entities are deleted from the database by calling remove

    method.

    entityManager.remove(student);

    Associated relationships will also be removed based on

    cascading rule.

    CrayomEntity Manager Refresh

  • 8/13/2019 EJB Entities

    84/106

    Page 84

    Refresh is opposite of merger. It will update the entity in memory

    from the values in database.

    entityManager.refresh(student);

    Crayomcontains and clear

  • 8/13/2019 EJB Entities

    85/106

    Page 85

    contains method tells if the entity is currently being managed. It

    takes entity as a parameter. clear detached all managed entities from a persistence context.

    Calling clear will result is changes made to entities getting lost.

    Better to call a flush before clear is called

    Crayomflush and FlushModeType

  • 8/13/2019 EJB Entities

    86/106

    Page 86

    flush synchronizes the changes made into entities to the

    database. By default flushing happens automatically.

    FlushModeType decides when the flush will be called.

    public enum FlushModeType{

    AUTO,COMMIT

    }

    COMMIT means that changes are flushed only when the

    transaction commits.

    CrayomQuery and EJB QL

  • 8/13/2019 EJB Entities

    87/106

    Page 87

    Query helps in pulling data from database in a flexible way.

    EJB QL is the declarative query language similar to SQL andsupports most of the artifact of SQL

    EJB QL is issued to database using Query interface.

  • 8/13/2019 EJB Entities

    88/106

    CrayomQuery API

  • 8/13/2019 EJB Entities

    89/106

    Page 89

    To fetch list of students

    Query query = entityManager(Select s from Student s);

    return query.getResultList();

    If we know that only one object will be returned

    Student student = (Student)query.getSingleResult();

    CrayomQuery API

  • 8/13/2019 EJB Entities

    90/106

    Page 90

    Parameters

    String queryString = "Select s from Student s " +

    " where s.firstName = :first and s.lastNane = :last ";

    Query query = entityManager(queryString);

    query.setParameter(first, first);query.setParameter(last, last);

    return query.getResultList();

    Positional parameters can be used in place of named

    parameters

    String queryString = "Select s from Student s " +" where s.firstName = ?1 and s.lastNane = ?2 ";

    CrayomQuery API

  • 8/13/2019 EJB Entities

    91/106

    Page 91

    Date Parameters

    setParameter(String name, Date date, TemporalType tType);

    setParameter(String name, Calendar value,

    TemporalType tType);

    CrayomPaging

  • 8/13/2019 EJB Entities

    92/106

    Page 92

    Suppose you want to retrieve first 25 entities

    query.setMaxResults(25);

    query.setFirstResult(0);

    List students = query.getResultList();

    CrayomSelecting Properties

  • 8/13/2019 EJB Entities

    93/106

    Page 93

    To retrieve specific properties

    Select s.firstName,s.lastName from Student s

    Parsing Results

    List resultList = query.getResultList();

    for(Object[] result: resultList){

    String first = (String)result[0];

    String last = (String)result[1];

    }

    CrayomSelecting Properties

  • 8/13/2019 EJB Entities

    94/106

    Page 94

    The properties navigation can be done to any depth. There

    should not be a collection in the dive

    Select s.address.city from Student s;

    We can fetch the properties in a user defined object also

    package com.crayom

    public class Name{

    String firstName;

    String lastName; ..

    Select new com.crayom.Name(s.firstName,s.lastName) from..

    CrayomIN operator and Inner join

  • 8/13/2019 EJB Entities

    95/106

    Page 95

    Getting all the phones of student

    Select p from Student s, IN(s.phoneList) p

    If we just want numbers

    Select p.number from Student s, IN(s.phoneList) p

    Query in inner join format

    Select p from Student s INNER JOIN s.phoneList p

    CrayomLeft Join and Fetch Join

  • 8/13/2019 EJB Entities

    96/106

    Page 96

    Getting all the student first name, last name and city

    Select s.firstName, a.city from Student s LEFT JOIN s.address a

    Fetch joinThis is important when we want to fetch the

    collection eagerly which is marked as lazily invoked in the entitydefinition

    Select s from Student s LEFT JOIN FETCH s.phoneList

    In this case one query is issued to database instead of N+1

    queries and can improve the performance dramatically

    CrayomOther Query features

  • 8/13/2019 EJB Entities

    97/106

    Page 97

    Where clause

    Select s from Student where s.address.city = Kothrud;

    We can use following operators

    Arithmetic operator

    Select c from Customer c where (c.creditLimit * 100) >

    100000

    Logical operator

    Select c from Customer c where (c.creditLimit * 100) >

    100000AND(c.creditLimit * 100) < 1000000000 Equality

    Select s from Student s where s = :studentEntity

    CrayomOther Query features

  • 8/13/2019 EJB Entities

    98/106

    Page 98

    Operators

    BetweenSelect c from Customer c where c.creditLimit BETWEEN100000 AND 10000000

    In

    Select s from Student s where s.address.city IN(DADAR)

    Select s from Student s where s.address.city NOT IN(DADAR)

    Is Null

    Select s from Student s where s.address IS NULL

    IS NOT NULL

    Is EmptySelect s from Student s where s.phoneList IS EMPTY

    IS NOT EMTPY

    CrayomOther Query features

  • 8/13/2019 EJB Entities

    99/106

    Page 99

    MEMBER OFWhether an entity is a member of specific

    collection. LIKETo match specified pattern

    Functional Expressions

    LOWER(String)

    UPPER(String)

    TRIM(String) MAX

    MIN

    AVG

    SUM

    Order By

    Group By

    Subqueries

    CrayomBulk Update and Delete

  • 8/13/2019 EJB Entities

    100/106

    Page 100

    Bulk update

    UPDATE Student s SET s.firstName = Sachin

    Bulk Delete

    DELETE Student s WHERE s.firstName like Shyam

    CrayomQuery API

  • 8/13/2019 EJB Entities

    101/106

    Page 101

    Named Query

    @NamedQuery{

    name=findAllStudents,

    query=SELECT s from Student s where

    s.firstName LIKE :firstName)

    Query query = em.createNamedQuery(findAllStudents);

    CrayomNative Query

  • 8/13/2019 EJB Entities

    102/106

    Page 102

    EJB QL should serve most of the purpose but if we want we can

    issues native SQL queries directly Native queries

    For scalar results

    createNativeQuery(String sql)

    Results of Sql statement are implicitly mapped to entity

    based on mapping metadata

    createNativeQuery(String sql, Class entityClass)

    Complex mapping based on native SQL where we retrieve

    values from different tables

    createNativeQuery(String sql, String mappingName)

    CrayomStatement Type

  • 8/13/2019 EJB Entities

    103/106

    Page 103

    Types Reserved Words

    Statementsand Clauses

    SELECT,UPDATE,DELETE,FROM,WHERE,GROUP,HAVING,OREDER BY,ASC,DESC

    Joins JOIN,OUTER,INNER,LEFT,FETCH

    Conditions andOperators

    DISTINCT,OBJECT,NULL,TRUE,FALSE,NOT,AND,OR,

    BETWEEN,LIKE,IN,AS,UNKNOWN,EMPTY,MEMBER,OF,

    IS,NEW,EXISTS,ALL,ANY,SOME

    Functions AVG,MAX,MIN,SUM,COUNT,MOD,UPPER,LOWER,TRIM,

    POSITION,CHARACTER_LENGTH,CHAR_LENGTH,BIT_LENGTH,CURRENT_TIME,CURRENT_DATE,CURRENT_TIMESTAMP

    CrayomEntity Lifecycle Listener

  • 8/13/2019 EJB Entities

    104/106

    Page 104

    Provides mechanism to intercept in lifecycle. Can be used for

    auditing information PrePersist

    PostPersist

    PostLoad

    PreUpdate

    PostUpdate

    PreRemove

    PostRemove

    For callback to work we need to annotate methods with the

    annotation given above@PostPersist

    void afterInsert() {

    CrayomEntity Listener

  • 8/13/2019 EJB Entities

    105/106

    Page 105

    Classes that can generically intercept entity callback events.

    They van be attached to an entity. This way common callbackevents can be placed at one place.

    public class AuditLogger{

    @Postpersist

    void afterInsert(Object entity) {

    @Entity

    @EntityListeners(Audit.class)

    public class Student{ For setting default entity listeners to be applied on all entities we

    need to register it into XML file.

    Crayom

  • 8/13/2019 EJB Entities

    106/106

    Thank you