Wanderlei C. A. Souza

Greenhorn
+ Follow
since Dec 13, 2006
Merit badge: grant badges
For More
Cows and Likes
Cows
Total received
0
In last 30 days
0
Total given
0
Likes
Total received
0
Received in last 30 days
0
Total given
0
Given in last 30 days
0
Forums and Threads
Scavenger Hunt
expand Ranch Hand Scavenger Hunt
expand Greenhorn Scavenger Hunt

Recent posts by Wanderlei C. A. Souza

I recommend some XML framework, it will make the things easier.

Try Jakarta Betwixt (http://jakarta.apache.org/commons/betwixt/)
or Castor (http://www.castor.org/xml-framework.html)

=)
17 years ago
continuance...

-JPA requires only two pieces of metadata: @javax.persistence.Entity and @javax.persistence.Id.
-by default, all properties are persistent.
-Instead of O/R annotations you can, alternatively, use the orm.xml (WEB-INF/) to describe the mapping.

<entity-mappings>
<entity class="mypackage.MyClass" access="PROPERTY">
<attributes>
<id name="id">
</attributes>
</entity>
</entity-mappings>


===elementary schema mappings===
@Entity
@Table(name="TABLE_NAME")
@Id
@Column(name="COL_NAME", nullable=false, columnDefinition="integer")
@Column(name="COL_NAME", length=20)

-Every entity bean must have a PK (and it must be unique, dah).
-You can generate the PK manually or using the @javax.persistence.GeneratedValue annotation.

Is possible use tables to get the generated IDs.
@TableGenerator(name="CUST_GENERATOR" ...)
@Id
@GeneratedValue(strategy=GenerationType.TABLE, generator="CUST_GENERATOR")

Using Oracle Sequence Generators...
@SequenceGenerator(name="CUSTOMER_SEQUENCE", sequenceName="CUST_SEQ")
@Id
@GeneratedValue(strategy=GenerationType.SEQUENCE, generator="CUSTOMER_SEQUENCE")


===Composite Keys===
There are two ways to map composite keys: @javax.persistence.IdClass and @javax.persistence.EmbeddedId.
NOTE: PK autogeneration is not supported for composite keys.

-The first way to define a composite PK is using @IdClass
You need to create a PK composite class and this class must:
.be serializable
.have a public no-arg constructor
.implements equals() and hashCode()

@Entity
@IdClass(MyPKComposite.class) //a serializable, +equals() +hashCode, no-public constructor, class.
public class SomeClass implements java.io.serializable {
//NOTE The SomeClass must have the same exact properties as the MyPKComposite class
private String firstName;
private String lastName;
private long ssn;

private String getFirstName() { return... }

@Id
private String getLastName() { return... }
@Id
private long getSsn() { return... }

//... and setters.
}

Another whay to define a PK composite is using the @EmbeddedId annotation:
-On this scenario, you need to create a PK composite class with the @Embeddable annotation
-You also can use @Embedded to embed nonentity Java Objetis (do not have any identity) within your entity bean.

@Embeddable
public class MyPKComposite implements java.io.serializable {
//... column mappings
@Column(name="REAL_COLUMN_NAME") //if you dont like this, you can use @AttributeOverrides instead.
public String getLastName() { //... }
}

@Entity
public class SomeClass implements java.io.serializable {
private String firstName;
private MyPKComposite pk;

@EmbeddedId
public MyPKComposite getPk() { //... }

// --- OR (dependes if @Column was not used in PK definition class) ----

@@EmbeddedId
@AttributeOverrides({
@AttributeOverride(name="lastName", column=@Column(name="REAL_COLUMN_NAME")),
//... all overrides
})
public MyPKComposite getPk() { //... }

//...other getters and setters.
}


===== property mappings =====

-@Transient: By default, all properties are persistent - use @Transient to avoid this behaviour.
-@Basic(fetch=FetchType.LAZY, optional=false) (usually you would never need this)
.Is just a hint! the provider could use FetchType.EAGER even if you choose LAZY.
.when optional is true, the property is treated as nullable.
-@Temporal provides aditional information about date/time properties in DB.
@Temporal(TemporalType.DATE)
@Temporal(TemporalType.TIME)
@Temporal(TemporalType.TIMESTAMP)
-@Lob to persist in a Blob or Clob DB field.
@Lob
@Basic(fetch=FetchType.Lazy, optional=true)
public JPEG getPicture() { //... };
-@Enumerated maps Java enum types to the DB.
@Enumerated(EnumType.STRING) //String enum value instead of ORDINAL (default) number.
publc MyEnum getMyEnum() { //... }
-@SecondaryTable to deal with one logical entry stored in two (OR MORE) different tables.
eg. A CUSTOMER_TABLE and an ADDRESS_TABLE
@Entity
@Table(name="CUSTOMER_TABLE", pkJoinColumns={@PrimaryKeyJoinColumn(name="ADDRESS_ID")})
public class Customer implements java.io.serializable {
//...
@Column(name="STREET", table="ADDRESS_TABLE")
//...
Amita,
In JEE/EJB3 enviroments (like JBoss) is better you use directly the @PersistenceContext annotation to obtain the PersistenceContext.

In JSE environment, you don't have the JEE facilities. In this situation, you need to create an EntityManagerFactory (using javax.persistence.Persistence) to get the PersistenceContext.

PersistenceContext is what really matters.

EntityManager manage the PersistenceContext and the PersistenceContext is in association with PersistenceUnit (described in persistence.xml file).

Thats it =)
People,
Im studying for the new EJB3 certification. I would like the share some study notes with you guys. This is my BASIC notes about INTRODUCTION to Java Persistence API (I'll increase the complexity in the future). Please, improve and give suggestions =]. Im based on the Enterprise Java Beans 3.0 5th edition book (O'Reilly). Sorry for any English inconvenience, my native language is Portuguese =))).

----
-***ENTITY MANAGER*** (javax.persistence.EntityManager) is the central service for all persistence actions.
-ENTITIES are pojos. They don't become persistent until interacts with the EntityManager to make them persistent.
-EntityManager provides...
--O/R mapping.
--API to create queries, finding, synchronizing and inserting objects.
--Caching.
--Interaction with JTA.
-EntityManager isn't limited to JEE environment (can use it in JSE).
-States: Entity Managed (attached to an Entity Manager) vs. Unmanaged (detached from an Entity Manager).

-***PERSISTENCE CONTEXT*** is a set of managed entity object instances.
-The Persistence Context are managed by an Entity Manager.
-When a persistence context is close, all the managed entities become detached and are no longer
managed (any state change will not be synchronized with the database).
-There are Two types of Persistence Context: Transaction-Scoped and Extended Persistence Context.
(1) In the Transaction-Scoped type, Persistence Context live as long a transaction and be closed when
a transaction completes (the transaction Persistence Context will be destroyed and all managed
entity become detached).
-Only app server managed persistence contexts can be transaction-scoped (only EntityManager instances
injected with the @PersistenceContext annotation or XML equivalent may be transaction-scoped).
(2) Extended Persistence Context live longer than a transaction. The entity instances remain managed
after a transaction is completed.

-***PERSISTENCE UNIT*** An EntityManager maps a fixed set of classes to a particular DB. This set of classes
is called a Persistence Unit.
-One or more Persistence Units are defined in a persistence.xml file (in the META-INF directory).
-The set of classes in the Persistence Unit can be specified or the provider can scan the jar automatically
(default) to determine the set of classes to deploy as entities.
-When automatic mode is used, the provider look for the @javax.persistence.Entity annotation.
-IMPORTANT NOTE: Each persistence unit is tied to one and only one data source.
-persistence.xml exemple
<persistence>
<persistence-unit name="titan"> <!-- used by injection annotations -->
<jta-data-source>java:/OracleDS</jta-data-source>
<properties>
<property name="org.hibernate.hbm2dll">update</property>
</properties>
</persistence-unit>
</persistence>

-Obtaining an EntityManager in JAVA SE:
-In Java SE EntityManagers are created by javax.persistence.EntityManagerFactory (Using the factory is possible
but isn't a requirement in Java EE).
-when finish to use the EntityManagerFactory you should close() (unless it is injected, when this occurs automatically)
-javax.persistence.Persistence class is responsible for creating an EntityManagerFactory.
EntityManagerFactory factory = Persistence.createEntityManagerFactory("persistenceUnitName");
...
factory.close(); // <-- you should do that when using Java SE.

-Obtaining an EntityManager in JAVA EE:
-@javax.persistence.PersistenceUnit annotation is used in Java EE environment.
@PersistenceUnit(unitName="persistenceUnitName") private EntityManagerFactory factory;
-if you call close() on an injected EntityManagerFactory, an IllegalStateException is thrown.

-Obtaining a Persistence Context
-A Persistence Context can be created calling the EntityManagerFactory.createEntityManager() method.
-createEntityManager() return an extended persistence context.
-If EntityManagerFactory is JTA-enablea you must call the EntityManager.joinTransaction() method*.
*If you are using EJB container managed persistence contexts, then you do not need to perform this.
-An EntityManager can be injected directly into an EJB using the @javax.persistence.PersistenceContext annotation**.
@PersistenceContext(unitName="persistenceUnitName",type=PersistenceContextType.EXTENDED)
private EntityManager entityManager;***
** the Transaction-Scoped Type is the default value.
*** extended type is only allowed in Stateful Session Beans. When the stateful bean is removed, the persistence
context is closed.
-It is strongly suggested that you use the @PersistenceContext or the XML equivalent instead of EntityManagerFactory
when you using Java Persistence with EJBs.

===API===
entityManager.persist(entityobject);
-> Queue for insertion and the object becomes managed. Throw an IllegalArgumentException if entityobject is not an entity type.
entityManager.flush();
-> Force manually insertion.
entityManager.find(entityClass, primaryKey);
-> Find by PK. If not found, null is returned.
Customer c = entityManager.find(Customer.class,2);
entityManager.getReference(entityClass, primaryKey);
-> Get Reference by PK. If not found, throw an EntityNotFoundException.
entityManager.createQuery();
Query query = entityManager.createQuery("from Customer c where id=2");
Custumer cust = (Custumer)query.getSingleResult();
note: All query, find or getReference are managed by the Persistence Context, and they return the same entity instance.
entityManager.merge(entityobject);
-> Attach the entity object to the Persistence Context.
Cabin entityCopy = entityManager.merge(entityObjectParam);*
*entityCopy is managed by the entity manager, entityObjectParam still detached.
entityManager.remove(entityObject); Throw TransactionRequiredException if this method is invoked on a transaction-scoped persistence context.
-> Queue for delete. Throw TransactionRequiredException if this method is invoked on a transaction-scoped persistence context.
entityManager.refresh(entityObject);
-> Refreshes the state of the entity from database, overwriting any changes made to that object.
Throw TransactionRequiredException if this method is invoked on a transaction-scoped persistence context.
Throw EntityNotFoundException if another thread removed the object.
entityManager.contains(entityObject);
-> Return true if the entityObject instance is currently being managed by the persistence context.
entityManager.clear()
-> Detach all managed entity instances from a persistence context. Any changes you have made will be lost.
-> Use flush() before clear() to avoid data lost.

entityManager.setFlushMode(FlushModeType.AUTO | FlushModeType.COMMIT);
.When you call persist(), merge() or remove(), these changes ARE NOT synchronized with de database until the EntityManager decide to flush.
.You can force the synch using flush(). By default flush happens before a correlated query is executed or transaction commit time (AUTO mode).
.When COMMIT mode is on, the flush ocurrs only when the transaction commits.

Resource Local Transactions.
-EntityManagers persistence context is usually JTA default in a Java EE environment.
EntityTransaction.begin(); .commit(); .rollback(); isActive();
-In a non-Java EE environment, JTA is not avaliable, so JPA provide the EntityTransaction interface to local control of transactions.
-You cannot use EntityTransactions if the transaction type of your persistence unit is JTA.
People,
Im studying for the new EJB3 certification. I would like the share some study notes with you guys. This is my BASIC notes about INTRODUCTION to Java Persistence API (I'll increase the complexity in the future). Please, improve and give suggestions =]. Im based on the Enterprise Java Beans 3.0 5th edition book (O'Reilly). Sorry for any English inconvenience, my native language is Portuguese =))).

----
-***ENTITY MANAGER*** (javax.persistence.EntityManager) is the central service for all persistence actions.
-ENTITIES are pojos. They don't become persistent until interacts with the EntityManager to make them persistent.
-EntityManager provides...
--O/R mapping.
--API to create queries, finding, synchronizing and inserting objects.
--Caching.
--Interaction with JTA.
-EntityManager isn't limited to JEE environment (can use it in JSE).
-States: Entity Managed (attached to an Entity Manager) vs. Unmanaged (detached from an Entity Manager).

-***PERSISTENCE CONTEXT*** is a set of managed entity object instances.
-The Persistence Context are managed by an Entity Manager.
-When a persistence context is close, all the managed entities become detached and are no longer
managed (any state change will not be synchronized with the database).
-There are Two types of Persistence Context: Transaction-Scoped and Extended Persistence Context.
(1) In the Transaction-Scoped type, Persistence Context live as long a transaction and be closed when
a transaction completes (the transaction Persistence Context will be destroyed and all managed
entity become detached).
-Only app server managed persistence contexts can be transaction-scoped (only EntityManager instances
injected with the @PersistenceContext annotation or XML equivalent may be transaction-scoped).
(2) Extended Persistence Context live longer than a transaction. The entity instances remain managed
after a transaction is completed.

-***PERSISTENCE UNIT*** An EntityManager maps a fixed set of classes to a particular DB. This set of classes
is called a Persistence Unit.
-One or more Persistence Units are defined in a persistence.xml file (in the META-INF directory).
-The set of classes in the Persistence Unit can be specified or the provider can scan the jar automatically
(default) to determine the set of classes to deploy as entities.
-When automatic mode is used, the provider look for the @javax.persistence.Entity annotation.
-IMPORTANT NOTE: Each persistence unit is tied to one and only one data source.
-persistence.xml exemple
<persistence>
<persistence-unit name="titan"> <!-- used by injection annotations -->
<jta-data-source>java:/OracleDS</jta-data-source>
<properties>
<property name="org.hibernate.hbm2dll">update</property>
</properties>
</persistence-unit>
</persistence>

-Obtaining an EntityManager in JAVA SE:
-In Java SE EntityManagers are created by javax.persistence.EntityManagerFactory (Using the factory is possible
but isn't a requirement in Java EE).
-when finish to use the EntityManagerFactory you should close() (unless it is injected, when this occurs automatically)
-javax.persistence.Persistence class is responsible for creating an EntityManagerFactory.
EntityManagerFactory factory = Persistence.createEntityManagerFactory("persistenceUnitName");
...
factory.close(); // <-- you should do that when using Java SE.

-Obtaining an EntityManager in JAVA EE:
-@javax.persistence.PersistenceUnit annotation is used in Java EE environment.
@PersistenceUnit(unitName="persistenceUnitName") private EntityManagerFactory factory;
-if you call close() on an injected EntityManagerFactory, an IllegalStateException is thrown.

-Obtaining a Persistence Context
-A Persistence Context can be created calling the EntityManagerFactory.createEntityManager() method.
-createEntityManager() return an extended persistence context.
-If EntityManagerFactory is JTA-enablea you must call the EntityManager.joinTransaction() method*.
*If you are using EJB container managed persistence contexts, then you do not need to perform this.
-An EntityManager can be injected directly into an EJB using the @javax.persistence.PersistenceContext annotation**.
@PersistenceContext(unitName="persistenceUnitName",type=PersistenceContextType.EXTENDED)
private EntityManager entityManager;***
** the Transaction-Scoped Type is the default value.
*** extended type is only allowed in Stateful Session Beans. When the stateful bean is removed, the persistence
context is closed.
-It is strongly suggested that you use the @PersistenceContext or the XML equivalent instead of EntityManagerFactory
when you using Java Persistence with EJBs.

===API===
entityManager.persist(entityobject);
-> Queue for insertion and the object becomes managed. Throw an IllegalArgumentException if entityobject is not an entity type.
entityManager.flush();
-> Force manually insertion.
entityManager.find(entityClass, primaryKey);
-> Find by PK. If not found, null is returned.
Customer c = entityManager.find(Customer.class,2);
entityManager.getReference(entityClass, primaryKey);
-> Get Reference by PK. If not found, throw an EntityNotFoundException.
entityManager.createQuery();
Query query = entityManager.createQuery("from Customer c where id=2");
Custumer cust = (Custumer)query.getSingleResult();
note: All query, find or getReference are managed by the Persistence Context, and they return the same entity instance.
entityManager.merge(entityobject);
-> Attach the entity object to the Persistence Context.
Cabin entityCopy = entityManager.merge(entityObjectParam);*
*entityCopy is managed by the entity manager, entityObjectParam still detached.
entityManager.remove(entityObject); Throw TransactionRequiredException if this method is invoked on a transaction-scoped persistence context.
-> Queue for delete. Throw TransactionRequiredException if this method is invoked on a transaction-scoped persistence context.
entityManager.refresh(entityObject);
-> Refreshes the state of the entity from database, overwriting any changes made to that object.
Throw TransactionRequiredException if this method is invoked on a transaction-scoped persistence context.
Throw EntityNotFoundException if another thread removed the object.
entityManager.contains(entityObject);
-> Return true if the entityObject instance is currently being managed by the persistence context.
entityManager.clear()
-> Detach all managed entity instances from a persistence context. Any changes you have made will be lost.
-> Use flush() before clear() to avoid data lost.

entityManager.setFlushMode(FlushModeType.AUTO | FlushModeType.COMMIT);
.When you call persist(), merge() or remove(), these changes ARE NOT synchronized with de database until the EntityManager decide to flush.
.You can force the synch using flush(). By default flush happens before a correlated query is executed or transaction commit time (AUTO mode).
.When COMMIT mode is on, the flush ocurrs only when the transaction commits.

Resource Local Transactions.
-EntityManagers persistence context is usually JTA default in a Java EE environment.
EntityTransaction.begin(); .commit(); .rollback(); isActive();
-In a non-Java EE environment, JTA is not avaliable, so JPA provide the EntityTransaction interface to local control of transactions.
-You cannot use EntityTransactions if the transaction type of your persistence unit is JTA.