Thursday, September 1, 2011

JPA2

82

Identifier Generation

@GeneratedValue

AUTO, TABLE, SEQUENCE, or IDENTITY

@Entity
public class Employee {
@Id @GeneratedValue(strategy=GenerationType.AUTO)
private int id;
// ...
}

Id Generation Using a Table

@Id @GeneratedValue(strategy=GenerationType.TABLE)
private int id;

@TableGenerator(name="Emp_Gen")
@Id @GeneratedValue(generator="Emp_Gen")
private int id;

@TableGenerator(name="Emp_Gen",
table="ID_GEN",
pkColumnName="GEN_NAME",
valueColumnName="GEN_VAL")

@TableGenerator(name="Address_Gen",
table="ID_GEN",
pkColumnName="GEN_NAME",
valueColumnName="GEN_VAL",
pkColumnValue="Addr_Gen",
initialValue=10000,
allocationSize=100)
@Id @GeneratedValue(generator="Address_Gen")
private int id;

Id Generation Using a Database Sequence

@Id @GeneratedValue(strategy=GenerationType.SEQUENCE)
private int id;

@SequenceGenerator(name="Emp_Gen", sequenceName="Emp_Seq")
@Id @GeneratedValue(generator="Emp_Gen")
private int getId;

CREATE SEQUENCE Emp_Seq
MINVALUE 1
START WITH 1
INCREMENT BY 50

Id Generation Using Database Identity

@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;

There is no generator annotation for IDENTITY because it must be defined as part of the database schema definition for the primary key column of the entity. Because each entity primary key column defines its own identity characteristic, IDENTITY generation cannot be shared across multiple entity types.
Another difference, hinted at earlier, between using IDENTITY and other id generation strategies is that the identifier will not be accessible until after the insert has occurred

Relationships

Relantionship Concepts:

  • Roles

  • Directionality

  • Cardinality

  • Ordinality




Single-Valued Associations/
An association from an entity instance to another entity instance (where the cardinality of the target is “one”) is called a single-valued association. The many-to-one and one-to-one relationship mappings fall into this category because the source entity refers to at most one target entity.

Many-to-One Mappings
@Entity
public class Employee {
// ...
@ManyToOne
private Department department;
// ...
}

A many-to-one mapping is defined by annotating the attribute in the source entity (the attribute that refers to the target entity) with the @ManyToOne annotation


Using Join Columns
In almost every relationship, independent of source and target sides, one of the two sides will have the join column in its table. That side is called the owning side or the owner of the relationship. The side that does not have the join column is called the non-owning or inverse side.

@Entity
public class Employee {
@Id private int id;
@ManyToOne
@JoinColumn(name="DEPT_ID")
private Department department;
// ...
}

One-to-One Mappings

@Entity
public class Employee {
@Id private int id;
private String name;
@OneToOne
@JoinColumn(name="PSPACE_ID")
private ParkingSpace parkingSpace;
// ...
}

Bidirectional One-to-One Mappings

@Entity
public class ParkingSpace {
@Id private int id;
private int lot;
private String location;
@OneToOne(mappedBy="parkingSpace")
private Employee employee;
// ...
}

The value of mappedBy is the name of
the attribute in the owning entity that points back to the inverse entity.
The two rules, then, for bidirectional one-to-one associations are the following:
• The @JoinColumn annotation goes on the mapping of the entity that is mapped to
the table containing the join column, or the owner of the relationship. This might
be on either side of the association.
• The mappedBy element should be specified in the @OneToOne annotation in the
entity that does not define a join column, or the inverse side of the relationship.



95

Monday, July 25, 2011

JPA2

69
Persistence annotations can be applied at three different levels: class, method, and field

The mapping annotations can be categorized as being in one of two categories: logical
annotations and physical annotations

ACCESSING ENTITY STATE
If we annotate fields, the provider will get and set the fields of the entity using reflection.

If the annotations are set on the getter methods of properties, those getter and setter methods will be invoked by the provider to access and set the state.

@Entity
public class Employee {
@Id private int id;

Mixed access
@Entity
@Access(AccessType.FIELD)
public class Employee {
public static final String LOCAL_AREA_CODE = "613";
@Id private int id;
@Transient private String phoneNum;

public int getId() { return id; }
public void setId(int id) { this.id = id; }

Mapping To A Table

Listing 4-4. Overriding the Default Table Name
@Entity
@Table(name="EMP")
public class Employee { ... }

Listing 4-5. Setting a Schema
@Entity
@Table(name="EMP", schema="HR")
public class Employee { ... }

Listing 4-6. Setting a Catalog
@Entity
@Table(name="EMP", catalog="HR")
public class Employee { ... }

Mapping Simple Types
If the type from the JDBC layer cannot be converted to the Java type of the
field or property, an exception will normally be thrown, although it is not guaranteed.

An optional @Basic annotation can be placed on a field or property to explicitly mark it as being persistent. This annotation is mostly for documentation purposes and is not required for the field or property to be persistent. Because of the annotation, we call mappings of simple types basic mappings. Now that we have seen how we can persist either fields or properties and how they are virtually equivalent in terms of persistence, we will just call them attributes. An attribute is a field or property of a class, and we will use the term attribute from now on to avoid having to continually refer to fields or properties in specific terms.

Column Mappings

Listing 4-7. Mapping Attributes to Columns
@Entity
public class Employee {
@Id
@Column(name="EMP_ID")
private int id;
private String name;
@Column(name="SAL")
private long salary;
@Column(name="COMM")
private String comments;
// ...
}

Lazy Fetching

Listing 4-8. Lazy Field Loading
@Entity
public class Employee {
// ...
@Basic(fetch=FetchType.LAZY)
@Column(name="COMM")
private String comments;
// ...
}

Second, on the surface it might appear that this is a good idea for certain attributes of an entity, but in practice it is almost never a good idea to lazily fetch simple types.

Large Objects

Listing 4-9. Mapping a BLOB Column
@Entity
public class Employee {
@Id
private int id;
@Basic(fetch=FetchType.LAZY)
@Lob @Column(name="PIC")
private byte[] picture;
// ...
}

Enumerated Types

@Entity
public class Employee {
@Id private int id;
private EmployeeType type;
// ...
}

Listing 4-11. Mapping an Enumerated Type Using Strings
@Entity
public class Employee {
@Id
private int id;
@Enumerated(EnumType.STRING)
private EmployeeType type;
// ...
}

Temporal Types

Listing 4-12. Mapping Temporal Types
@Entity
public class Employee {
@Id
private int id;
@Temporal(TemporalType.DATE)
private Calendar dob;
@Temporal(TemporalType.DATE)
@Column(name="S_DATE")
private Date startDate;
// ...
}

Transient State
Attributes that are part of a persistent entity but not intended to be persistent can either be modified with the transient modifier in Java or be annotated with the @Transient annotation.

81

Monday, July 4, 2011

JPA2 - 04 iulie

Dependency lookup


A reference is declared using one of the resource reference annotations: @Resource, @EJB, @PersistenceContext, or @PersistenceUnit.

@Stateless
public class EmployeeServiceBean implements EmployeeService {
@PersistenceContext(unitName="EmployeeService")
EntityManager em;
// ...
}

@Stateful
public class EmployeeServiceBean implements EmployeeService {
@PersistenceUnit(unitName="EmployeeService")
private EntityManagerFactory emf;
private EntityManager em;
@PostConstruct
public void init() {
em = emf.createEntityManager();
}
// ...
}

@Stateless
public class DeptServiceBean implements DeptService {
@EJB(beanName="AuditServiceBean")
AuditService audit;
// ...
}

Transactions
@Stateless
@TransactionManagement(TransactionManagementType.BEAN)
public class ProjectServiceBean implements ProjectService {
// methods in this class manually control transaction demarcation
}

@Stateful
public class ShoppingCartBean implements ShoppingCart {
@TransactionAttribute(TransactionAttributeType.SUPPORTS)
public void addItem(String item, Integer quantity) {
verifyItem(item, quantity);
// ...
}
// ...
}

CMT or BMT

Thursday, June 30, 2011

JPA2 - 30 iunie

em.find(Employee.class,14)
em.remove(emp);
em.getTransaction().begin();
em.getTransaction().commit();
em.close();
emf.close();

Query - either Query or TypedQuery

1. static query - named query
2. dynamic query

TypedQuery query = em.createQuery("SELECT e from EMPLOYEE e");
List emps = em.getResultList();

<persistence-unit name="EmployeeService"
transaction-type="RESOURCE_LOCAL">
RESOURCE_LOCAL means that we are using resource-level EntityTransaction
isntead of JTA.

---------------
calculat ca imi ia 22 de zile sa citesc cartea (hai sa vedem daca reusim in 5)
---------------

Session beans - encapsulate business services
have a business interface
a client gets a session bean and starts a session with that bean

3 types - stateless, stateful and singleton
business operations on a stateful session bean can maintain state on the bean between calls. This is not true for a stateless session bean.
singleton - just one

@Stateless annotation

To emphasize that an interface is a local business interface @Local annotation
can be put on the interface.

Local business interface means that it is accessible to clients only within the same application server.

You can also define it with no interface. In this case the local business interface will be considered the public methods from that class.

For
stateless session beans, there are two lifecycle callbacks: PostConstruct and PreDestroy.

The server will invoke the PostConstruct callback as soon as it has completed initializing all the container services for the bean. In effect, this replaces the constructor as the location for initialization logic because it is only here that container services are guaranteed to be available.

@Remote
public interface HelloServiceRemote {
public String sayHello(String name);
}

@Stateful
public class ShoppingCartBean implements ShoppingCart {

@Remove
public void checkout(int paymentId) {
// store items to database
// ...
}
}

Passivation is the process by which
the server serializes the bean instance so that it can either be stored offline to free up resources or
replicated to another server in a cluster. Activation is the process of deserializing a passivated session
bean instance and making it active in the server once again.

@PrePassivate
public void passivate() { releaseConnection(); }
@PostActivate
public void activate() { acquireConnection(); }

Unlike other session beans, the singleton can be created eagerly during application initialization and exist until the application shuts down.

@Singleton
public class HitCounter {
int count;
public void increment() { ++count; }
public void getCount() { return count; }
public void reset() { count = 0; }
}

The container determines the point when the singleton instance gets created unless the bean includes the @Startup annotation to force eager initialization when the application starts.

When multiple singleton session beans depend on one another, the container needs to be informed of the order in which they should be instantiated. This is accomplished via the @DependsOn annotation on the bean class, which lists the names of other singleton session beans that must be created first.

@Singleton
public class HitCounter {
int count;
public void increment() { ++count; }
@Lock(LockType.READ)
public void getCount() { return count; }
public void reset() { count = 0; }
}

For those who wish to have fine-grained control over concurrency, the singleton session bean can be configured to use bean-managed concurrency via the
@ConcurrencyManagement(ConcurrencyManagementType.BEAN) annotation on the bean class.

@MessageDriven(
activationConfig = {
@ActivationConfigProperty(propertyName="destinationType",
propertyValue="javax.jms.Queue"),
@ActivationConfigProperty(propertyName="messageSelector",
propertyValue="RECIPIENT='ReportProcessor'")
})
public class ReportProcessorBean implements javax.jms.MessageListener {
public void onMessage(javax.jms.Message message) {
// ...

Wednesday, June 29, 2011

JPA2

Objects that leave the persistence layer are called detached objects

The set of managed entity instances within an entity manager at any
given time is called its persistence context.


There is an one-to-one correspondence between an EntityManagerFactory and a persistence unit.


----------------------------

correspondence timeunit ?

----------------------------

EntityManagerFactory emf =
Persistence.createEntityManagerFactory("EmployeeService");

1 to 1 EntityManagerFactory and persistence unit

Tuesday, April 5, 2011

5th of april

morning - figure out a plan for doing something, think of an activity for after
noon - take the towel (do some cleaning - take trash,etc)
after work - continue cleaning,clean the computer, change, if enough time do some shopping, think of an activity


acting, cantat in pasaj, cantat in dal, unghii

Thursday, March 31, 2011

JSF2 complete reference - again 6 - march 31

312 (343)

read about a simple input component, the fact
that u have to declare in a taglib.xml and also
have the java class that defines the component (u could also
have a separate renderer).

The java class must have an annotation @FacesComponent(value = "nameOfTheComponent")
or you have to declare in faces-config.xml.