Showing posts with label jpa. Show all posts
Showing posts with label jpa. Show all posts

Friday, November 19, 2010

Devoxx 2010 daily notes: day four

Java EE Key Note: The Future Roadmap of Java EE

Java EE wil evolved to cloud platform and, to do so, it will needs modularity based on Java SE.

JSF 2.1

JSF 2.1 will propose:

  • transient state saving
  • XML view cleaning
  • targeted to HTML 5

JMS

JMS is an old specification, which need to evelove for addressing new communication layers:

  • resolving specification ambiguities
  • standardized vendor extension
  • integration with other specifications
  • integration with the web tier (websocket, JSON, NIO2)

JPA 2.1

JPA targets to improve standardization, flexibility and control of persistence context synchronization. The metamodel will be extended to ORM.

Several addition will take place in this release:

  • add event listener
  • outer join with ON conditions
  • update and delete query based
  • mapping between JPQL and criteria queries
  • DB and vendor function invocation
  • support stored procedure

The expert group will be done for january 2011, but the release date could be delay by J2EE timeline (modularity is waiting for Java SE 8).

JAX-RS

JAX-RS 2.0 should be commited in december.

Actually, JAX-RS specification is not included into web profile.

A client API will be added:

  • low level builder pattern
  • high level response matching

JAX-RS will be adapted for MVC architecture based on JSP and Scalate.

Asynchronous, base on Atmosphere (HTTP streaming), will be too added with validation and injection. For exeample, @Context will be replaced by @Inject).

Comparing JVM Web Frameworks

In 2004, criteria to choose a web framework were:

  • request, component or RIA
  • stateful or stateless
  • project community
  • project futur
  • maintenance
  • technical features

And the choice could be described this way:

  • High traffic: request framework
  • Intranet: component
  • Products: products vendor

Now, in 2010, criteria are:

  • development productivity
  • developer perception
  • learning curve
  • project health
  • developer availability
  • job trends
  • templating
  • components
  • ajax
  • plugin
  • scalability
  • REST support
  • multi language
  • validation
  • books
  • doc
  • mobile
  • risk

After a comparison, to top five is:

  • Spring MVC (pro: configuration, integrtion, REST support; cons: instant reload)
  • GWT (pro: write in Java, easy to learn; cons: slow compilation)
  • Rails (pro: easy to learn, doc; con: performance, development tools)
  • Grails (pro: esay for Java programmers; cons: targeted to Java programmers)
  • Wiket (pro: for Java developpers; cons: no developpers available)

Standard DI with @Inject and JSR-330

CDI is a joined proposition from Google and Spring. It is resumed by five annotations and one interface.

@Inject identifies injectable members, that can be any visible fields (static or instance).

Injection order is:

  1. constructor
  2. fields
  3. methods

By default each time an injection must be done, a new instance is created.

@Qualifier allows to solve naming ambiguities by providing a way to create annotation to qualify a classe.

Interface Provide is a kind of factory where injection is not enough to create an object.

Guice and Spring Framework implements this JSR.

The Java Persistence Criteria API

JPA started with JPQL, a SQL like query language that can be used in static queries (@NamedQuery) and dynamic queries.

JPQL for dynamic query is:

  • String based: very easy to do
  • SQL like syntax
  • But it is String: risk of performance lost, lost of readability
  • No type safety

Criteria API is object based and typesafe (use of a metamodel).

CriteriaQuery are composite:

  • roots
  • join
  • expression
  • predicates
  • selections
  • ordering
  • grouping
  • method to assign: select(), multiselect(), from()
  • browse result: getSingleResult()

CriteriaBuilder: a factory of CriteriaBuilder for Expression and Predicate:

select c from Customer c;

TypedQuery tq = em.createQuery(Customer);

List resultList = tq.getResultList();

  • join -> root.join("orders");
  • where -> cq.where(cb.equal(root.get("...")).select(root)

There is hole in type safety in join and where: usage of string to specify attribute name.

The solution used by JPA is to generate at compile time a static metamodel (logical view).

Directly accessible via EntityManager.getMetamodel(), it is defined by a hierarchy of interfaces to describes types and attributes. So, browsing the metamodel is possible.

Now, it is possible to replace String in criteria by metamodel attribute or by accessing directly to the metamodel (path navigation).

Path navigation brings tha ability to access attributes of composite object: c.get(attribute_a).get(attribute_b). It is used to compound predicates.

CriteriaQuey is able to create subqueries and to call database specific function: cb.function("NAME", return_type, path);

Criteria parameters are created by using CriteriaBuilder and can be named.

Queries are modifiable.

HTML 5 Fact and Fiction

HTML 5 is mainly a collection of features.

It is actually better supported on mobile devices than on desktop.

HTML 5 is driven by mobile development. Developping a native application for each platform is too cheaper, we need a common platform, and this the web.

Feature detection can be done with Javascript and preferably by using library such as Modernizr.

Now, browser evolution is driven by specification. This can avoid a quirck mode where standard is more or less respected. HTML header file becomes:

HTML brings very feww components. So, developers uses external library, but there is no standard. HTML 5 comes with new input types. If they are not yet supported by browser, a text field is displayed. One of the target of such component is to brings facilities to mobile devices. For example, an email input field results to the @ symbol to be directly available on the keyboard.

It defines too things that are used from decades such as headers and footers.

It brings too:

  • autofocus
  • local storage: response to heavy cookie usage
  • offline mode: cache the application
  • microdata: semantic web
  • multithreading
  • geolocation (not part of HTML 5)

Activiti in Action

Activiti is a BPM open source tool , it is now mainly developed by Alfresco, but these are 2 distinct products, it is supported by SpringSource and Signavio. Activiti is based on the BPMN 2.0 standard, and the data can be persisted in an XML format.

Activiti allows you to model a process in BPMN 2.0 using “Activiti modeler” (from Signavio), or via an eclipse-based interface. At each step of the process, you can define who can execute the task, and define what are the information that should be filled in. Afterwards, you can initiate process instances, and each person involved will have access to the “activiti explorer” where he will have the possibility to fill in the required information. Once a process step is completed, activity notifies the next person involved that he has a task to do. The “activiti explorer” also provides analysts with process instances status and statistics (it is also possible to create easily a BIRT report about process instances report).

Activiti also provides other modules:

  • Activiti Probe (check process status)
  • Activiti Cycle (BPM collaboration platform)
  • iPhone client
  • Grails integration

Finally, Activiti is highly customizable and can be easily embedded into another application (you can, for instance, request to add a document into Alfresco at a particular process step using 5 lines of Java code …)

  • SpringSource provides an integration via a bean
  • A full query API provides access to the Activiti data
  • REST interface provided (used by an iPhone application

Thursday, November 18, 2010

Devoxx 2010 daily notes: day three

Java SE Keynote

Java platform is now targeting:

  • productivity
  • performance
  • universality
  • modularity
  • integration

Java language evolution will be:

  • for generics: declarations like: HashMap<String, List<String>> map = new HashMap<String, List<String>>(); will become: HashMap<String, List<String>> map = new HashMap<>();
  • lambada expressions will be added (JDK 8)
  • type reification: primitive type will be used as generics
  • module will be added: based on descriptor (module-info.java) and manage by JMOD (integration with maven and its repositories)
  • module will be able to be package as RPM, JAR or DEB or directly managed by JMOD

Java evolution has been planned until 2030.

For the roadmap:

  • Java 7: end of july 2011 (project coin, fork/join framework)
  • Java 8: end of 2012

Java Persistence 2.0

JPA 2.0 brings some news:

  • Criteria API
  • pessimistic lock
  • metamodel API
  • standardize configuration
  • collections of basic types

Basic types collections:

  • @ElementCollection: this collection must be stored as an elmeent collection
  • @CollectionTable(...): specify the table name
  • @Colcumn(...): specify the collection column name

Embadable objects:

  • multi level (@AttributeOverride)
  • relationship (@AssociationOverride, @JoinTable)

Persistence order:

  • implemented by provider as an additional column (@OrderColumn)
  • in case of legacy use @OrderBy to use existing schema

Maps usage:

  • key: basic type, embeddable, entity
  • value: basic type, embeddable, entity

JPQL:

  • conditional expression: CASE ... THEN .. (usefull with map)
  • restriction on type TYPE(e) IN (...) (usefull for inheritance)

Criteria API: support object and strinf literals

  • CriteriaQuery: query description
  • CriteriaBuilder: criteria query objects factory
  • How to express: select c from Customer
    CriteriaQuery cq = criteriaBuilder.createQuery(Customer.Class);
    Root root = cq.from(Customer.class);
    cq.select(root);

Metamodel: abstract schema model.

Pessemistic lock: specify mode as properties.

Second level cache API: use of @Cacheable on properties

Standardized configuration by providing a set of default properties.

Validation: automatic validation for PrePersist, PreUpdate and PreRemove.

The Next Big JVM Language

Actually, languages challenge Java by providing more features and different expression ways (have a look to Stephen Colebourn).

What Java has done right:

  • simplify C++ migration
  • take old ideas but JVM make them popular (garbage collector for example)

What Java has done wrong:

  • Checked exception: how to ignored them?
  • primitives: split type system
  • arrays: split type system and expose JVM future
  • monitors: unsafe effects, difficult to optimize
  • static: cannot be override, hurt concurrency
  • method overloading: complexity for compiler and for programmer
  • generics: too complex, background compatibility result in erasure

The New Big JVM Language should be:

  • like C syntax
  • multi paradigm: object oriented and functional
  • type system: static typing
  • easy reflection
  • have properties
  • have closure in language core
  • a better null handling (avoiding NullPointerException and long and borring debugging)
  • thread not exposed
  • have modules
  • good tooling (make tooling esay to build)
  • extensible (combination of language feature)
  • not verbose

No JVM languages fullfil these criteria, so, perhaps it is time for a none backward compatible version of Java: Java 9?

Project Lambda: To Multicore and Beyond

The based of Lambda project is SAM types: interfaces or abstract classes with a single abstract method.

Closure take the following syntax:

#{Person.getLastName()}

Collection framework will be adapted to provides facilities based on closure, such as filtering, sorting, etc...

New key words will be added to define immutable classes and their properties:

value class ImmutableClass {  
properties String lastname;
}

Actually, modifying an interface results to breaking API compatibility. With Lambda, it will be possible to add method with default behavior.

Spring 3.1 - Themes and Trends

Spring 3.0 brings:

  • annotated component model
  • expression language
  • REST support
  • Portlet 2.0
  • support Java EE 6 (JPA 2)
  • custom annotation
  • include JavaConfig (configuration classes)
  • @Value (use of value express with EL)
  • model validation @Valid on parameters
  • type conversion @DateTimeFormat(iso=ISO.DATE)
  • annotation scheduling: @Scheduled

Spring 3.1 will provide:

  • environment profiles
    • activated in command line by: -DspringProfile=env
    • provides environment abstraction as an API
    • custom placeholder resolution
  • java based configuration: @Configuration on class
  • cache abstraction
    • EhCache support (important for cloud)
    • support for Gemfire, Coherence
    • annotation @Cacheable
    • cache could be conditional
    • @CacheEvict to avoid caching
    • new namespace declaration
  • conversation management:
    • HttpSession ++
    • association with browser and tabs
    • foundation for WebFlow 3
  • Groovy will be used as template engine
  • c: namespace for constructor arguments
  • Roadmap:
    • M1 in december
    • 3.1 GA march/april 2011

HTML 5 Websockets: A New World of Limitless, Live, and Wickedly Cool Web Applications

Actually, HTTP is not full duplex, so, Websockets brings full duplex to web.

It is implemented as a Javascript API that uses IETF protocol, but is still compatible with HTTP. The idea is not to replace HTTP.

Websocket allowed cross origin, secured and unsecured communication in standard.

It is supported by browsers:

  • Chrome 4.0+
  • Safari 5.0, iOS 4
  • Firefox 4 beta
  • to check compatibility, go to Websocket web site

Beyond the scene, Websocket allows:

  • connection reuse
  • extends client server protocol (available in JS API)
From the tests, Websocket, compared to pure HTTP, reduce latency from 150 ms to 50 ms.

Visage Android Workshop

Visage is a dynamic UI language inspired by Flex and JavaFX for different target, and especially, for Android.It is declarative, brings data binding, provides closure to implements triggers and brings null safety.

Compilation is divided in two phases:

  • Visage to Java bytecode
  • Bytecode to Dalvik

Friday, July 23, 2010

DAO or not DAO? This is the question...

In a multi tiers architecture application, data access are managed by dedicated object, called: Data Access Object, aka DAO. They are responsible how to connect to data store and brings functionalities for making operation on data. For the following explanation, I will use JPA as ORM.

DAO approach

A general way to implement the DAO layer is a parametrized interface defining contract for CRUD operations:

public interface GenericDao<E, PK> {
E findByPrimaryKey(PK pk);

void save(E entity);

void update(E entity);

void delete(E entity);
}

And now, we define an abstract class implementing a JPA dedicated DAO. The default constructor is used to determine the type of the entity and the primary key type, that allows to implement CRUD operation:

public abstract class JpaDao<E, PK> implements GenericDao<E, PK> {

private EntityManager entityManager;

public JpaDao() {
ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
this.entityType = (Class<E>) genericSuperclass.getActualTypeArguments()[0];
}

protected EntityManager getEntityManager() {
return entityManager;
}

public E findByPrimaryKey(PK pk) throws DataAccessException {
return entityManager.find(entityType, pk);
}

public void save(E entity) throws DataAccessException {
entityManager.persist(entity);
}

public void update(E entity) throws DataAccessException {
entityManager.merge(entity);
entityManager.flush();
}

public void delete(E entity) throws DataAccessException {
entityManager.remove(entity);
}

public List<E> findAll() throws DataAccessException {
Query query = entityManager.createQuery("SELECT e FROM " + entityType.getName() + " AS e");
return query.getResultList();
}
}

This implementation forces to get one DAO per entity, even in case non additional operations are needed. And separate DAO and entities encourages AnemicDomainModel discussed by Martin Follower. In this case, entities are only by bag of getters and setters without any behavior.

Brings DAO functionalities to entities

My proposal is to implement a utility class to manage data access. A kind of generic DAO.

Utilities for DAO implementation

This class has to be a singleton that shares an EntityManager between every entities. It implements too methods to create and commit transaction. Generic functions are implemented fro CRUD operation and takes a entity class object as parameter to apply CRUD on entity class:

public final class EntityUtility {
private EntityManager entityManager;

private static EntityUtility instance = new EntityUtility();

public static EntityUtility instance() {
return instance;
}

public final EntityManager getEntityManager() {
return entityManager;
}

public final void setEntityManager(EntityManager em) {
entityManager = em;
}

public <T> List<T> find(Class<T> entityClass, String where, Object... values) {
EntityTransaction transaction = getEntityManager().getTransaction();
transaction.begin();
StringBuilder builder = new StringBuilder("SELECT e FROM ");
builder.append(entityClass.getName());
builder.append(" AS e WHERE ");
builder.append(where);
Query query = getEntityManager().createQuery(builder.toString());
for(int i = 0; i < values.length; i++) {
query.setParameter(i + 1, values[i]);
}

List<T> result = query.getResultList();
transaction.commit();
return result;
}

public <T> List<T> findAll(Class<T> entityClass) {
EntityTransaction transaction = getEntityManager().getTransaction();
transaction.begin();
StringBuilder builder = new StringBuilder("SELECT e FROM ");
builder.append(entityClass.getName());
builder.append(" AS e");
Query query = getEntityManager().createQuery(builder.toString());
List<T> result = query.getResultList();
transaction.commit();
return result;
}

public <T> void save(T entity) {
EntityTransaction transaction = getEntityManager().getTransaction();
transaction.begin();
getEntityManager().persist(entity);
transaction.commit();
}

public <T> void delete(T entity) {
EntityTransaction transaction = getEntityManager().getTransaction();
transaction.begin();
getEntityManager().remove(entity);
transaction.commit();
}

public <T> void refresh(T entity) {
EntityTransaction transaction = getEntityManager().getTransaction();
transaction.begin();
getEntityManager().refresh(entity);
transaction.commit();
}

public <T> void update(T entity) {
EntityTransaction transaction = getEntityManager().getTransaction();
transaction.begin();
getEntityManager().merge(entity);
transaction.commit();
}
}

Entity superclass

To bring data access capabilities to entities, I need a class to bring CRUD methods implementation to entity classes. This class should provide implementation for creation, deletion and update methods:


public class Model {
protected static EntityUtility utility = EntityUtility.instance();

public final void save() {
utility.save(this);
}
public final void refresh(){
utility.refresh(this);
}
public final void update() {
utility.update(this);
}
public final void delete() {
utility.delete(this);
}

Entity implementation

Methods such find and findAll should be implemented as static method in entity level, but use EntityUtility functionality that provides methods to find entities by using where clause passed as parameter:

@Entity
public class User extends Model {
@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String firstName;
private String lastName;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

public Long getId() {
return id;
}

public static List<User> find(String where, Object... values) {
return utility.find(User.class, where, values);
}

public static List<User> findAll() {
return utility.findAll(User.class);
}
}

Conclusion

In this case, entities should inherit a class. It could be seen as a regression as JPA brings ORM POJO based implementation. But the Model class gives ORM functionalities such:

  • persistence
  • remove
  • refresh state
  • update

Model miss methods for search functionalities. So, Entity classes can implement static methods as delegate of EntityUtility methods.