Book Image

Java EE 7 Developer Handbook

By : Peter A. Pilgrim
Book Image

Java EE 7 Developer Handbook

By: Peter A. Pilgrim

Overview of this book

<p>The seventh edition of the Enterprise Java platform is aimed at helping Java engineers take advantage of the advancements in HTML5 and web standards. Web Sockets, asynchronous input and output with Servlets, and strong type safety through the CDI containers will ensure that Java EE 7 remains popular for server-side applications.<br />If you are a user aiming to get acquainted with the Java EE 7 platform, this book is for you.</p> <p>"Java EE 7 Developer Handbook" provides a solid foundation of knowledge for developers to build business applications. Following the lead of Agile practices, there is a focus on writing tests to demonstrate test-driven development principles, using the embedded GlassFish 4.0 container examples and the Gradle build system. You will learn about CDI, EJB, JPA, JMS, MDB, Servlets, WebSocket, JAX-RS, Bean Validation, and so much more.</p> <p>"Java EE 7 Developer Handbook" is designed as a companion to the professional software developer who quickly needs to lookup some working code, understand the basics of the framework, and then go out and fulfill the business contract with the customer. Typically, engineers are under pressure to develop professional code that is of high quality and contains a low number of bugs. Java EE 7 Developer Handbook relies heavily on the Arquillian framework to illustrate how much easier it is to write Java EE tests, and together with the modern practice of writing containerless applications that actually embed an application container, developing agile Java EE suddenly becomes reasonable, smart, pragmatic, and achievable.</p> <p>You will start off with an overview of the Java EE platform: the containers, the design, and architecture. From there, you can follow the path of the CDI, the true gem of the framework, and then the server side end point, EJB. It is completely up to you when and if you want to learn about Java persistence. However, don’t miss out on the highlights of Java EE 7 such as WebSocket, Bean Validation, and asynchronous Servlet API.</p> <p>"Java EE 7 Developer Handbook" is a vertical slice through standard Java enterprise architecture. If you have been wondering why developers have invested so much time and effort into learning topics such as Enterprise Java Beans, you will quickly understand why when you find out the difference between stateful and stateless Beans. Best of all, this book covers the topic from the perspective of new API and new modern practices. For instance, you, the developer and designer, are expected to write applications with annotations in comparison with J2EE. Java EE 7 Developer Handbook incorporates helpful hints and tips to get the developer up to speed in a short amount of time on EJB, CDI, Persistence, Servlet, JMS, WebSocket, JAX-RS and Bean Validation, and much more.</p> <p>"Java EE 7 Developer Handbook" is the reference guide you need beside you at your desk.</p>
Table of Contents (23 chapters)
Java EE 7 Developer Handbook
Credits
About the Author
Acknowledgment
About the Reviewers
www.PacktPub.com
Preface
Index

JPA miscellaneous features


This section covers some advanced JPA 2.1 mapping features.

Converters

JPA 2.1 defines converters for translating data values from Java to database specific values. Converters make it easy to write Java interpreters for special monetary values, enumerated text values, and Boolean values. It is very common in business to have different designations for Boolean in a production database. Some tables may have text columns, say T, F or Y, N and others have integers 0 and 1.

Here is a converter that translates trade data in a database in order to determine if the bank is buying or selling to and from a counterparty.

enum Direction { BUY, SELL }

@Converter
public class TradeDirectionConverter
    implements AttributeConverter<Direction,String>
{
    @Override
    public String convertToDatabaseColumn(Direction attribute) {
        switch (attribute) {
            case BUY: return ""P"";
            default: return ""S"";
        }
    }

    @Override
    public Direction convertToEntityAttribute(String dbData) {
        dbData = dbData.trim().toLowerCase();
        if ( dbData.equals(""P""))
            return Direction.BUY;
        else
            return Direction.SELL;
    }
}

The convertor class TradeDirectionConverter extends the AttributeConverter Java generic interface, new in JPA 2.1. The developer simply implements two methods convertToEntityAttribute() and convertToDatabaseColumn() as the conversion process is bidirectional.

We can apply this converter to the entities with the Direction type. Here is an example of the converter in a foreign-exchange bank trade entity.

@Entity @Table(name = ""FXTRADE"")
public class ForexTrade {
    /* ... */
    @Convert(converter=TradeDirectionConverter.class)
    Direction direction;
    /* ... */
}

We explicitly declare the convertor with the @Convert annotation that references the conversion class.

JPA 2.1 also allows converters to be applied globally across the entire domain. To allow this, the converter must be annotated as @Converter(autoApply = true). Global convertors do not require an entity to be explicitly annotated with @Convert on the field or properties. These definitions, therefore, can be removed for global converters.

Tip

A word of caution about JPA conversions: be careful with your JPQL statements such that they reflect the Java side of the conversion. Take care with native SQL query statements and mixing Java queries so that they reflect the end result of data that is actually stored inside the database.

Native constructor results

It is possible to build a projection, which is a partial view of an entity having a narrower collection of columns, with a JPQL statement using the syntax: SELECT NEW. Unfortunately, in the previous specification, it was not possible to write native SQL using JPA to build entities and non-entities.

Here is a JPQL query to view a financial banking trade as a non-entity:

SELECT NEW TradeView(t.id, t.book, t.tradeDate, t.settlementDate, t.amount, t.ccy )
FROM Counterparty c JOIN c.trades t
WHERE t.amount >= 250000 AND t.book = ""Exchange West"" AND t.ccy = ""USD""

In JPA 2.1 the new annotation @ConstructorResult is designed for native SQL queries to build an entity or non-entity. The @ConstructorResult is combined with the @ColumnResult to build a dynamic constructor argument list by type.

Here is an example of a native SQL query that creates a bond trade:

@NamedNativeQuery(
  name=""BondTradeView.findByAccountId"",
  query=""SELECT B.TRADE_ID, B.NOTIONAL, A.ACC_NAME, ""+""A.CPTY_NAME FROM TRADE B, ACCOUNT A ""+""WHERE B.TYPE=''BOND'' ""+""AND B.ACC_ID = A.ACC_ID AND A.ACC = :ID "",resultSetMapping=""bondtradeview""
)
@SqlResultSetMapping(name=""bondtradeview"", 
  classes={ 
    @ConstructorResult(targetClass=BondTradeView.class, columns={
        @ColumnResult(name=""TRADE_ID"", type=Integer.class),
        @ColumnResult(name=""NOTIONAL"", type=BigDecimal.class),
        @ColumnResult(name=""ACC_NAME"", type=String.class),
        @ColumnResult(name=""CPTY_NAME"", type=String.class)
    })
  }
)
public class BondTradeView {
  /* ... */
}

In order to use @ConstructorResult correctly, we must apply it to a SQL result set mapping and also the named native query.