+ All Categories

JPA

Date post: 07-Nov-2014
Category:
Upload: navis-pretheeba-santhana-raj
View: 88 times
Download: 0 times
Share this document with a friend
Description:
Notes
Popular Tags:
34
OrderBy is used when you have a persistent field in the entity of the collection by which you want to order. For example,if you had a field named "joiningDate" in Employee class, you could do: @Entity public class Department{ @OneToMany @OrderBy("joiningDate") //or @OrderBy("joiningDate DSC") or @OrderBy("joiningDate ASC") List<Employee> employees; //when you retrieve this collection, elements will be ordered by joiningDate ascending (by default). } No additional database column is created because the existing joiningDate field is used. Only single state field expressions can be used. OrderColumn is used to preserve order of elements in which they were added in a collection. There is no additional persistent field required in the collection entity, however, an additional database column is created. For example: @Entity public class CustomerOrder{ @OneToMany @OrderColumn // an additional column LINEITEM_ORDER will be created in the db, //though there is no persistent field corresponding to this column in LineItem entity. //It is used transparently by the persistence provider. List<LineItem> lineItems; } The OrderColumn annotation specifies a column that is used to maintain the persistent order of a list. The persistence provider is responsible for maintaining the order upon retrieval and in the database. The persistence provider is responsible for updating the ordering upon flushing to the database to reflect any insertion, deletion, or reordering affecting the list. The OrderColumn annotation may be specified on a one-to-many or many-to-many relationship or on an element collection. The OrderColumn annotation is specified on the side of the relationship that references the collection that is to be ordered. The order column is not visible as part of the state of the entity or embeddable class. Using @OrderColumn is appropriate here because this will not require you to have any additional field in Student or Course class. It will create an
Transcript

OrderBy is used when you have a persistent field in the entity of the collection by which you want to order. For example,if you had a field named "joiningDate" in Employee class, you could do:@Entitypublic class Department{ @OneToMany @OrderBy("joiningDate") //or @OrderBy("joiningDate DSC") or @OrderBy("joiningDate ASC") List<Employee> employees; //when you retrieve this collection, elements will be ordered by joiningDate ascending (by default).}No additional database column is created because the existing joiningDate field is used.Only single state field expressions can be used.

OrderColumn is used to preserve order of elements in which they were added in a collection. There is no additional persistent field required in the collection entity, however, an additional database column is created.

For example:@Entitypublic class CustomerOrder{ @OneToMany @OrderColumn // an additional column LINEITEM_ORDER will be created in the db, //though there is no persistent field corresponding to this column in LineItem entity. //It is used transparently by the persistence provider. List<LineItem> lineItems;}The OrderColumn annotation specifies a column that is used to maintain the persistent order of a list. The persistence provider is responsible for maintaining the order upon retrieval and in the database. The persistence provider is responsible for updating the ordering upon flushing to the database to reflect any insertion, deletion, or reordering affecting the list. The OrderColumn annotation may be specified on a one-to-many or many-to-many relationship or on an element collection. The OrderColumn annotation is specified on the side of the relationship that references the collection that is to be ordered. The order column is not visible as part of the state of the entity or embeddable class.Using @OrderColumn is appropriate here because this will not require you to have any additional field in Student or Course class. It will create an additional column in the join table to maintain the order but that is totally transparent to the application and will be used behind the scenes by the persistence provider.

ExceptionsRemember that all the exceptions defined in javax.persistence extend from javax.persistence.PersistenceException, which in turn extends from java.lang.RuntimeException.

Further, all instances of PersistenceException except for instances of NoResultException, NonUniqueResultException, LockTimeoutException, and QueryTimeoutException will cause the current transaction, if one is active, to be marked for rollback.

This means the transaction will be marked for roll back if the persistence provider throws :-

EntityExistsException, EntityNotFoundException, OptimisticLockException, PessimisticLockException.

Persist-It will throw EntityExistsException if the entity already exists. The EntityExistsException may be thrown when the persist operation is invoked, or the EntityExistsException or another PersistenceException may be thrown at flush or commit time and the transaction will be rolled back.persisting a removed entity will make it managed and persisting a detached entity will throw EntityExistsException.

When a system exception is thrown while the bean is executing in a the client's transaction context, the transaction is marked for rollback and a javax.ejb.TransactionRolledbackException is thrown to the client.

An application exception in the same situation does not cause the transaction to be rolled back and the same exception is thrown to the client. The client may proceed with the same transaction. The bean instance is not destroyed because the method has thrown an application exception and not a system exception (in which case, the instance would have been taken out of service).

If it is a checked exception, from which the bean cannot recover, the bean provider must ensure that the transaction is never committed and the instance is discarded. To achieve that he must throw a system exception. This can be done by wrapping the exception into an EJBException and rethrowing it. EJBException is a system exception and this will ensure that the transaction will never be committed and instance will be discarded.

If you throw the checked exception as it is (if it is listed in the throws clause), transaction will not be automatically set for a rollback and there is a possibility that the client my still try to commit it.On the other hand when the bean is not running in any transaction, the client gets an EJBException for a system exception and the same exception (i.e. the exception that was thrown in the bean) for an application exception. The client's transaction remains undisturbed.

Collection MapThe ElementCollection, OneToMany, and ManyToMany annotations are used to specify the map as an element collection or entity relationship as follows: when the map value is a basic type or embeddable class, the ElementCollection annotation is used; when the map value is an entity, the OneToMany or ManyToMany annotation is used.

@CollectionTable is used when @ElementCollection is used.

If you want to override the table name or column name for @OneToMany/ManyToMany/ManyToOne, you should use @JoinTable and @JoinColumn

Table strategiesThere are three strategies for implementing inheritance in entities: SINGLE_TABLE, JOINED, and TABLE_PER_CLASS (Support for the TABLE_PER_CLASS mapping strategy is optional in JPA 2.0 as per Section 11.1.20)In TABLE_PER_CLASS, there is a table for each concrete (non-abstract) class and each table contains all the fields for the superclasses as well.In this mapping strategy, each class is mapped to a separate table. All properties of the class, includinginherited properties, are mapped to columns of the table for the class.This strategy has the following drawbacks:

1. It provides poor support for polymorphic relationships. 2. It typically requires that SQL UNION queries (or a separate SQL query per subclass) be issuedfor queries that are intended to range over the class hierarch

In SINGLE_TABLE, there is only one table and it contains all the fields of all the classes in the hierarchy.In this strategy, all the classes in a hierarchy are mapped to a single table. The table has a column that serves as a “discriminator column”, that is, a column whose value identifies the specific subclass to which the instance that is represented by the row belongs.This mapping strategy provides good support for polymorphic relationships between entities and for queries that range deep over the class hierarchy.It has the drawback, however, that it requires that the columns that correspond to state specific to the subclasses be nullable.

@Inheritance(strategy=InheritanceType.JOINED)In JOINED, there is a table for each class. However, tables for subclasses contain only those fields that are specific to those classes. In the joined subclass strategy, the root of the class hierarchy is represented by a single table. Each subclass is represented by a separate table that contains those fields that are specific to the subclass (not inherited from its superclass), as well as the column(s) that represent its primary key. The primary key column(s) of the subclass table serves as a foreign key to the primary key of the superclass table.This strategy provides support for polymorphic relationships between entities.It has the drawback that it requires that one or more join operations be performed to instantiate instances of a subclass. In deep class hierarchies, this may lead to unacceptable performance. Queries that range over the class hierarchy likewise require joins.

Criteria Query

SELECT c.*FROM Customer c,  CustomerOrder coWHERE c.ID=co.CUSTOMER_IDand co.DISCOUNT = (select max(DISCOUNT) from CUSTOMERORDER)

1. SELECT c.* implies:

           CriteriaQuery<Customer> cq = cb.createQuery(Customer.class);           Root<Customer> customer = cq.from(Customer.class);           cq.select(customer).distinct(true);

2. FROM Customer c,  CustomerOrder co    WHERE c.ID=co.CUSTOMER_IDimplies:            Join<Customer, CustomerOrder> custOrder = customer.join("orders");    Note that customer.join("orders") is same as customer.join(Customer_.orders).           3. (select max(DISCOUNT) from CUSTOMERORDER)

implies:            Subquery<Double> sq = cq.subquery(Double.class);            Root<CustomerOrder> sqRoot = sq.from(CustomerOrder.class);            sq.select(cb.max(sqRoot.get(CustomerOrder_.discount)));

4. co.DISCOUNT =   implies:

           cq.where( cb.equal(custOrder.get(CustomerOrder_.discount),  sq) );

correlate() takes a Root or a Join object, not a Class object.Further, correlate is not warranted in this situation

Transaction Rollback ExceptionWhen a bean running in the client's transaction context encounters a system exception, the container marks the transaction for rollback and throws a javax.ejb.EJBTransactionRolledbackException to all 3.0 clients whether local or remote.However, if the business interface is a remote business interface that extends java.rmi.Remote, the javax.transaction.TransactionRolledbackException is thrown to the clients.

If the bean encounters an application exception, the container does not mark the transaction for roll back (if rollback=true is not specified for this exception) and throws the exact same application exception to the client. Note that the bean developer may call the setRollbackOnly() method in the bean, in which case the transaction will be set to rollback. However, if the developer does not call this method, then unlike in the case of system exception, the container does not mark the transaction for rollback.

Locks

@NamedQueries({ @NamedQuery(name="Employee.findByPrimaryKey", query="SELECT e FROM Employee e WHERE e.id = :id", lockMode=LockModeType.PESSIMISTIC_WRITE)})@Statelesspublic class EmployeeServiceBean implements EmployeeService { @PersistenceContext(unitName="EmployeeService") EntityManager em; public void processEmployee(int id) { Employee employee = em.createNamedQuery("Employee.findByPrimaryKey",Employee.class).setParameter("id", id).getSingleResult();

// do something with employee

}

The rows for element collection are not locked. They are locked only if lock.scope is set to PessimisticLockScope.EXTENDED in the query. For example: @NamedQuery( name="Employee.findByPrimaryKey", query="SELECT e FROM Employee e WHERE e.id = :id", lockMode=LockModeType.PESSIMISTIC_WRITE , hints={@QueryHint(name="javax.persistence.lock.scope",value="EXTENDED")} )

When an entity instance is locked using pessimistic locking, the persistence provider must lock the database row(s) that correspond to the non-collection-valued persistent state of that instance. If a joined inheritance strategy is used, or if the entity is otherwise mapped to a secondary table, this entails locking the row(s) for the entity instance in the additional table(s). Entity relationships for which the locked entity contains the foreign key will also be locked, but not the state of the referenced entities (unless those entities are explicitly locked). Element collections and relationships for which the entity does not contain the foreign key (such as relationships that are mapped to join tables or unidirectional one-to-many relationships for which the target entity contains the foreign key) will not be locked by default.

Element collections and relationships owned by the entity that are contained in join tables will be locked if the javax.persistence.lock.scope property is specified with a value of PessimisticLockScope.EXTENDED. The state of entities referenced by such relationships will not be locked (unless those entities are explicitly locked). This property may be passed as an argument to the methods of the EntityManager, Query, and TypedQuery interfaces that allow lock modes to be specified or used with the NamedQuery annotation.

Locking such a relationship or element collection generally locks only the rows in the join table or collection table for that relationship or collection. This means that phantoms will be possible.

A request for pessimistic lock causes the provider to acquire the database lock immediately. If the lock cannot be obtained, it with throw either LockTimeoutException or PessimisticLockException.

As per section 3.4.4.1 : If transaction T1 calls lock(entity, LockModeType.OPTIMISTIC_FORCE_INCREMENT) on a versioned object, it must force an update (increment) to the entity's version column. A forced version update may be performed immediately, or may be deferred until a flush or commit. If an entity is removed before a deferred version update was to have been applied, the forced version update is omitted.

In optimistic locking, no lock is actually obtained from the database.Optimistic locking is a technique that is used to insure that updates to the database data corresponding to the state of an entity are made only when no intervening transaction has updated that data for the entity state since the entity state was read. Optimistic locking is a technique that is used to insure that updates to the database data corresponding to the state of an entity are made only when no intervening transaction has updated that data for the entity state since the entity state was read.

Attribute Override

@AttributeOverrides( { @AttributeOverride( name="value.embeddableValue2", column=@Column(name="EV_2") ), @AttributeOverride( name="value.embeddableValue1", column=@Column(name="EV_1") ) } )

@ElementCollection //This is required and is used because embeddedData is a collection and not a basic property. @CollectionTable(name="PROJECT_METADATA") //This is optional and is used to change the table name. @AttributeOverrides( //This is optional and is used here because we are overriding multiple column names. { @AttributeOverride( name="key.keyfield1", //Observe that the name of the field in key class of the map is prefixed by "key."

//Notice that the name of the parameter is column and not joinColumns, which is used in AssociationOverride column=@Column(name="KF_1") //This is the new column name that we want to use in PROJECT_METADATA table ), @AttributeOverride( name="value.embeddableValue1", //Observe that the name of the field in value class of the map is prefixed by "value." column=@Column(name="EV_1") ) } ) Map<EmbeddableKey, EmbeddableValue> embeddedData;

NOTE: Since none of the key or value class is an Entity in this case, AttributeOverride is used. When the key or value is an Entity, AssociationOverride is used. The use of map keys that contain embeddables that reference entities is not permitted.

Embeddable

An embeddable class may contain a relationship to an entity or collection of entities. Since instances ofembeddable classes themselves have no persistent identity, the relationship from the referenced entity is to the entity that contains the embeddable instance(s) and not to the embeddable itself. An embeddable class that is used as an embedded id or as a map key must not contain such a relationship. An embeddable class (including an embeddable class within another embeddable class) may contain a collection of a basic type or other embeddable class.

CachingJPA second level (L2) caching shares entity state across various persistence contexts.JPA second level (L1) entity manager one persistence context.@Entitypublic class Account{ ... }

@Entity@Cacheable(true)public class CheckingAccount extends Account{ ... }

@Entitypublic class SavingsAccount extends Account{ ... }

Given that the persistence provide

r supports caching and shared-cache-mode is set to DISABLE_SELECTIVE, which of the entities will be removed from the cache when the following code is executed?

Cache c = ...//get a reference to Cache somehow c.evict(Account.class)

A value of NONE causes caching to be disabled for the persistence unit. Persistence providers must not cache if NONE is specified.

Note that when share-cached-mode is set to DISABLE_SELECTIVE, all the entities are cached except the ones for which @Cacheable(false) is specified. Cache.evict(class) applies to all the entities of the given class and its subclasses. Thus, in the case all instance of Account, CheckingAccount and SavingsAccount will be evicted.

when you call evict(class, PK), the API does not mention anything about a subclass. Thus, it can be interpreted only the instance of the given class with the given primary key will be evicted.

ENABLE_SELECTIVEIn this mode, none of the entities are cached by default. Only the ones with @Cacheable(true) are cached.

However, the Cacheable element applies to the given entity and its subclasses unless subsequently overridden by a subclass. So in this case, even though there is no Cacheable annotation of SavingsAccount, it will be cached as well if for Account it is set as true.Note that when share-cached-mode is set to ALL, all the entities are cached irrespective of their @Cacheable annotation.

A second-level cache is typically used to enhance performance. The persistence provider is not required to support use of a second-level cache. If the persistence provider does not support use of a second-level cache or a second-level cache is not installed, all caching related meta data is ignored no caching will occur. All the caching related annotations defined by JPA 2.0 specification are portable. They may be ignored if the persistence provider does not support caching but they will not break the application.

Entity States

A removed entity does not necessarily mean a detached entity. Until the transaction is committed, a removed entity is still a managed entity and a duplicate call to remove the same entity will not cause any exception but will only be ignored.

It is the managed entity that can be removed, so there is no cause for an exception in this case.

A detached entity means that it is not managed by the EntityManager. Thus, the EntityManager cannot remove it. A detached entity results from transaction commit if a transaction-scoped container-managed entity manager is used ; from transaction rollback; from detaching the entity from the persistence context; from clearing the persistence context; from closing an entity manager; or from serializing an entity or otherwise passing an entity by value—e.g., to a separate application tier, through a remote interface, etc.

Detached entity instances continue to live outside of the persistence context in which they were persisted or retrieved. Their state is no longer guaranteed to be synchronized with the database state.

Entity s does not exist in the database. It is possible that the database row corresponding to entity s is removed by some other process, while s is still being managed by the EntityManager. In this case, there won't be any exception.

Serializable is required only for transferring an object remotely. It is not required for database operations.

A detached entity instance is the one that has a corresponding row in the database table but is not currently managed by the current EntityManager.

A removed entity instance is the one that does not have a corresponding row in the database (or will not have a corresponding row when the transaction commits) but is currently managed by the EntityManager.If merge is called on it, IllegalArgumentexception is thrown. If not here, then in commit TransactionRolledBack Exception will be thrown.

A managed entity instance is an instance with a persistent identity that is currently associated with a persistence context.

BMT

A session bean using bean managed transactions can use multiple transactional resources. A transactional resource means a resource that "understands" transactions. For example, a database or a JMS message server. Any bean can use a transactional resource.Transaction management type of a session bean and type of entity manager (container managed or bean managed) are two different things. Any type of entity manager can be enlisted in a transaction started by a session bean with bean managed transactions.

If an instance of a message-driven bean with container-managed transaction demarcation attempts to invoke the getUserTransaction method of the EJBContext interface, the container must throw and log the java.lang.IllegalStateException. setRollbackOnly() and rollback() should be called only if a transaction is active. If there is no transaction active, they throw IllegalStateException. ut.getStatus() can be used to determine whether a transaction is active or not.

FYI, an enterprise bean with bean-managed transaction demarcation can obtain the status of a transaction by using the getStatus method of the javax.transaction.UserTransaction interface.

ut.begin();//bmt anotherBean.anotherMethod();//anotherBean is cmt bean, as persistence context is automatically propagated(it uses existing and does not start a new transaction)

Lifecycle Callback methods

If multiple entity listeners are defined, the order in which they are invoked is determined by the order in which they are specified in the EntityListeners annotation. The XML descriptor may be used as an alternative to specify the invocation order of entity listeners or to override the order specified in metadata annotations.

t is implementation-dependent as to whether PreUpdate and PostUpdate callbacks occur when an entity is persisted/subsequently modified in a single transaction or when an entity

is modified /subsequently removed within a single transaction. Portable applications should not rely on such behavior.

Lifecycle callback methods may throw runtime exceptions. Runtime exception thrown by a callback method that executes within a transaction causes that transaction to be rolled back. No further lifecycle callback methods will be invoked after a runtime exception is thrown.

The entity callback methods are invoked in the transaction and security contexts of the calling component at the time at which the callback method is invoked.

A lifecycle callback method may be defined on an entity class, a mapped superclass, or an entity listener class associated with an entity or mapped superclass. An entity listener class is a class whose methods are invoked in response to lifecycle events on an entity. Any number of entity listener classes may be defined for an entity class or mapped superclass.

The rule is that one class cannot have two or more methods for the same lifecycle event. So it can have multiple listener classes, each having a @PrePersist method.

Callback methods defined on an entity listener class have the following signature:void <METHOD>(Object)The Object argument is the entity instance for which the callback method is invoked.

Lock Modes

READ/ OPTIMISTIC : Prevents dirty read and non-repeatable readWRITE/OPTIMISTIC_FORCE_INCREMENT: Prevents dirty read and non-repeatable read as well as increments the version of the object.

(Note: Database locks are not obtained for any of the above modes. That's why they are called optimistic locking modes. Another important point to note is that OPTIMISTIC locking may not always be supported for non-versioned objects.)

An OptimisticLockException always causes the transaction to be marked for rollback. Refreshing objects or reloading objects in a new transaction context and then retrying the transaction is a potential response to an OptimisticLockException.

PESSIMISTIC_READ : Acquires the lock on the row in the database + Prevents dirty read and non-repeatable readPESSIMISTIC_WRITE : Acquires the lock on the row in the database + Prevents dirty read and non-repeatable read.

LockModeType.PESSIMISTIC_READ can be used to query data using repeatable-read semantics without the need to reread the data at the end of the transaction to obtain a lock, and without blocking other transactions reading the data. PESSIMISTIC_WRITE can be obtained on an entity instance to force serialization among transactions attempting to update the entity data. A lock with LockModeType.PESSIMISTIC_WRITE can be used when querying data and there is a high likelihood of deadlock or update failure among concurrent updating transactions.

PESSIMISTIC_FORCE_INCREMENT: Acquires the lock on the row in the database + Prevents dirty read and non-repeatable read + Increments the version of the object. Support for this lock mode for non-versioned objects is not required.

NONE

MappedBy

The side which has the foreign key is the owning side. MappedBy is specified in the inverse side (actual owner of relationship)2. For many-to-many bidirectional relationships either side may be the owning side.3.ManyToOne side , many is always the owning side, mappedBy is not required here4. OneToMany ,many is always owning side and must have mappedBy element.

@ManyToMany in Course class and @ManyToMany(mappedBy="proffs") in Professor class. This implies that Course class is the owning side of the relationship.

targetEntity is an optional attribute of @OneToOne, @ManyToOne, @OneToMany, and @ManyToMany annotations. It refers to the entity class that is the target of the association. It is not normally necessary to specify the target entity explicitly since it can usually be inferred from the type of the object being referenced. This is useful when you have entity class hierarchy.

The mappedBy attribute is specified on the non-owning side of the relationship and the foreignkey column is created on the owning side of the relationship. In this case, since there is no mappedBy attribute for either side, a foreignkey column will be created on both the tables. While it is desirable, the mappedBy attribute is optional for a one to one relationship.

Association OverrideSince the cubeLocation field is defined within Employee class, the AssociationOverride annotation has to be applied directly to the field definition. Had the cubeLocation field been defined in a MappedSuper class of Employee (say, in Person), you would have to specify AssociationOverride annotation on the class.

Designates a class whose mapping information is applied to the entities that inherit from it. A mapped superclass has no separate table defined for it.

@Entitypublic class Employee { @Embedded @AssociationOverride( name="mailBox", joinColumns=@JoinColumn(name="MBX_ID") ) private CubeLocation cubeLocation;

//rest of the code not shown}

//Association override is used here because the target you are trying to override is an entity

Association Override – name and joinColumnsAttribute Override- name and column

UDR BDR

one-to-one-FK,joinColumn one-to-one-FK,joinColumn

many-to-one-FK,joinColumn many-to-one-FK,joinColumn

one-to-many-Jointable one-to-many- FK,joinColumnmany-to-many-Jointable many-to-many- Jointable

Transaction Attributes

@TransactionAttribute(REQUIRED)Since mB()'s transaction attribute is Mandatory, it means that its caller must have a transaction context. In this case, its caller is mA(). Since mA()'s transaction attribute is NotSupported, it does not execute within a transaction context. Therefore, when it calls mB(), it will get a javax.ejb.EJBTransactionRequiredException. Since this exception extends from EJBException, it is a system exception. This means that mA() encounters a system exception and thus the bean A instance will be discarded.

Note that in general, any system exception thrown by an EJB would cause the respective instance to be discarded. However, that does not apply to singleton beans, because they must remain active until the shutdown of the application. Therefore, any system exception thrown on a business method or on a callback does not cause the instance to be destroyed.

Even though this does happen with REQUIRES_NEW, here, the xml overrides the transaction attributes of all the methods of the bean. So. in effect, the transaction attribute of this method becomes NOT_SUPPORTED. Thus, the existing transaction will be suspended for the execution of this method.

Bean A with transaction attributes of "RequiresNew" for all its methods. Bean B with transaction attributes of "Supports" for all its methods. A client having a transaction context calls a method mA() on bean A, which in turns calls a method mB() on Bean B.

The client's transaction is suspended when mA() executes because mA()'s transaction attribute is RequiresNew. Therefore, the client's transaction will not be rolled back automatically. Only mA()'s transaction will be rolled back by the container automatically. The client has an option to catch the EJBException and continue with its transaction.

A client of a session bean calls a method on the bean and the method throws a system exception.

If the bean method runs in the context of a transaction that the container started immediately before dispatching the business method, the client will get EJBException. If the bean method runs in the context of the caller’s transaction, the client will get javax.ejb.EJBTransactionRolledbackException.

1. methodA's transaction attribute is Required. Therefore, if the client has a transaction context, it will be used otherwise a new transaction will be created.

2. methodB's transaction attribute is NotSupported. So if there is a transaction context for the caller then it will be suspended and methodB will be executed without any transaction context.

3. methodC's transaction attribute is Supports. So if there is a transaction context for the caller then it will be used and if there is no transaction context with the caller then this method will be executed without any transaction context.

The onMessage method of a MDB can only have Required or NotSupported.

Overloaded methods need not have the same transaction attribute.

Visibility

Persistent fields of an entity class must be public, private, protected, or package visibility.

They must not be public.The persistent state of an entity is represented by instance variables, which may correspond to Java-Beans properties. An instance variable may be directly accessed only from within the methods of the entity by the entity instance itself. Instance variables must not be accessed by clients of the entity. The state of the entity is available to clients only through the entity’s accessor methods (getter/setter methods) or other business methods.

SubQueriesSubqueries are allowed in HAVING and WHERE clauses.

Types of persistent fieldJava primitive types; java.lang.String; other Java serializable types (including wrappers of the primitive types, java.math.BigInteger, java.math.BigDecimal, java.util.Date, java.util.Calendar, java.sql.Date, java.sql.Time, java.sql.Timestamp, byte[], Byte[], char[], Character[], and user-defined types that implement the Serializable interface); enums; entity types; collections of entity types; embeddable classes; collections of basic and embeddable types.Bulk Operations

1. A bulk operation applies to entities of the specified class and its subclasses. It does not cascade to related entities.

2. Bulk update maps directly to a database update operation, bypassing optimistic locking checks. Portable applications must manually update the value of the version column, if desired, and/or manually validate the value of the version column.

3. The persistence context is not synchronized with the result of the bulk update or delete.

4. Caution should be used when executing bulk update or delete operations because they may result in inconsistencies between the database and the entities in the active persistence context. In general, bulk update and delete operations should only be performed within a separate transaction or at the beginning of a transaction (before entities have been accessed whose state might be affected by such operations).

Join Table

@Entitypublic class Project {

@Id private Long id;

@OneToMany(mappedBy = "project") private Collection<Task> tasks;

}

@Entitypublic class Task {

@Id private Long id;

@ManyToOne @JoinTable( name = "Project_Tasks", inverseJoinColumns = @JoinColumn(name = "project_id"), joinColumns = @JoinColumn(name = "task_id") ) private Project project;

}

It is always specified on the owning side. Though, in a bidirectional many-to-many relationship, any side can be the owning side.//joincolumn alone specified, then it is in inverse sideThe default name is created using the name of the two entities. If the JoinColumns are not specified, the primary keys of both the entities are used.

Note that whenever a join table is used (i.e. in a many to many relationship), mapping overrides can be done only through joinTable parameter (as shown above) otherwise, joinColumns parameter is used in AssociationOverride.

@JoinColumn annotation is used when you have a simple primary/foreign key (i.e. only one column key) in a one to many or many to one relationships.

@JoinColumns annotation is used when you have a composite primary/foreign key (i.e. more than one column key) in a one to many or many to one relationships.

Primary Key Class

The primary key class must be Serializable and must contain valid implementations of equals and hashCode.The primary key class must be public and must have a public no-arg constructor.

Create a class containing the primary key fields that match the database columns and specify this class using @IdClass annotation on your entity class. Further, put the same fields in your entity class and annotate them with @Id.

1. A class containing primary key fields must be created. For example:

public class EmployeePK{ String empName; Integer code;

}

2. This class name must be specified in the @IdClass annotation in the entity class. For example:

@IdClass(com.acme.EmployeePK.class)@Entitypublic class Employee { @Id String empName; //The names must match the ones in PK class. @Id Integer code;...}

OR

Use embedded

For example:A class containing primary key fields must be created and annotated with @Embeddable. For example:@Embeddablepublic class EmployeePK{ //These field names should match the DB column names if you want to use default mappings. String empName; Integer code;}

@Entitypublic class Employee { @EmbeddedId EmployeePK empPK;...}

MetaModel

If class X extends another class S, where S is the most derived managed class (i.e., entity or mapped superclass) extended by X, then class X_ must extend class S_, where S_ is the metamodel class created for S.

@Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String topic;

For every persistent non-collection-valued attribute y declared by class X, where the type of y is Y, the metamodel class must contain a declaration as follows:

public static volatile SingularAttribute<X, Y> y;

if the collection type of z is java.util.Collection, thenpublic static volatile CollectionAttribute<X, Z> z;

• if the collection type of z is java.util.Set, thenpublic static volatile SetAttribute<X, Z> z;

• if the collection type of z is java.util.List, thenpublic static volatile ListAttribute<X, Z> z;

• if the collection type of z is java.util.Map, thenpublic static volatile MapAttribute<X, K, Z> z;where K is the type of the key of the map in class X

Transaction Scopes

When an EntityManager with an extended persistence context is used, the persist, remove, merge, and refresh operations can be called regardless of whether a transaction is active. The effects of these operations will be committed to the database when the extended persistence context is enlisted in a transaction and the transaction commits.

Persistence context is not propagated to remote tiers.

An EntityManager with an extended persistence context maintains its references to the entity objects after a transaction has committed.("Maintain references" means the persistence context has valid references to the actual entity objects.)

While a Java SE environment is only required to support an application managed entity manager (which is always extended scoped), a Java EE environment supports both - application and container managed. A Container managed entity manager can be extended scoped or transaction scoped.

The managed entities of the entity manager will become detached when the transaction is rolled back.In case of an extended scoped entity manager, the entities remain managed as long as the entity manager is not closed.

Remember that, by default, i.e. if you do not specify type attribute for @PersistenceContext, it is assumed to be transaction scoped. So type=TRANSACTION is not needed.

@PersistenceContext(type=PersistenceContextType.TRANSACTION)EntityManager em;

@PersistenceContext(type=PersistenceContextType.EXTENDED)EntityManager em;

Remember that if an entity manager is being injected by the container, it is container managed. An application managed entity manager is obtained in the bean code by using EntityManagerFactory.There is no way to specify scope for an application managed persistence context because it is always EXTENDED.

@PersistentUnit is used to inject EntityManagerFactory.

It starts when the first transaction is started under an entity manager.

False because The extended persistence context exists from the point at which the entity manager has been created using EntityManagerFactory.createEntityManager until the entity manager is closed by means of EntityManager.close.

An EntityManager instance is associated with a persistence context. A persistence context is a set of entity instances in which for any persistent entity identity there is a unique entity instance. Within the persistence context, the entity instances and their lifecycle are managed. This interface defines the methods that are used to interact with the persistence context. The EntityManager API is used to create and remove persistent entity instances, to find entities by their primary key, and to query over entities.

The set of entities that can be managed by a given EntityManager instance is defined by a persistence unit. A persistence unit defines the set of all classes that are related or grouped by the application, and which must be collocated in their mapping to a single database.

You need to understand the different flavors of persistence contexts (also referred to as Entity Manager sometimes) for the exam. The following details are enough for the purpose of the exam:

1 - Application Managed persistence context - It is always an extended persistence context. In other words, the scope of the persistence context of an application-managed entity manager is always extended. It is the responsibility of the application to manage the lifecycle of the persistence context. When a JTA application-managed entity manager is used, if the entity manager is created outside the scope of the current JTA transaction, it is the responsibility of the application to associate the entity manager with the transaction (if desired) by calling EntityManager.joinTransaction. If the entity manager is created outside the scope of a JTA transaction, it is not associated with the transaction unless EntityManager.joinTransaction is called.

2 - Container Managed persistence context - It can be transaction scoped or extended. In other words, the lifetime of a container-managed persistence context can either be scoped to a transaction (transaction-scoped persistence context), or have a lifetime scope that extends beyond that of a single transaction (extended persistence context). The enum PersistenceContextType is used to define the persistence context lifetime scope for container-managed entity managers. The persistence context lifetime scope is defined when the EntityManager instance is created (whether explicitly, or in conjunction with injection or JNDI lookup). By default, the lifetime of the persistence context of a container-managed entity manager corresponds to the scope of a transaction (i.e., it is of type PersistenceContextType.TRANSACTION).

A new transaction scoped persistence context begins when the container-managed entity manager is invoked in the scope of an active JTA transaction, and there is no current persistence context already associated with the JTA transaction. The persistence context is created and then associated with the JTA transaction. The persistence context ends when the associated JTA transaction commits or rolls back, and all entities that were managed by the EntityManager become detached.

A container-managed extended persistence context can only be initiated within the scope of a stateful session bean. It exists from the point at which the stateful session bean that declares a dependency on an entity manager of type PersistenceContextType.EXTENDED is created, and is said to be bound to the stateful session bean. The dependency on the extended persistence context is declared by means of the PersistenceContext annotation or persistence-context-ref deployment descriptor element. The persistence context is closed by the container when the @Remove method of

the stateful session bean completes (or the stateful session bean instance is otherwise destroyed).

An application managed extended persistence context exists from the point at which the entity manager has been created using EntityManagerFactory.createEntityManager until the entity manager is closed by means of EntityManager.close. An extended persistence context obtained from the application-managed entity manager is a stand-alone persistence context—it is not propagated with the transaction.

The container throws the TransactionRequiredException if a transaction-scoped persistence context is used, and the EntityManager persist, remove, merge, or refresh method is invoked when no transaction is active.

JTA is a means to control transactions of an Entity manager and so is EntityTransaction interface. There is either a JTA Entity Manager or a Resource-local Entity Manager.

You can create multiple EntityManagers for a PersistenceUnit in an application.Usually, you create a new EntityManager with each new transaction (i.e. a transaction scoped entity manager). However, a single EntityManager that spans multiple transactions is possible as well (i.e. extended scoped entity manager.)

//in java Boolean can not be converted to int, it cannot be represented as 0 or 1.

Left Join FetchObserve that the query uses LEFT JOIN FETCH. This forces the persistence provider to populate the orders collection with CustomerOrder objects associated with the customer.Therefore, when the code tries to access the order objects later, no database access is required.Remember that LEFT JOIN is same as LEFT OUTER JOIN.

Mapping

Which of the following techniques can be used to specify object-relational mapping information for entity classes?

XML Metadata- Mapping information can be specified in orm.xml file that can be supplied with class files.Annotations

Modelling

1. ACCOUNT 2. ACCOUNT_DETAILS3. ACCT_ACCTDET_JOINTABLE ACCT_ACCTDET_JOINTABLE contains two columns - ACCT_ID and ACT_DETAILS_ID. Both are foreign keys, referring to ACCOUNT and ACCOUNT_DETAILS tables respectively, and there are UNIQUE constraints defined for both of the columns of this table. Further, the primary key of this table is a composite key consisting of both the columns.

The problem statement clearly specifies that both the columns of ACCT_ACCTDET_JOINTABLE have unique constraints on them. This means neither of the values can be repeated in multiple rows. Therefore, you cannot have a many relationship on any side. This is a OneToOne relationship. It could be modeled as a bidirectional or unidirectional OneToOne.

Model ACCOUNT and ACCOUNT_DETAILS as two entities - Account and AccountDetails. Model ACCT_ACCTDET_JOINTABLE as a join table to establish a OneToOne bidirectional relationship between the Account and AccountDetails entities.

Only @OneToMany and @ElementCollection can be used while modeling using Map.@ManyToMany can be used as well if it is a many to many relationship.

OneToMany. Valid arguments are: targetEntity, cascade, fetch, mappedBy, and orphanRemove. @OneToMany(cascade = {CascadeType.ALL }, targetEntity=OrderLineItem.class, mappedBy="custOrder")

MapKey and MapKey Class

The MapKey annotation is not used when MapKeyClass is specified and vice versa.

MapKeyClass is used when the map field is not generic. (It is not wrong though to use it even when map field is generic.)@OneToMany(targetEntity=CreditCard.class) @MapKeyClass(String.class) private Map creditCards;

@OneToMany@MapKey(name="cardNumber") private Map<String, CreditCard> creditCards;

The table name and join column can be overridden using @CollectionTable and @JoinColumn, the column name for map key can be overridden using @MapKeyJoinColumn, and the column name for map value  can be overridden by using @Column

For example:    @ElementCollection    @CollectionTable(name="CUST_CARDS", joinColumns=@JoinColumn(name="MY_CUSTOMER_ID"))    @MapKeyJoinColumn(name="THE_CREDITCARD_ID")    @Column(name="BALANCE")    private Map<CreditCard, Double> creditCards;

If Java generic types are not used, the targetEntity element of the OneToMany or ManyToMany annotation must be used to specify the value type for the map. Without this information, the persistence provider cannot know the type of the values that are stored in the map. Similarly, we must specify the type of the map key as well. This is specified using either of the two ways:1. You can either use @MapKeyClass(CardType.class).2 Or use @MapKey(name="cardType"), since the persistence provider may easily deduce the key type by the attribute indicated explicitly. Note that it is given that cardType is an attribute in the target entity.

The MapKeyEnumerated annotation is used to specify the enum type for a map key whose basic type is an enumerated type. @MapKeyEnumerated(CardType.class)

Entity Manager Types

An entity manager whose transactions are controlled by the application through the EntityTransaction API is called a resource-local entity manager. On the other hand, an entity manager whose underlying transactions are controlled through JTA is termed a JTA entity manager. A container-managed entity manager must be a JTA entity manager. A resource local entity manager cannot be container managed. If an entity manager is injected by the container, that means, it is a container managed entity manager, which can only be a JTA entity manager. Only a resource local entity manager is permitted to use EntityTransaction interface. A JTA entity manager uses JTA to control the transactions.

Entity Manager Methods

ClearIt clears the persistence context, causing all managed entities to become detached. Changes made to entities that have not been flushed to the database will not be persisted. Throws: IllegalStateException - if this EntityManager has been closed

CloseIt closes an application-managed EntityManager. Throws: IllegalStateException - if the EntityManager is container-managed or has been already closed.

FlushIt synchronizes the persistence context to the underlying database. Throws: IllegalStateException - if this EntityManager has been closed. TransactionRequiredException - if there is no transaction PersistenceException - if the flush fails

lock(Object entity, LockModeType lockMode)It set the lock mode for an entity object contained in the persistence context.

Parameters:entity - lockMode - Throws: IllegalStateException - if this EntityManager has been closed. PersistenceException - if an unsupported lock call is made IllegalArgumentException - if the instance is not an entity or is a detached entity TransactionRequiredException - if there is no transaction

Findfind() will not help because if the entity instance is contained in the persistence context, it is returned from there. It doesn't fetch it from the database again.The cacheable annotation only affects the 2nd level cache. The first level cache (which is the EntityManager itself) may still contain stale data.

RefreshCall EntityManager.refresh with the same primary key as the object for which you want the latest data

Queries

Insert statements are not supported by JPQL. New rows can be created in the database using em.persist() operation.

How can a Java Persistence Query Language query be predefined so that it can be used repeatedly?Using @NamedQuery annotation

The use of named parameters is not defined for native queries. Only positional parameter binding forSQL queries may be used by portable applications.

The result of a native SQL query may consist of entities, scalar values, or a combination of the two. The entities returned by a query may be of different entity types.

select new Integer(avg(s.score)) from Student s Doing new Integer here is invalid. It should be new java.lang.Integer. Further, AVG function always returns Double so it cannot be passed as an argument to Integer.

select count(s.presentations) from Student s(Assume that presentations is a Collection field in Student) This is not a valid query because you cannot perform operations on a collection valued attribute without first declaring an identification variable for the collection. In this case, for example, you will need to do:select count(p) from Student s JOIN s.presentations p

The following aggregate functions can be used in the SELECT clause of a query: AVG, COUNT, MAX, MIN, SUM.

The Java type that is contained in the result of a query using an aggregate function is as follows:• COUNT returns Long.• MAX, MIN return the type of the state-field to which they are applied.• AVG returns Double.• SUM returns Long when applied to state-fields of integral types (other than BigInteger); Double when applied to state-fields of floating point types; BigInteger when applied to state-fields of type BigInteger; and BigDecimal when applied to state-fields of type BigDecimal.

If SUM, AVG, MAX, or MIN is used, and there are no values to which the aggregate function can be applied, the result of the aggregate function is NULL.

If COUNT is used, and there are no values to which COUNT can be applied, the result of the aggregate function is 0.

Quantifiers ANY,ALL,SOME used only in sub queries. EXISTS is also used in sub queries.

Database isolation Level

1. Client 1 retrieves an Account entity. The Account entity's status property has a value of "outstanding".2. Client 2 performs a bulk update on all Accounts changing their status property to "normal".

3. Client 1 updates the account balance of the Account entity that it was accessing and merges the instance

Remember that bulk operations do not respect the Version attribute. They just go and update the database rows irrespective of version values. Further, changes made by bulk updates are not reflected in the entities currently existing in the persistence context.Thus, in this case, when client 2 updates the status property of Accounts, the value of version attribute is not incremented for any of the Accounts. The Account entity that Client 1 is using is not updated with the new status either. So when Client 1 updates the Account with new balance, its old value of status is also written back to the database.Database isolation level is READ_COMMITTED. In this case, as soon as client 1 reads an Account entity within a transaction, the database would lock the row. Now, when the Client 2 tries to fire an update on that table in another transaction, the database will hold the bulk update until the read lock is released. Thus, the database will be in consistent state and the issue described in this question will not occur.

Cascade Values

ALL DETACH MERGE PERSIST REFRESH REMOVE // The relationship modeling annotation constrains the use of the cascade=REMOVE specification. The cascade=REMOVE specification should only be applied to associations that are specified as OneToOne or OneToMany. Applications that apply cascade=REMOVE to other associations are not portable.@OneToMany(orphanRemoval=true) If orphanRemoval is true and the remove operation is applied to the source entity, the remove operation will be cascaded to the relationship target in as per the cascade type.If orphanRemoval is true and an entity that is the target of the relationship is removed from the relationship (either by removal from the collection or by setting the relationship to null), the remove operation will be applied to the entity being orphaned.

2. When there is no cascade parameter and orphanRemoval=trueThe associated address entity will be removed in both the situations above. When orphanRemoval=true is specified, casade=REMOVE is not required.

<cascade-persist/> The cascade-persist subelement applies to all relationships in the persistence unit.Specifying this subelement adds the cascade persist option to all relationships in addition to any settings specified in annotations or XML.

Cascade should be specified on the owning side

Entity Class

The entity class must be annotated with the Entity annotation OR denoted in the XML descriptor as an entity.The entity class must have a no-arg constructor. The entity class may have other constructors as well.The no-arg constructor must be public or protected.An enum or interface should not be designated as an entity.The entity class must not be final. No methods or persistent instance variables of the entity class can be final.

If an entity instance is to be passed by value as a detached object (for example, through a remote interface), the entity class must implement the Serializable interface.

Entity ListenersThe entity listener class must have a public no-arg constructor.

Entity listeners are stateless. The lifecycle of an entity listener is unspecified.

The following rules apply to lifecycle callbacks:

• Lifecycle callback methods may throw unchecked/runtime exceptions. A runtime exception thrown by a callback method that executes within a transaction causes that transaction to be marked for rollback.• Lifecycle callbacks can invoke JNDI, JDBC, JMS, and enterprise beans.• In general, the lifecycle method of a portable application should not invoke EntityManager or Query operations, access other entity instances, or modify relationships within the same persistence context. A lifecycle callback method may modify the non-relationship state of the entity on which it is invoked.

XML Descriptors<persistence> <persistence-unit name="forumPU"> ... <class>Post</class> <class>PostMeta</class> ... </persistence-unit></persistence><exclude-unlisted-classes/> element is absent from from persistence.xml - This implies that all the classes need not be listed in the persistence.xml using <class> elements. Classes can be implicity denoted as managed by putting them in appropriate locations.

EJB3.1Entities don't manage transactions anyway. Session beans or Message Driven Beans work with transactions. Since isolation levels are implemented differently in various databases, the EJB specification has not standardized its usage. It does not allow nested transactions.

Only a stateful session bean is permitted to continue a transaction beyond a method. A stateless session bean must either committ or rollback a transaction before it returns.

Query and Flush Modes Thus, to ensure that the results of past queries in the persistence context are visible to the query  1. either the flush mode on EntityManager should be set to AUTO and flush mode on Query should not be set.  2. or, the flush mode on Query should be set to AUTO.

If FlushModeType.COMMIT is set, the effect of updates made to entities in the persistence context upon queries is unspecified. If FlushModeType.COMMIT is specified, flushing will occur at transaction commit;"However, it further adds, "the persistence provider is permitted, but not required, to perform to flush at other times."

Version

1.It is used to ensure integrity when performing the merge operation and for optimistic concurrency control.2.Application code should never modify its value. The container modifies it as required. However, in case of bulk updates, a developer may intentionally want to modify the @Version column in the database, so bulk changes will be recognized by EntityManager. Even so, the @Version attribute should not be modified.3.Only a single Version property or field should be used per class; applications that use more than oneVersion property or field will not be portable. The Version property should be mapped to the primary table for the entity class;4. instance variables must be private, protected, or package visibility. This applies to fields annotated with @Version as well. It cannot be static or final.

User Transaction Methods-used only by BMTInterface javax.transaction.UserTransaction

void begin() Create a new transaction and associate it with the current thread.

void commit() Complete the transaction associated with the current thread.

void rollback() Roll back the transaction associated with the current thread.

void setRollbackOnly() Modify the transaction associated with the current thread such that the only possible outcome of the transaction is to roll back the transaction.

int getStatus() Obtain the status of the transaction associated with the current thread.

void setTransactionTimeout(int seconds) Modify the value of the timeout value that is associated with the transactions started by the current thread with the begin method.

Entity Transaction API

The EntityManager.getTransaction() method returns the EntityTransaction interface.

void begin() Create a new transaction and associate it with the current thread.

void commit() Complete the transaction associated with the current thread.

void rollback() Roll back the transaction associated with the current thread.

void setRollbackOnly() Modify the transaction associated with the current thread such that the only possible outcome of the transaction is to roll back the transaction.

getRollbackOnly()           Determine whether the current resource transaction has been marked for rollback.

isActive()           Indicate whether a resource transaction is in progress.

Primary Key

Multiple entities can have the same primary key class. You cannot change the primary key of an entity because it identifies the bean in the database. Changing the primary key means you are creating or retrieving a different bean. As per the specification, the application must not change the value of the primary key. The behavior is undefined if this occurs.Every entity must have a primary key.

The primary key must be defined on the entity that is the root of the entity hierarchy or on a mapped superclass of the entity hierarchy. The primary key must be defined exactly once in an entity hierarchy.A simple (i.e., non-composite) primary key must correspond to a single persistent field or property of the entity class. The Id annotation is used to denote a simple primary key.

A composite primary key must correspond to either a single persistent field or property or to a set of such fields or properties as described below. A primary key class must be defined to represent a composite primary key. Composite primary keys typically arise when mapping from legacy databases when the database key is comprised of several columns. The EmbeddedId and IdClass annotations are used to denote composite primary keys.

The primary key (or field or property of a composite primary key) should be one of the following types:

any Java primitive type; any primitive wrapper type; java.lang.String; java.util.Date;java.sql.Date.

In general, however, approximate numeric types (e.g., floating point types) should never be used in primary keys. Entities whose primary keys use types other than these will not be portable. If generated primary keys are used, only integral types will be portable. If java.util.Date is used as a primary key field or property, the temporal type should be specified as DATE.

Query Functions

String Functions:

CONCAT( String, String) returns a StringSUBSTRING( String, start, length) returns a StringLOCATE( String, String [, start]) returns an intLENGTH( String) returns an intLOWERUPPERTRIM

Arithmetic Functions:

ABS( number) returns a number (int, float, or double)

SQRT( double) returns a doubleMODSIZEINDEX

Date Functions:CURRENT_DATE ,CURRENT_TIME ,CURRENT_TIMESTAMP

Packaging

mybusiness.ear forum.war WEB-INF/classes ForumServlet.class Forum.class Post.class WEB-INF/classes/META-INF persistence.xml <--- Contents of this file are as follows - <persistence> <persistence-unit name="forumPU"> ... </persistence> forumejb.jar ForumSession.class META-INF persistence.xml <--- Contents of this file are as follows - <persistence> <persistence-unit name="forumPU"> ... </persistence>

The restriction is that only one persistence unit of any given name must be defined within a single EJB-JAR file, within a single WAR file, within a single application client jar, or within an EAR. Here, the same name for two PUs is used but not in the same scope. One is in war file and another is in a separate jar file. So this is valid.A persistence unit that is defined at the level of the EAR is generally visible to all components in the application. However, if a persistence unit of the same name is defined by an EJB-JAR, WAR, or application jar file within the EAR, the persistence unit of that name defined at EAR level will not be visible to the components defined by that EJB-JAR, WAR, or application jar file unless the persistence unit reference uses the persistence unit name # syntax to specify a path name to disambiguate the reference. When the # syntax is used, the path name is relative to the referencing application component jar file. For example, the syntax ../lib/persistenceUnitRoot.jar#myPersistenceUnit refers to a persistence unit whose name, as specified in the name element of the persistence.xml file, is myPersistenceUnit and for which the relative path name of the root of the persistence unit is ../lib/persistenceUnitRoot.jar. The # syntax may be used with both the unitName annotation element or persistence-unit-name deployment descriptor element to reference a persistence unit defined at EAR level.

How can you include an entity class in the set of managed classes of a Persistent Unit for a Java EE environment?

By explicitly naming it in persistence.xml and ensuring that the class is in the classpath.<persistence-unit name="myPU" >

... <class>salesapp.Address</class> ... </persistence-unit></persistence>

By putting the class file (in appropriate package structure) under the root of persistence unit.So, for example, all entity classes under WEB-INF/classes of a war file will automatically be managed by the PU (The WEB-INF/classes/META-INF/persistence.xml must still be present though).

A object/relational mapping XML file named orm.xml may be specified in the META-INF directory in the root of the persistence unit or in the META-INF directory of any jar file referenced by the persistence.xml. Classes referenced in this file are implicitly included in the set of managed classes.

persistence.xml file contains overall properties of an application. It may contain a list of entity classes but does not contain properties for individual entity classes. It may contain references to xml files (which can be named anything) in <mapping-file> element and such xml files contain properties for individual entity classes. It may also contain references to jar files containing entity classes and such jar files may have META-INF/orm.xml, which contain properties for individual entity classes.

The following classes must be implicitly or explicitly denoted as managed persistence classes to be included within a persistence unit: entity classes; embeddable classes; mapped superclasses.

The set of managed persistence classes that are managed by a persistence unit is defined by using one or more of the following:• Annotated managed persistence classes contained in the root of the persistence unit (unless the exclude-unlisted-classes element is specified)• One or more object/relational mapping XML files• One or more jar files that will be searched for classes• An explicit list of classes

EnumTypepublic enum EnumType { ORDINAL, //This is the default. It implies that integer index of the enum value is stored in the database. STRING}

Servletpublic class MyServlet extends HttpServlet{ @PersistenceContext(unitName="myPU") private EntityManager entityManager;

public void doGet(HttpServletRequest req, HttpServletResponse res) { //use entityManager here. }}

This is not a recommended approach becase a servlet is by default multi threaded. That means, multiple threads processing multiple requests will be able to access the same entityManager. So if one request rolls back a transaction, other requests will be affected as well. Thus, the goal is to get the same entitymnager only for the same transaction. For different request you should get a different entity manager.

Also, remember that methods of EntityManager are NOT thread safe but methods of EntityManagerFactory are.

Id Generators

@Entity public class Employee { ... @TableGenerator( name="empGen", table="ID_GEN", pkColumnName="GEN_KEY", valueColumnName="GEN_VALUE", pkColumnValue="EMP_ID", allocationSize=1)@Id@GeneratedValue(strategy=TABLE, generator="empGen")public int id;...}

Example 2 -

@Entity public class Employee { ... @SequenceGenerator( name="seqGen", allocationSize=10)@Id@GeneratedValue(strategy=SEQUENCE, generator="seqGen")public int id;...}

Access ModesThere is no default. It depends on whether a field or a property (i.e. a getter method for id) is annotated with @Id. Remember that @Id must be present for every entity class (or its superclass), if the bean is using only annotations. Access mode may also be specified using "access" element of XML descriptor. If a property based access is chosen for an entity class, the names of the fields do not have to correspond to the method names. Entity subclasses may override the property accessor methods. However, portable applications must not override the object/relational mapping metadata that applies to the persistent fields or properties of entity superclasses.

Annotations

@Basic(fetch=LAZY) private Double balance; Apply @Enumerated(EnumType.STRING) on cardType attribute in CreditCard entity.


Recommended