SlideShare ist ein Scribd-Unternehmen logo
1 von 78
TOP 50 JAVA EE 7 BEST
PRACTICES
Ryan Cuprak
Michael Remijan
About Us
Ryan
• @ctjava
• rcuprak@gmail.com
• http://www.cuprak.info
• https://www.linkedin.com/in/rcuprak
Michael
• @mjremijan
• mjremijan@yahoo.com
• http://mjremijan.blogspot.com
• http://linkedin.com/in/mjremijan
EJB 3 In Action 2nd Edition
Updated For
• EE 7
• EJB 3.2
Java EE 7
Concurrency
Utilities
Batch
Applications
Java
API for
JSON
Java API for
WebSocket
JSF 2.2
JSX-WS
2.2
JAX-RS
2
EL 3
Servlet 3.1
Common
Annotations 1.2
Interceptors 1.2 CDI 1.1
Managed Beans 1.0 EJB 3.2
Connector
1.7
JPA 2.1 JTA 1.2 JMS 2
JSP 2.3
JAXB
#1 JAX-RS: API Versioning
Version your JAX-RS with one of two approaches:
1. URL
http://ctjava.org/v2/meetings
http://ctjava.org/v1/meetngs
2. Media Content or Header Param
curl -H "Content-Type:application/srv-v4+json” …
Return HTTP Status Codes for services moved/changed:
• 301 Moved Permanently
• 302 Found
#1 JAX-RS: API Versioning (Continued…)
Approach 1: URL
Approach 2: Media Types
#1 JAX-RS: API Versioning (Continued…)
Service Moved Permanently
#2 JAX-RS: Error Handling
Provide ExceptionMappers to handle and process errors.
#2 JAX-RS: Error Handling (Continued…)
HTML content is hardly a friendly response for an API!
#2 JAX-RS: Error Handling (Continued…)
#3 JAX-RS: Caching
Tell clients to cache data!
#4 JAX-RS + Bean Validation
Use Bean Validation to check data.
#5 JAX-RS: Compress Responses
Use gzip compression for responses to reduce bandwidth.
#6 Securing RESTful Services
• Use tokens with RESTful Web Services (OWASP).
• Leverage JASPIC to setup JAAS environment.
#7 JAX-RS + EJB
• Use @Stateless and @Path together
• Pooled, thread safe, monitored
#7 JAX-RS + EJB (Continued…)
• http://localhost:4848/monitoring/domain/server/applications/WebApp
lication1/StatelessResource/bean-methods/getText[.json]
#8 JAX-RS: Asynchronous API Gateway
• Gateway calls multiple microservices asynchronously
• Combines results into a DTO
#8 JAX-RS: Async…(Continued…)
• Gateway calls multiple microservices asynchronously
• Combines results into a DTO
#9 JPA: Pagination
Use pagination for potential large result sets.
#9 JPA: Pagination (Continued…)
#10 JPA: Lazy Relationships
Avoid unnecessary queries – use Fetch on Lazy
relationships.
#10 JPA: Lazy Relationships (Continued…)
1. SELECT MEETINGID, DATE, MEETINGABSTRACT, TITLE FROM MEETING WHERE (MEETINGID
= ?)
2. SELECT t1.SPEAKERID, t1.BIOGRAPHY, t1.FIRSTNAME, t1.LASTNAME FROM meeting_speakers
t0, SPEAKER t1 WHERE ((t0.meetingid = ?) AND (t1.SPEAKERID = t0.speakerid))
#10 JPA: Lazy Relationships (Continued…)
1. SELECT t1.MEETINGID, t1.DATE, t1.MEETINGABSTRACT, t1.TITLE, t0.SPEAKERID, t0.BIOGRAPHY,
t0.FIRSTNAME, t0.LASTNAME FROM SPEAKER t0, meeting_speakers t2, MEETING t1 WHERE
((t1.MEETINGID = ?) AND ((t2.meetingid = t1.MEETINGID) AND (t0.SPEAKERID = t2.speakerid)))
1 Query Not TWO!
#11 JPA: Cascade
• Don’t forget cascade levels to handle child data
• cascade=ALL is equivalent to cascade={PERSIST,
MERGE, REMOVE, REFRESH, DETACH}
#12 JPA: Entity Graphs
#13 JPA + DAO
Put CRUD operations into DAOs.
#14 JPA: hashcode() & equals()
The equals and hashcode are required for:
• Entity is added to a collection
• When re-attaching entities to a new persistence context.
Important points:
• Do not use generated identifiers
• Use business key equality
#14 JPA: hashcode() & equals() Continued…
#15 JPA: Optimistic Locking
• Don’t roll your own
• Use @Version for optimistic locking: Integer
#15 JPA: Optimistic Locking (Continued…)
• Timestamp
#16 JPA: Pessimistic Locking
• PESSIMISTIC_READ, PESSIMISTIC_WRITE
• Lock timeout
HINT
#17 JPA: Mapping Inheritance
• Inheritance can have a big impact upon performance.
• Three approaches:
• Single table
• Joined-tables
• Table-per-class
• Denormalize for better performance
#18 JPA L2 Cache
JPA 2 introduced the L2 Cache, use this cache for:
• Entities that are frequently read
• Entities that are modified infrequently
• Not critical if stale
• L2 cache can consume large amounts of memory
• ALL
• NONE
• ENABLE_SELECTIVE
• DISABLE_SELECTIVE
Are you using a default setting?
#18 JPA L2 Cache (Continued…)
Mark entity for L2 cache
Bypass L2 cache
#19 JPA: Persisting ENUM
• ENUM is a good case of converting data types
• Use a @Converter
#19 JPA: Persisting ENUM (Continued…)
• @Converter
• AttributeConverter<X,Y>
• X is my application, Y is the database
#20 EJB: Transaction Handling
• EJBs exist to handle transactions. Keep them at the right layer
• Don’t ignore transactions. Default: REQUIRED
• JAX-RS endpoints, database reads & performance
#21 EJB: Stateless Thread Safety
• Stateless beans are a pooled, managed resource
• Pools configurable by the application server
#22 EJB: Asynchronous
• @Asynchronous runs in container-managed thread
• Return Future<> to get results later
• Ideal for wrapping JAX-RS calls
• Good way to avoid any of your own threading
#23 EJB: Security
• Use declarative security and let the container handle it
• Avoid programmatic security
• EE servers trust principal/roles passed between
containers.
#23 EJB: Security (Continued…)
• EE Configuration
• web.xml
• @DeclaredRoles
• @RolesAllowed
• Custom Configuration
• EE Server Realm
• glassfish-web.xml
#24 EJB: Avoid Lengthy Initialization
Don’t abuse startup – @PostConconstruct delays
You delay initialization of the container!
#24 EJB: Avoid Lengthy Initialization
#25 CDI: Observers
• In-memory event processing
• Very “reactive”
• Decouple work to be done, avoids unnecessary
dependencies
• Create an event to fire
#25 CDI: Observers (Continued…)
• Fire the event
• Observers process the event
#26 CDI: Producer + Cache
• Use a producer to customize creation of an object
• Producer method is always called, so cache the instance
#27 CDI: Interceptors
• Limit to cross-cutting concerns
• Do not use to change business logic
• Create an annotation
#27 CDI: Interceptors
• Create the interceptor
#27 CDI: Interceptors
• Apply the interceptor
#28 CDI: Decorators
• Use to enhance or decorate existing code
• Open-close principle
• Do not use for cross-cutting concerns
#28 CDI: Decorators (Continued…)
• /WEB-INF/beans.xml
• /META-INF/beans.xml
#29 CDI: Transactions
Java EE introduced @Transactional for non-EJBs.
Pro: Easier to utilize transactions outside of EJB.
Con: Mixes layers – transactions & rest etc.
#30 CDI: Bean Discovery
• Java EE 7 CDI is enabled by default.
• beans.xml is no longer required as in EE 6
• Bean discovery mode:
• Annotated – only annotated classes
• All – includes beans that are not annotated
• None – CDI disabled
• Default mode is ‘annotated’
#31 Batch: Java EE not SE
• Think Java EE for batch, not SE
• Batch API
• Cron like schedule on EJB methods
• META-INF/batch-jobs/processInvoices.xml
#32: Batch Best Practices
• Package/deploy batch jobs separately
• Implement logic to cleanup old jobs
• Implement logic for auto-restart
• Test restart and checkpoint logic
• Configure database to store jobs
• Configure thread pool for batch jobs
• Only invoke batch jobs from logic that is secured (@Role
etc.)
#33 JAXB Primitive Data Types
anySimpleType
decimal
integer
long
int
short
byte
float double
nonPositiveInteger
negativeInteger
nonNegativeInteger
unsigneLong positiveInteger
unsignedInt
unsignedInt
unsignedByte
#34 JAXB: Date & Time Representation
• Use XMLGregorianCalendar for dates
• Avoid java.util.Date and java.util.Calendar
• XMLGregorianCalendar
• Handles long fractions of seconds – important to .NET
interoperability
#35 JAXB: Annotate
Don’t let JAXB generate everything!
#36 JAX-WS: RPC vs. Document
• Four different possibilities:
• RPC/Literal
• RPC/Encoded
• Document/Literal
• Document/Encoded
• Encoded is not supported by WS-I
• Default and most commonly used is Document/Literal
• Use Document/Literal
• RPC/Literal:
• Limited to basic XSD types
• WSDL will not include types section to constrain parameters
#37 JAX-WS: JAXB Gotcha
• JAXB will serialize an entire object graph.
Oops!
Use either:
• DTO – Data Transfer Object
• @XmlTransient
#38 JAX-WS Interoperable Services
• Design service starting with the WSDL
• Create data types using XSD
• Keep data types SIMPLE
• Avoid xsd:anyType
• Avoid sending Null values
• Use byte[] instead of String when character encoding is
unknown
#39 SOAP Faults
• Types of SOAP faults:
• Modeled – exception explicitly thrown by business logic.
• Mapped to wsdl:fault in WSDL file
• Unmodeled – RuntimeException, represented as generic
SOAPFaultException
#40 JAX-WS Input/Output Processing
Use SOAP message handlers to pre/post process
messages and handle SOAP faults.
#40 JAX-WS Input/Output Processing
#41 JAX-WS Security
Specify Roles
#42 JAX-WS Large Files
Use W3C Message Transmission Optimization Mechanism
(MTOM) to handle large files.
#43 Deployment Classpath
• Are you pulling in third-party JAR files?
• Do these JAR files include Java EE annotated classes?
• Are you accidently deploying web services, MDBs etc.?
• Are you including container dependencies?
BAD!
#44 Threading
• Never create create threads.
• Container manages resources.
#44 Threading…
Thread Factory
#45 Distributed Caches
• Don’t treat @Singleton as a “global” singleton!
• Use JCache implementation (ex. HazelCast)
Java EE Server #1
app.war
SingletonBean
Java EE Server #2
app.war
SingletonBean
#46 Testing: Load
Load testing always at 100%?
Scenario:
• Message Driven Bean with a connection to a remote
resource.
• Standing pool size: 3
Oops!
#46 Testing Load (Continued…)
Oops, resource only leak as bean instances fluctuate!
0
5
10
15
20
25
30
35
1 2 3 4 5 6 7 8 9
Leak
Bean
Returning to standing pool size leaks resources.
#47 Testing: Integration
Use Arquillian:
#48 Java EE Tutorial Table of Contents
• What’s in Java EE?
• 918 pages
• TOC is a great summary
• 30+ pages
• Highlights just how much is
in EE
#49 There are no “small” applications
• Don’t fall into these traps:
• “It’s just a simple application”
• “It only needs to do…”
• “Code it up real quick…”
• EE Specification exists for a reason
• Multiple users
• Concurrency
• Multi-threading
• Transaction management
• External resources
• Messaging
#50 Start with an EE Server
• Because there are no “small” applications
• Start with an EE Server
Avoid filling yourWAR with
“EE Features”
because you are not using an EE server
• But Servers are “heavy-weight”?
• Payara
• WildFly
• TomEE
• Benefits
• “Light-weight”
• Regular updates
• Great online community support
Join Us!
https://javaee-guardians.io
Q&A

Weitere ähnliche Inhalte

Was ist angesagt?

Workshop Spring - Session 1 - L'offre Spring et les bases
Workshop Spring  - Session 1 - L'offre Spring et les basesWorkshop Spring  - Session 1 - L'offre Spring et les bases
Workshop Spring - Session 1 - L'offre Spring et les basesAntoine Rey
 
为啥别读HotSpot VM的源码(2012-03-03)
为啥别读HotSpot VM的源码(2012-03-03)为啥别读HotSpot VM的源码(2012-03-03)
为啥别读HotSpot VM的源码(2012-03-03)Kris Mok
 
Comparing Native Java REST API Frameworks - Seattle JUG 2022
Comparing Native Java REST API Frameworks - Seattle JUG 2022Comparing Native Java REST API Frameworks - Seattle JUG 2022
Comparing Native Java REST API Frameworks - Seattle JUG 2022Matt Raible
 
Introduction Ă  JPA (Java Persistence API )
Introduction Ă  JPA  (Java Persistence API )Introduction Ă  JPA  (Java Persistence API )
Introduction Ă  JPA (Java Persistence API )Daniel Rene FOUOMENE PEWO
 
Java EE no ambiente corporativo: primeiros passos WebLogic 12c
Java EE no ambiente corporativo: primeiros passos WebLogic 12cJava EE no ambiente corporativo: primeiros passos WebLogic 12c
Java EE no ambiente corporativo: primeiros passos WebLogic 12cBruno Borges
 
Introduction to Kafka with Spring Integration
Introduction to Kafka with Spring IntegrationIntroduction to Kafka with Spring Integration
Introduction to Kafka with Spring IntegrationBorislav Markov
 
SpringDataJPA - 스프링 캠프
SpringDataJPA - 스프링 캠프SpringDataJPA - 스프링 캠프
SpringDataJPA - 스프링 캠프Younghan Kim
 
도메인 주도 설계의 본질
도메인 주도 설계의 본질도메인 주도 설계의 본질
도메인 주도 설계의 본질Young-Ho Cho
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPACheng Ta Yeh
 
Dissecting the rabbit: RabbitMQ Internal Architecture
Dissecting the rabbit: RabbitMQ Internal ArchitectureDissecting the rabbit: RabbitMQ Internal Architecture
Dissecting the rabbit: RabbitMQ Internal ArchitectureAlvaro Videla
 
서버 성능에 대한 정의와 이해
서버 성능에 대한 정의와 이해서버 성능에 대한 정의와 이해
서버 성능에 대한 정의와 이해중선 곽
 
Exploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaExploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaCODE WHITE GmbH
 
Networking in Java with NIO and Netty
Networking in Java with NIO and NettyNetworking in Java with NIO and Netty
Networking in Java with NIO and NettyConstantine Slisenka
 
Oracle Client Failover - Under The Hood
Oracle Client Failover - Under The HoodOracle Client Failover - Under The Hood
Oracle Client Failover - Under The HoodLudovico Caldara
 
Modern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafModern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafLAY Leangsros
 
webservice scaling for newbie
webservice scaling for newbiewebservice scaling for newbie
webservice scaling for newbieDaeMyung Kang
 
How to get http query parameters in mule
How to get http query parameters in muleHow to get http query parameters in mule
How to get http query parameters in muleRamakrishna kapa
 

Was ist angesagt? (20)

Workshop Spring - Session 1 - L'offre Spring et les bases
Workshop Spring  - Session 1 - L'offre Spring et les basesWorkshop Spring  - Session 1 - L'offre Spring et les bases
Workshop Spring - Session 1 - L'offre Spring et les bases
 
为啥别读HotSpot VM的源码(2012-03-03)
为啥别读HotSpot VM的源码(2012-03-03)为啥别读HotSpot VM的源码(2012-03-03)
为啥别读HotSpot VM的源码(2012-03-03)
 
Comparing Native Java REST API Frameworks - Seattle JUG 2022
Comparing Native Java REST API Frameworks - Seattle JUG 2022Comparing Native Java REST API Frameworks - Seattle JUG 2022
Comparing Native Java REST API Frameworks - Seattle JUG 2022
 
Spring data jpa
Spring data jpaSpring data jpa
Spring data jpa
 
Introduction Ă  JPA (Java Persistence API )
Introduction Ă  JPA  (Java Persistence API )Introduction Ă  JPA  (Java Persistence API )
Introduction Ă  JPA (Java Persistence API )
 
Java EE no ambiente corporativo: primeiros passos WebLogic 12c
Java EE no ambiente corporativo: primeiros passos WebLogic 12cJava EE no ambiente corporativo: primeiros passos WebLogic 12c
Java EE no ambiente corporativo: primeiros passos WebLogic 12c
 
Introduction to Kafka with Spring Integration
Introduction to Kafka with Spring IntegrationIntroduction to Kafka with Spring Integration
Introduction to Kafka with Spring Integration
 
SpringDataJPA - 스프링 캠프
SpringDataJPA - 스프링 캠프SpringDataJPA - 스프링 캠프
SpringDataJPA - 스프링 캠프
 
Custom PrimeFaces components
Custom PrimeFaces componentsCustom PrimeFaces components
Custom PrimeFaces components
 
도메인 주도 설계의 본질
도메인 주도 설계의 본질도메인 주도 설계의 본질
도메인 주도 설계의 본질
 
Spring Data JPA
Spring Data JPASpring Data JPA
Spring Data JPA
 
Dissecting the rabbit: RabbitMQ Internal Architecture
Dissecting the rabbit: RabbitMQ Internal ArchitectureDissecting the rabbit: RabbitMQ Internal Architecture
Dissecting the rabbit: RabbitMQ Internal Architecture
 
서버 성능에 대한 정의와 이해
서버 성능에 대한 정의와 이해서버 성능에 대한 정의와 이해
서버 성능에 대한 정의와 이해
 
Exploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in JavaExploiting Deserialization Vulnerabilities in Java
Exploiting Deserialization Vulnerabilities in Java
 
Networking in Java with NIO and Netty
Networking in Java with NIO and NettyNetworking in Java with NIO and Netty
Networking in Java with NIO and Netty
 
Oracle Client Failover - Under The Hood
Oracle Client Failover - Under The HoodOracle Client Failover - Under The Hood
Oracle Client Failover - Under The Hood
 
Modern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and ThymeleafModern Java web applications with Spring Boot and Thymeleaf
Modern Java web applications with Spring Boot and Thymeleaf
 
Spring Core
Spring CoreSpring Core
Spring Core
 
webservice scaling for newbie
webservice scaling for newbiewebservice scaling for newbie
webservice scaling for newbie
 
How to get http query parameters in mule
How to get http query parameters in muleHow to get http query parameters in mule
How to get http query parameters in mule
 

Ähnlich wie Top 50 java ee 7 best practices [con5669]

Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best PracticesDavid Keener
 
Memcached-инъекции - они существуют и работают, Иван Новиков (ONsec)
Memcached-инъекции - они существуют и работают, Иван Новиков (ONsec)Memcached-инъекции - они существуют и работают, Иван Новиков (ONsec)
Memcached-инъекции - они существуют и работают, Иван Новиков (ONsec)Ontico
 
Byte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in JavaByte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in JavaAlex Moskvin
 
Oracle Fuson Middleware Diagnostics, Performance and Troubleshoot
Oracle Fuson Middleware Diagnostics, Performance and TroubleshootOracle Fuson Middleware Diagnostics, Performance and Troubleshoot
Oracle Fuson Middleware Diagnostics, Performance and TroubleshootMichel Schildmeijer
 
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...Malin Weiss
 
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...Speedment, Inc.
 
mjprof: Monadic approach for JVM profiling
mjprof: Monadic approach for JVM profilingmjprof: Monadic approach for JVM profiling
mjprof: Monadic approach for JVM profilingHaim Yadid
 
The Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans TechnologyThe Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans TechnologySimon Ritter
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agilityelliando dias
 
BTV PHP - Building Fast Websites
BTV PHP - Building Fast WebsitesBTV PHP - Building Fast Websites
BTV PHP - Building Fast WebsitesJonathan Klein
 
Fundamentals of java --- version 2
Fundamentals of java --- version 2Fundamentals of java --- version 2
Fundamentals of java --- version 2Uday Sharma
 
How to generate customized java 8 code from your database
How to generate customized java 8 code from your databaseHow to generate customized java 8 code from your database
How to generate customized java 8 code from your databaseSpeedment, Inc.
 
Silicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSilicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSpeedment, Inc.
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionMazenetsolution
 
Fun with EJB 3.1 and Open EJB
Fun with EJB 3.1 and Open EJBFun with EJB 3.1 and Open EJB
Fun with EJB 3.1 and Open EJBArun Gupta
 
NYJavaSIG - Big Data Microservices w/ Speedment
NYJavaSIG - Big Data Microservices w/ SpeedmentNYJavaSIG - Big Data Microservices w/ Speedment
NYJavaSIG - Big Data Microservices w/ SpeedmentSpeedment, Inc.
 
Overview of Java EE 6 by Roberto Chinnici at SFJUG
Overview of Java EE 6 by Roberto Chinnici at SFJUGOverview of Java EE 6 by Roberto Chinnici at SFJUG
Overview of Java EE 6 by Roberto Chinnici at SFJUGMarakana Inc.
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersJonathan Levin
 

Ähnlich wie Top 50 java ee 7 best practices [con5669] (20)

Rails Tips and Best Practices
Rails Tips and Best PracticesRails Tips and Best Practices
Rails Tips and Best Practices
 
Memcached-инъекции - они существуют и работают, Иван Новиков (ONsec)
Memcached-инъекции - они существуют и работают, Иван Новиков (ONsec)Memcached-инъекции - они существуют и работают, Иван Новиков (ONsec)
Memcached-инъекции - они существуют и работают, Иван Новиков (ONsec)
 
Byte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in JavaByte code manipulation and instrumentalization in Java
Byte code manipulation and instrumentalization in Java
 
Oracle Fuson Middleware Diagnostics, Performance and Troubleshoot
Oracle Fuson Middleware Diagnostics, Performance and TroubleshootOracle Fuson Middleware Diagnostics, Performance and Troubleshoot
Oracle Fuson Middleware Diagnostics, Performance and Troubleshoot
 
Loom promises: be there!
Loom promises: be there!Loom promises: be there!
Loom promises: be there!
 
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
How to JavaOne 2016 - Generate Customized Java 8 Code from Your Database [TUT...
 
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
JavaOne2016 - How to Generate Customized Java 8 Code from Your Database [TUT4...
 
mjprof: Monadic approach for JVM profiling
mjprof: Monadic approach for JVM profilingmjprof: Monadic approach for JVM profiling
mjprof: Monadic approach for JVM profiling
 
The Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans TechnologyThe Latest in Enterprise JavaBeans Technology
The Latest in Enterprise JavaBeans Technology
 
Polyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better AgilityPolyglot and Poly-paradigm Programming for Better Agility
Polyglot and Poly-paradigm Programming for Better Agility
 
BTV PHP - Building Fast Websites
BTV PHP - Building Fast WebsitesBTV PHP - Building Fast Websites
BTV PHP - Building Fast Websites
 
Fundamentals of java --- version 2
Fundamentals of java --- version 2Fundamentals of java --- version 2
Fundamentals of java --- version 2
 
How to generate customized java 8 code from your database
How to generate customized java 8 code from your databaseHow to generate customized java 8 code from your database
How to generate customized java 8 code from your database
 
Silicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your databaseSilicon Valley JUG - How to generate customized java 8 code from your database
Silicon Valley JUG - How to generate customized java 8 code from your database
 
JavaOne_2010
JavaOne_2010JavaOne_2010
JavaOne_2010
 
Java- JDBC- Mazenet Solution
Java- JDBC- Mazenet SolutionJava- JDBC- Mazenet Solution
Java- JDBC- Mazenet Solution
 
Fun with EJB 3.1 and Open EJB
Fun with EJB 3.1 and Open EJBFun with EJB 3.1 and Open EJB
Fun with EJB 3.1 and Open EJB
 
NYJavaSIG - Big Data Microservices w/ Speedment
NYJavaSIG - Big Data Microservices w/ SpeedmentNYJavaSIG - Big Data Microservices w/ Speedment
NYJavaSIG - Big Data Microservices w/ Speedment
 
Overview of Java EE 6 by Roberto Chinnici at SFJUG
Overview of Java EE 6 by Roberto Chinnici at SFJUGOverview of Java EE 6 by Roberto Chinnici at SFJUG
Overview of Java EE 6 by Roberto Chinnici at SFJUG
 
Scaling MySQL Strategies for Developers
Scaling MySQL Strategies for DevelopersScaling MySQL Strategies for Developers
Scaling MySQL Strategies for Developers
 

Mehr von Ryan Cuprak

Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)Ryan Cuprak
 
DIY Home Weather Station (Devoxx Poland 2023)
DIY Home Weather Station (Devoxx Poland 2023)DIY Home Weather Station (Devoxx Poland 2023)
DIY Home Weather Station (Devoxx Poland 2023)Ryan Cuprak
 
Why jakarta ee matters (ConFoo 2021)
Why jakarta ee matters (ConFoo 2021)Why jakarta ee matters (ConFoo 2021)
Why jakarta ee matters (ConFoo 2021)Ryan Cuprak
 
Polygot Java EE on the GraalVM
Polygot Java EE on the GraalVMPolygot Java EE on the GraalVM
Polygot Java EE on the GraalVMRyan Cuprak
 
Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Ryan Cuprak
 
Node.js Development with Apache NetBeans
Node.js Development with Apache NetBeansNode.js Development with Apache NetBeans
Node.js Development with Apache NetBeansRyan Cuprak
 
Preparing for java 9 modules upload
Preparing for java 9 modules uploadPreparing for java 9 modules upload
Preparing for java 9 modules uploadRyan Cuprak
 
Faster Java EE Builds with Gradle
Faster Java EE Builds with GradleFaster Java EE Builds with Gradle
Faster Java EE Builds with GradleRyan Cuprak
 
Faster Java EE Builds with Gradle
Faster Java EE Builds with GradleFaster Java EE Builds with Gradle
Faster Java EE Builds with GradleRyan Cuprak
 
Containerless in the Cloud with AWS Lambda
Containerless in the Cloud with AWS LambdaContainerless in the Cloud with AWS Lambda
Containerless in the Cloud with AWS LambdaRyan Cuprak
 
Java EE 8 Update
Java EE 8 UpdateJava EE 8 Update
Java EE 8 UpdateRyan Cuprak
 
Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)Ryan Cuprak
 
Faster java ee builds with gradle [con4921]
Faster java ee builds with gradle [con4921]Faster java ee builds with gradle [con4921]
Faster java ee builds with gradle [con4921]Ryan Cuprak
 
Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]Ryan Cuprak
 
Jms deep dive [con4864]
Jms deep dive [con4864]Jms deep dive [con4864]
Jms deep dive [con4864]Ryan Cuprak
 
Developing in the Cloud
Developing in the CloudDeveloping in the Cloud
Developing in the CloudRyan Cuprak
 
Combining R With Java For Data Analysis (Devoxx UK 2015 Session)
Combining R With Java For Data Analysis (Devoxx UK 2015 Session)Combining R With Java For Data Analysis (Devoxx UK 2015 Session)
Combining R With Java For Data Analysis (Devoxx UK 2015 Session)Ryan Cuprak
 
Hybrid Mobile Development with Apache Cordova and
Hybrid Mobile Development with Apache Cordova and Hybrid Mobile Development with Apache Cordova and
Hybrid Mobile Development with Apache Cordova and Ryan Cuprak
 
JavaFX Versus HTML5 - JavaOne 2014
JavaFX Versus HTML5 - JavaOne 2014JavaFX Versus HTML5 - JavaOne 2014
JavaFX Versus HTML5 - JavaOne 2014Ryan Cuprak
 

Mehr von Ryan Cuprak (20)

Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)Jakarta EE Test Strategies (2022)
Jakarta EE Test Strategies (2022)
 
DIY Home Weather Station (Devoxx Poland 2023)
DIY Home Weather Station (Devoxx Poland 2023)DIY Home Weather Station (Devoxx Poland 2023)
DIY Home Weather Station (Devoxx Poland 2023)
 
Why jakarta ee matters (ConFoo 2021)
Why jakarta ee matters (ConFoo 2021)Why jakarta ee matters (ConFoo 2021)
Why jakarta ee matters (ConFoo 2021)
 
Polygot Java EE on the GraalVM
Polygot Java EE on the GraalVMPolygot Java EE on the GraalVM
Polygot Java EE on the GraalVM
 
Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)Exploring Java Heap Dumps (Oracle Code One 2018)
Exploring Java Heap Dumps (Oracle Code One 2018)
 
Node.js Development with Apache NetBeans
Node.js Development with Apache NetBeansNode.js Development with Apache NetBeans
Node.js Development with Apache NetBeans
 
Preparing for java 9 modules upload
Preparing for java 9 modules uploadPreparing for java 9 modules upload
Preparing for java 9 modules upload
 
Faster Java EE Builds with Gradle
Faster Java EE Builds with GradleFaster Java EE Builds with Gradle
Faster Java EE Builds with Gradle
 
Java EE 8
Java EE 8Java EE 8
Java EE 8
 
Faster Java EE Builds with Gradle
Faster Java EE Builds with GradleFaster Java EE Builds with Gradle
Faster Java EE Builds with Gradle
 
Containerless in the Cloud with AWS Lambda
Containerless in the Cloud with AWS LambdaContainerless in the Cloud with AWS Lambda
Containerless in the Cloud with AWS Lambda
 
Java EE 8 Update
Java EE 8 UpdateJava EE 8 Update
Java EE 8 Update
 
Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)Batching and Java EE (jdk.io)
Batching and Java EE (jdk.io)
 
Faster java ee builds with gradle [con4921]
Faster java ee builds with gradle [con4921]Faster java ee builds with gradle [con4921]
Faster java ee builds with gradle [con4921]
 
Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]Java script nirvana in netbeans [con5679]
Java script nirvana in netbeans [con5679]
 
Jms deep dive [con4864]
Jms deep dive [con4864]Jms deep dive [con4864]
Jms deep dive [con4864]
 
Developing in the Cloud
Developing in the CloudDeveloping in the Cloud
Developing in the Cloud
 
Combining R With Java For Data Analysis (Devoxx UK 2015 Session)
Combining R With Java For Data Analysis (Devoxx UK 2015 Session)Combining R With Java For Data Analysis (Devoxx UK 2015 Session)
Combining R With Java For Data Analysis (Devoxx UK 2015 Session)
 
Hybrid Mobile Development with Apache Cordova and
Hybrid Mobile Development with Apache Cordova and Hybrid Mobile Development with Apache Cordova and
Hybrid Mobile Development with Apache Cordova and
 
JavaFX Versus HTML5 - JavaOne 2014
JavaFX Versus HTML5 - JavaOne 2014JavaFX Versus HTML5 - JavaOne 2014
JavaFX Versus HTML5 - JavaOne 2014
 

KĂźrzlich hochgeladen

The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfkalichargn70th171
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software DevelopersVinodh Ram
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...harshavardhanraghave
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackVICTOR MAESTRE RAMIREZ
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfjoe51371421
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationkaushalgiri8080
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about usDynamic Netsoft
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number SystemsJheuzeDellosa
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Intelisync
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxComplianceQuest1
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantAxelRicardoTrocheRiq
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...gurkirankumar98700
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityNeo4j
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfkalichargn70th171
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEOrtus Solutions, Corp
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideChristina Lin
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 

KĂźrzlich hochgeladen (20)

The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdfThe Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
The Essentials of Digital Experience Monitoring_ A Comprehensive Guide.pdf
 
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...Call Girls In Mukherjee Nagar 📱  9999965857  🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
Call Girls In Mukherjee Nagar 📱 9999965857 🤩 Delhi 🫦 HOT AND SEXY VVIP 🍎 SE...
 
Professional Resume Template for Software Developers
Professional Resume Template for Software DevelopersProfessional Resume Template for Software Developers
Professional Resume Template for Software Developers
 
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
Reassessing the Bedrock of Clinical Function Models: An Examination of Large ...
 
Cloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStackCloud Management Software Platforms: OpenStack
Cloud Management Software Platforms: OpenStack
 
why an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdfwhy an Opensea Clone Script might be your perfect match.pdf
why an Opensea Clone Script might be your perfect match.pdf
 
Project Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanationProject Based Learning (A.I).pptx detail explanation
Project Based Learning (A.I).pptx detail explanation
 
DNT_Corporate presentation know about us
DNT_Corporate presentation know about usDNT_Corporate presentation know about us
DNT_Corporate presentation know about us
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
What is Binary Language? Computer Number Systems
What is Binary Language?  Computer Number SystemsWhat is Binary Language?  Computer Number Systems
What is Binary Language? Computer Number Systems
 
Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)Introduction to Decentralized Applications (dApps)
Introduction to Decentralized Applications (dApps)
 
A Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docxA Secure and Reliable Document Management System is Essential.docx
A Secure and Reliable Document Management System is Essential.docx
 
Salesforce Certified Field Service Consultant
Salesforce Certified Field Service ConsultantSalesforce Certified Field Service Consultant
Salesforce Certified Field Service Consultant
 
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
(Genuine) Escort Service Lucknow | Starting ₹,5K To @25k with A/C 🧑🏽‍❤️‍🧑🏻 89...
 
EY_Graph Database Powered Sustainability
EY_Graph Database Powered SustainabilityEY_Graph Database Powered Sustainability
EY_Graph Database Powered Sustainability
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdfThe Ultimate Test Automation Guide_ Best Practices and Tips.pdf
The Ultimate Test Automation Guide_ Best Practices and Tips.pdf
 
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASEBATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
BATTLEFIELD ORM: TIPS, TACTICS AND STRATEGIES FOR CONQUERING YOUR DATABASE
 
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop SlideBuilding Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
Building Real-Time Data Pipelines: Stream & Batch Processing workshop Slide
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 

Top 50 java ee 7 best practices [con5669]

  • 1. TOP 50 JAVA EE 7 BEST PRACTICES Ryan Cuprak Michael Remijan
  • 2. About Us Ryan • @ctjava • rcuprak@gmail.com • http://www.cuprak.info • https://www.linkedin.com/in/rcuprak Michael • @mjremijan • mjremijan@yahoo.com • http://mjremijan.blogspot.com • http://linkedin.com/in/mjremijan
  • 3. EJB 3 In Action 2nd Edition Updated For • EE 7 • EJB 3.2
  • 4. Java EE 7 Concurrency Utilities Batch Applications Java API for JSON Java API for WebSocket JSF 2.2 JSX-WS 2.2 JAX-RS 2 EL 3 Servlet 3.1 Common Annotations 1.2 Interceptors 1.2 CDI 1.1 Managed Beans 1.0 EJB 3.2 Connector 1.7 JPA 2.1 JTA 1.2 JMS 2 JSP 2.3 JAXB
  • 5. #1 JAX-RS: API Versioning Version your JAX-RS with one of two approaches: 1. URL http://ctjava.org/v2/meetings http://ctjava.org/v1/meetngs 2. Media Content or Header Param curl -H "Content-Type:application/srv-v4+json” … Return HTTP Status Codes for services moved/changed: • 301 Moved Permanently • 302 Found
  • 6. #1 JAX-RS: API Versioning (Continued…) Approach 1: URL Approach 2: Media Types
  • 7. #1 JAX-RS: API Versioning (Continued…) Service Moved Permanently
  • 8. #2 JAX-RS: Error Handling Provide ExceptionMappers to handle and process errors.
  • 9. #2 JAX-RS: Error Handling (Continued…) HTML content is hardly a friendly response for an API!
  • 10. #2 JAX-RS: Error Handling (Continued…)
  • 11. #3 JAX-RS: Caching Tell clients to cache data!
  • 12. #4 JAX-RS + Bean Validation Use Bean Validation to check data.
  • 13. #5 JAX-RS: Compress Responses Use gzip compression for responses to reduce bandwidth.
  • 14. #6 Securing RESTful Services • Use tokens with RESTful Web Services (OWASP). • Leverage JASPIC to setup JAAS environment.
  • 15. #7 JAX-RS + EJB • Use @Stateless and @Path together • Pooled, thread safe, monitored
  • 16. #7 JAX-RS + EJB (Continued…) • http://localhost:4848/monitoring/domain/server/applications/WebApp lication1/StatelessResource/bean-methods/getText[.json]
  • 17. #8 JAX-RS: Asynchronous API Gateway • Gateway calls multiple microservices asynchronously • Combines results into a DTO
  • 18. #8 JAX-RS: Async…(Continued…) • Gateway calls multiple microservices asynchronously • Combines results into a DTO
  • 19. #9 JPA: Pagination Use pagination for potential large result sets.
  • 20. #9 JPA: Pagination (Continued…)
  • 21. #10 JPA: Lazy Relationships Avoid unnecessary queries – use Fetch on Lazy relationships.
  • 22. #10 JPA: Lazy Relationships (Continued…) 1. SELECT MEETINGID, DATE, MEETINGABSTRACT, TITLE FROM MEETING WHERE (MEETINGID = ?) 2. SELECT t1.SPEAKERID, t1.BIOGRAPHY, t1.FIRSTNAME, t1.LASTNAME FROM meeting_speakers t0, SPEAKER t1 WHERE ((t0.meetingid = ?) AND (t1.SPEAKERID = t0.speakerid))
  • 23. #10 JPA: Lazy Relationships (Continued…) 1. SELECT t1.MEETINGID, t1.DATE, t1.MEETINGABSTRACT, t1.TITLE, t0.SPEAKERID, t0.BIOGRAPHY, t0.FIRSTNAME, t0.LASTNAME FROM SPEAKER t0, meeting_speakers t2, MEETING t1 WHERE ((t1.MEETINGID = ?) AND ((t2.meetingid = t1.MEETINGID) AND (t0.SPEAKERID = t2.speakerid))) 1 Query Not TWO!
  • 24. #11 JPA: Cascade • Don’t forget cascade levels to handle child data • cascade=ALL is equivalent to cascade={PERSIST, MERGE, REMOVE, REFRESH, DETACH}
  • 25. #12 JPA: Entity Graphs
  • 26. #13 JPA + DAO Put CRUD operations into DAOs.
  • 27. #14 JPA: hashcode() & equals() The equals and hashcode are required for: • Entity is added to a collection • When re-attaching entities to a new persistence context. Important points: • Do not use generated identifiers • Use business key equality
  • 28. #14 JPA: hashcode() & equals() Continued…
  • 29. #15 JPA: Optimistic Locking • Don’t roll your own • Use @Version for optimistic locking: Integer
  • 30. #15 JPA: Optimistic Locking (Continued…) • Timestamp
  • 31. #16 JPA: Pessimistic Locking • PESSIMISTIC_READ, PESSIMISTIC_WRITE • Lock timeout HINT
  • 32. #17 JPA: Mapping Inheritance • Inheritance can have a big impact upon performance. • Three approaches: • Single table • Joined-tables • Table-per-class • Denormalize for better performance
  • 33. #18 JPA L2 Cache JPA 2 introduced the L2 Cache, use this cache for: • Entities that are frequently read • Entities that are modified infrequently • Not critical if stale • L2 cache can consume large amounts of memory • ALL • NONE • ENABLE_SELECTIVE • DISABLE_SELECTIVE Are you using a default setting?
  • 34. #18 JPA L2 Cache (Continued…) Mark entity for L2 cache Bypass L2 cache
  • 35. #19 JPA: Persisting ENUM • ENUM is a good case of converting data types • Use a @Converter
  • 36. #19 JPA: Persisting ENUM (Continued…) • @Converter • AttributeConverter<X,Y> • X is my application, Y is the database
  • 37. #20 EJB: Transaction Handling • EJBs exist to handle transactions. Keep them at the right layer • Don’t ignore transactions. Default: REQUIRED • JAX-RS endpoints, database reads & performance
  • 38. #21 EJB: Stateless Thread Safety • Stateless beans are a pooled, managed resource • Pools configurable by the application server
  • 39. #22 EJB: Asynchronous • @Asynchronous runs in container-managed thread • Return Future<> to get results later • Ideal for wrapping JAX-RS calls • Good way to avoid any of your own threading
  • 40. #23 EJB: Security • Use declarative security and let the container handle it • Avoid programmatic security • EE servers trust principal/roles passed between containers.
  • 41. #23 EJB: Security (Continued…) • EE Configuration • web.xml • @DeclaredRoles • @RolesAllowed • Custom Configuration • EE Server Realm • glassfish-web.xml
  • 42. #24 EJB: Avoid Lengthy Initialization Don’t abuse startup – @PostConconstruct delays You delay initialization of the container!
  • 43. #24 EJB: Avoid Lengthy Initialization
  • 44. #25 CDI: Observers • In-memory event processing • Very “reactive” • Decouple work to be done, avoids unnecessary dependencies • Create an event to fire
  • 45. #25 CDI: Observers (Continued…) • Fire the event • Observers process the event
  • 46. #26 CDI: Producer + Cache • Use a producer to customize creation of an object • Producer method is always called, so cache the instance
  • 47. #27 CDI: Interceptors • Limit to cross-cutting concerns • Do not use to change business logic • Create an annotation
  • 48. #27 CDI: Interceptors • Create the interceptor
  • 49. #27 CDI: Interceptors • Apply the interceptor
  • 50. #28 CDI: Decorators • Use to enhance or decorate existing code • Open-close principle • Do not use for cross-cutting concerns
  • 51. #28 CDI: Decorators (Continued…) • /WEB-INF/beans.xml • /META-INF/beans.xml
  • 52. #29 CDI: Transactions Java EE introduced @Transactional for non-EJBs. Pro: Easier to utilize transactions outside of EJB. Con: Mixes layers – transactions & rest etc.
  • 53. #30 CDI: Bean Discovery • Java EE 7 CDI is enabled by default. • beans.xml is no longer required as in EE 6 • Bean discovery mode: • Annotated – only annotated classes • All – includes beans that are not annotated • None – CDI disabled • Default mode is ‘annotated’
  • 54. #31 Batch: Java EE not SE • Think Java EE for batch, not SE • Batch API • Cron like schedule on EJB methods • META-INF/batch-jobs/processInvoices.xml
  • 55. #32: Batch Best Practices • Package/deploy batch jobs separately • Implement logic to cleanup old jobs • Implement logic for auto-restart • Test restart and checkpoint logic • Configure database to store jobs • Configure thread pool for batch jobs • Only invoke batch jobs from logic that is secured (@Role etc.)
  • 56. #33 JAXB Primitive Data Types anySimpleType decimal integer long int short byte float double nonPositiveInteger negativeInteger nonNegativeInteger unsigneLong positiveInteger unsignedInt unsignedInt unsignedByte
  • 57. #34 JAXB: Date & Time Representation • Use XMLGregorianCalendar for dates • Avoid java.util.Date and java.util.Calendar • XMLGregorianCalendar • Handles long fractions of seconds – important to .NET interoperability
  • 58. #35 JAXB: Annotate Don’t let JAXB generate everything!
  • 59. #36 JAX-WS: RPC vs. Document • Four different possibilities: • RPC/Literal • RPC/Encoded • Document/Literal • Document/Encoded • Encoded is not supported by WS-I • Default and most commonly used is Document/Literal • Use Document/Literal • RPC/Literal: • Limited to basic XSD types • WSDL will not include types section to constrain parameters
  • 60. #37 JAX-WS: JAXB Gotcha • JAXB will serialize an entire object graph. Oops! Use either: • DTO – Data Transfer Object • @XmlTransient
  • 61. #38 JAX-WS Interoperable Services • Design service starting with the WSDL • Create data types using XSD • Keep data types SIMPLE • Avoid xsd:anyType • Avoid sending Null values • Use byte[] instead of String when character encoding is unknown
  • 62. #39 SOAP Faults • Types of SOAP faults: • Modeled – exception explicitly thrown by business logic. • Mapped to wsdl:fault in WSDL file • Unmodeled – RuntimeException, represented as generic SOAPFaultException
  • 63. #40 JAX-WS Input/Output Processing Use SOAP message handlers to pre/post process messages and handle SOAP faults.
  • 66. #42 JAX-WS Large Files Use W3C Message Transmission Optimization Mechanism (MTOM) to handle large files.
  • 67. #43 Deployment Classpath • Are you pulling in third-party JAR files? • Do these JAR files include Java EE annotated classes? • Are you accidently deploying web services, MDBs etc.? • Are you including container dependencies? BAD!
  • 68. #44 Threading • Never create create threads. • Container manages resources.
  • 70. #45 Distributed Caches • Don’t treat @Singleton as a “global” singleton! • Use JCache implementation (ex. HazelCast) Java EE Server #1 app.war SingletonBean Java EE Server #2 app.war SingletonBean
  • 71. #46 Testing: Load Load testing always at 100%? Scenario: • Message Driven Bean with a connection to a remote resource. • Standing pool size: 3 Oops!
  • 72. #46 Testing Load (Continued…) Oops, resource only leak as bean instances fluctuate! 0 5 10 15 20 25 30 35 1 2 3 4 5 6 7 8 9 Leak Bean Returning to standing pool size leaks resources.
  • 74. #48 Java EE Tutorial Table of Contents • What’s in Java EE? • 918 pages • TOC is a great summary • 30+ pages • Highlights just how much is in EE
  • 75. #49 There are no “small” applications • Don’t fall into these traps: • “It’s just a simple application” • “It only needs to do…” • “Code it up real quick…” • EE Specification exists for a reason • Multiple users • Concurrency • Multi-threading • Transaction management • External resources • Messaging
  • 76. #50 Start with an EE Server • Because there are no “small” applications • Start with an EE Server Avoid filling yourWAR with “EE Features” because you are not using an EE server • But Servers are “heavy-weight”? • Payara • WildFly • TomEE • Benefits • “Light-weight” • Regular updates • Great online community support
  • 78. Q&A

Hinweis der Redaktion

  1. [Ryan] - Welcome to the Top 50 Java Best Practices
  2. I am Ryan, this is Michael,