Introduction to Session beans. EJB - continued

Similar documents
Object-Relational Mapping is NOT serialization! You can perform queries on each field!

jar command Java Archive inherits from tar : Tape Archive commands: jar cvf filename jar tvf filename jar xvf filename java jar filename.

Introduction to Session beans EJB 3.0

Module 8 The Java Persistence API

International Journal of Advance Research in Engineering, Science & Technology HIBERNATE FRAMEWORK FOR ENTERPRISE APPLICATION

Injection Of Entitymanager

Step By Step Guideline for Building & Running HelloWorld Hibernate Application

JPA Entities. Course Multi Tier Business Applications with Java EE. Prof. Dr. Eric Dubuis Berner Fachhochschule Biel. Berner Fachhochschule

EJB 3 Entities. Course Multi Tier Business Applications with Java EE. Prof. Dr. Eric Dubuis Berner Fachhochschule Biel. Berner Fachhochschule

Fast Track to EJB 3.0 and the JPA Using JBoss

Installing MySQL. Hibernate: Setup, Use, and Mapping file. Setup Hibernate in IDE. Starting WAMP server. phpmyadmin web console

Chapter 3. Harnessing Hibernate

Async EJB calls, Java Persistence API and XML. Carl Nettelblad

Lightweight J2EE Framework

Table of Contents EJB 3.1 and JPA 2

Entity LifeCycle Callback Methods Srikanth Technologies Page : 1

Entities are classes that need to be persisted, usually in a relational database. In this chapter we cover the following topics:

Get Back in Control of your SQL

Introduction to JPA. Fabio Falcinelli

1 st Step. Prepare the class to be persistent:

Testing Transactions BMT

Practice Test. Oracle 1z Java Enterprise Edition 5 Business Component Developer Certified Professional Upgrade Exam. Version: 14.

Exam Questions 1Z0-895

Developing container managed persistence with JPA

Deccansoft Software Services. J2EE Syllabus

Java Object/Relational Persistence with Hibernate. David Lucek 11 Jan 2005

Java Persistence API (JPA) Entities

Table of Contents. I. Pre-Requisites A. Audience B. Pre-Requisites. II. Introduction A. The Problem B. Overview C. History

Hibernate Overview. By Khader Shaik

Model Driven Architecture with Java

GET BACK IN CONTROL OF YOUR SQL. Lukas Eder

Web Application Development Using JEE, Enterprise JavaBeans and JPA

BEAWebLogic Server. Programming WebLogic Enterprise JavaBeans, Version 3.0

Java EE 7: Back-End Server Application Development

WHAT IS EJB. Security. life cycle management.

Oracle EXAM - 1Z Java EE 6 Enterprise JavaBeans Developer Certified Expert Exam. Buy Full Product.

Web Application Development Using JEE, Enterprise JavaBeans and JPA

Java- EE Web Application Development with Enterprise JavaBeans and Web Services

Chapter 1 Introducing EJB 1. What is Java EE Introduction to EJB...5 Need of EJB...6 Types of Enterprise Beans...7

Unit 6 Hibernate. List the advantages of hibernate over JDBC

CO Java EE 7: Back-End Server Application Development

SUN Sun Cert Bus Component Developer Java EE Platform 5, Upgrade. Download Full Version :

"Charting the Course... Mastering EJB 3.0 Applications. Course Summary

The Details of Writing Enterprise Java Beans

NetBeans IDE Field Guide

Dynamic DAO Implementation

Generating A Hibernate Mapping File And Java Classes From The Sql Schema

Webservice Inheritance

PostgreSQL From a Java Enterprise Point of View

EJB ENTERPRISE JAVA BEANS INTRODUCTION TO ENTERPRISE JAVA BEANS, JAVA'S SERVER SIDE COMPONENT TECHNOLOGY. EJB Enterprise Java

JPA and CDI JPA and EJB

UNIT-III EJB APPLICATIONS

ADVANCED JAVA TRAINING IN BANGALORE

Topics in Enterprise Information Management

Java EE Application Assembly & Deployment Packaging Applications, Java EE modules. Model View Controller (MVC)2 Architecture & Packaging EJB Module

Chapter 2. Introduction to Mapping

Enterprise JavaBeans, Version 3 (EJB3) Programming

JAVA COURSES. Empowering Innovation. DN InfoTech Pvt. Ltd. H-151, Sector 63, Noida, UP

Migrating traditional Java EE applications to mobile

Dynamic Datasource Routing

SDN Community Contribution

Call: JSP Spring Hibernate Webservice Course Content:35-40hours Course Outline

8. Component Software

Implementing a Web Service p. 110 Implementing a Web Service Client p. 114 Summary p. 117 Introduction to Entity Beans p. 119 Persistence Concepts p.

The dialog boxes Import Database Schema, Import Hibernate Mappings and Import Entity EJBs are used to create annotated Java classes and persistence.

1Z Oracle. Java Enterprise Edition 5 Business Component Developer Certified Professional Upgrade

object/relational persistence What is persistence? 5

<Insert Picture Here> Productive JavaEE 5.0 Development

Java EE Architecture, Part Three. Java EE architecture, part three 1(57)

J2EE Development. Course Detail: Audience. Duration. Course Abstract. Course Objectives. Course Topics. Class Format.

The Good, the Bad and the Ugly

Java EE Architecture, Part Three. Java EE architecture, part three 1(69)

Hibernate Interview Questions

JVA-163. Enterprise JavaBeans

Pro JPA 2. Mastering the Java Persistence API. Apress* Mike Keith and Merrick Schnicariol

Enterprise JavaBeans. Layer:08. Persistence

Spring & Hibernate. Knowledge of database. And basic Knowledge of web application development. Module 1: Spring Basics

Enterprise JavaBeans. Layer:03. Session

Java Enterprise Edition

Course Content for Java J2EE

Stateless Session Bean

Chapter 6 Enterprise Java Beans

HIBERNATE MOCK TEST HIBERNATE MOCK TEST IV

Java EE 6: Develop Business Components with JMS & EJBs

Practical EJB 3.0. Bill Burke JBoss Fellow Red Hat. Easier for application and framework developers. Professional Open Source

~ Ian Hunneybell: CBSD Revision Notes (07/06/2006) ~

ENTERPRISE JAVABEANS TM (EJB TM ) 3.1 TECHNOLOGY

Table of Contents - Fast Track to Hibernate 3

Apache OpenJPA User's Guide

Week 2 Unit 1: Introduction and First Steps with EJB. January, 2015

WAS V7 Application Development

Stateful Session Beans

Object Persistence and Object-Relational Mapping. James Brucker

Fast Track to Spring 3 and Spring MVC / Web Flow

Leverage Rational Application Developer v8 to develop Java EE6 application and test with WebSphere Application Server v8

Enterprise JavaBeans 3.1

Apache OpenJPA User's Guide

EJB 2.1 CMP EntityBeans (CMP2)

Enterprise JavaBeans EJB component types

Web Application Development Using Spring, Hibernate and JPA

Transcription:

Introduction to Session beans EJB - continued

Local Interface /** * This is the HelloBean local interface. * * This interface is what local clients operate * on when they interact with EJB local objects. * The container vendor will implement this * interface; the implemented object is the * EJB local object, which delegates invocations * to the actual bean. */ public interface HelloLocal extends javax.ejb.ejblocalobject { /** * The one method - hello - returns a greeting to the client. */ public String hello(); May throw EJBException instead of RemoteException

Local Home Interface /** * This is the home interface for HelloBean. This interface * is implemented by the EJB Server s tools - the * implemented object is called the Home Object, and serves * as a factory for EJB Objects. * * One create() method is in this Home Interface, which * corresponds to the ejbcreate() method in HelloBean. */ public interface HelloLocalHome extends javax.ejb.ejblocalhome { /* * This method creates the EJB Object. * * @return The newly created EJB Object. */ HelloLocal create() throws javax.ejb.createexception;

Local Client Object ref = jndicontext.lookup( HelloHome"); HelloHome home = (HelloHome) PortableRemoteObject.narrow(ref,HelloHome.class); HelloHome cabin_1 = home.create(); HelloLocalHome home = (HelloLocalHome ) jndicontext.lookup( java:comp/env/ejb/ HelloLocalHome "); HelloLocalHome cabin_1 = home.create(); We looked up a bean in java:comp/env/ejb. This is the JNDI location that the EJB specification recommends (but does not require) you put beans that are referenced from other beans.

Bean Implementation EJB 3.0 ============================================================== package examples.session.stateless; import javax.ejb.local; import javax.ejb.stateless; @Stateless @Local(Hello.class) public class HelloBean implements Hello { public String hello() { System.out.println( hello() ); return Hello, World! ; enterprise bean instance

3.0 Packaging

3.0 Lifecycle

Passivation

Activation

Managing the lifecycle 3.0 @Stateful public class MyBean { @PrePassivate public void passivate() { <close socket connections, etc...>... @PostActivate public void activate() { <open socket connections, etc...>...

Installing a Derby DB

Derby quick installation download Derby from http://db.apache.org/derby/ and unzip it in a shell, set DERBY_HOME and execute setembeddedcp DERBY_HOME=/yourpathto/db-derby-10.11.1.1-bin DERBY_HOME/bin/setEmbeddedCP start Derby java jar DERBY_HOME/lib/derbyrun.jar server start &

Persistency Demo download Hibernate from http://sourceforge.net/projects/hibernate/ unzip it

ORM - DAO WORLD MODEL UML ORM ERA ARCHITECTURE DAO DB Actual storage FS Data Object

ORM Object-Relational Mapping is NOT serialization! You can perform queries on each field!

Technologies Java Data Objects (JDO) EJB 2.0 Container Managed Persistence (CMP) evolved into Java Persistence API (JPA) configuration via XML or Annotation

Object states in JPA

package org.hibernate.tutorial.hbm; import java.util.date; public class Event { private Long id; private String title; private Date date; public Event() { // this form used by Hibernate public Event(String title, Date date) { // for application use, to create new events this.title = title; this.date = date; public Long getid() { return id; private void setid(long id) { this.id = id; public Date getdate() { return date; public void setdate(date date) { this.date = date; public String gettitle() { return title; public void settitle(string title) { this.title = title; Demo Event.java

Event.hbm.xml <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> <hibernate-mapping package="org.hibernate.tutorial.hbm"> <class name="event" table="events"> <id name="id" column="event_id"> <generator class="increment"/> </id> <property name="date" type="timestamp" column="event_date"/> <property name="title"/> </class> </hibernate-mapping>

package org.hibernate.tutorial.hbm; import ; public class Test { private SessionFactory sessionfactory; public static void main (String a[]) throws Exception{ Test x= new Test(); x.setup(); if (a[0].equalsignorecase("r")) x.read(); if (a[0].equalsignorecase("w")) x.write(); x.teardown(); Demo Test.java protected void setup() throws Exception { // A SessionFactory is set up once for an application sessionfactory = new Configuration().configure() // configures settings from hibernate.cfg.xml.buildsessionfactory(); protected void teardown() throws Exception { if ( sessionfactory!= null ) { sessionfactory.close();

public void write() { // create a couple of events... Session session = sessionfactory.opensession(); session.begintransaction(); session.save( new Event( "Our very first event!", new Date() ) ); session.save( new Event( "A follow up event", new Date() ) ); session.gettransaction().commit(); session.close(); public void read() { // now lets pull events from the database and list them Session session = sessionfactory.opensession(); session.begintransaction(); List result = session.createquery( "from Event" ).list(); for ( Event event : (List<Event>) result ) { System.out.println( "Event (" + event.getdate() + ") : " + event.gettitle() ); session.gettransaction().commit(); session.close(); Demo

hibernate.cfg.xml <!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> <hibernate-configuration> <session-factory> <!-- Database connection settings --> <property name="connection.driver_class">org.apache.derby.jdbc.clientdriver</ property> <property name="connection.url">jdbc:derby://localhost:1527/ databasename;create=true</property> <property name="connection.username">admin</property> <property name="connection.password">admin</property> <!-- JDBC connection pool (use the built-in) --> <property name="connection.pool_size">1</property> <!-- SQL dialect --> <property name="dialect">org.hibernate.dialect.derbydialect</property>

hibernate.cfg.xml <!-- Disable the second-level cache --> <property name="cache.provider_class">org.hibernate.cache.internal.nocacheprovider</property> <!-- Echo all executed SQL to stdout --> <property name="show_sql">true</property> <!-- Drop and re-create the database schema on startup: create instead of validate --> <property name="hbm2ddl.auto">validate</property> <mapping resource="org/hibernate/tutorial/hbm/event.hbm.xml"/> </session-factory> </hibernate-configuration Note: bindings for other DBs: http://karussell.wordpress.com/2009/06/09/hibernate-cfg-xml-settings-for-derby-oracle-and-h2/

write run: set 30, 2014 12:12:44 PM org.hibernate.annotations.common.reflection.java.javareflectionmanager <clinit> INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final INFO: HHH000037: Columns: [title, event_date, event_id] Hibernate: select event0_.event_id as EVENT_ID1_0_, event0_.event_date as EVENT_DA2_0_, event0_.title as title3_0_ from EVENTS event0_ INFO: HHH000037: Columns: [title, event_date, event_id] Hibernate: select max(event_id) from EVENTS Hibernate: insert into EVENTS (EVENT_DATE, title, EVENT_ID) values (?,?,?) Hibernate: insert into EVENTS (EVENT_DATE, title, EVENT_ID) values (?,?,?) set 30, 2014 12:12:45 PM org.hibernate.engine.jdbc.connections.internal.drivermanagerconnectionproviderimpl stop INFO: HHH000030: Cleaning up connection pool [jdbc:derby://localhost:1527/ databasename;create=true] BUILD SUCCESSFUL (total time: 1 second)

read run: set 30, 2014 12:12:44 PM org.hibernate.annotations.common.reflection.java.javareflectionmanager <clinit> INFO: HCANN000001: Hibernate Commons Annotations {4.0.5.Final INFO: HHH000037: Columns: [title, event_date, event_id] Hibernate: select event0_.event_id as EVENT_ID1_0_, event0_.event_date as EVENT_DA2_0_, event0_.title as title3_0_ from EVENTS event0_ Event (2014-09-30 12:12:35.622) : Our very first event! Event (2014-09-30 12:12:35.682) : A follow up event set 30, 2014 12:12:45 PM org.hibernate.engine.jdbc.connections.internal.drivermanagerconnectionproviderimpl stop INFO: HHH000030: Cleaning up connection pool [jdbc:derby://localhost:1527/ databasename;create=true] BUILD SUCCESSFUL (total time: 1 second)

persistence.xml vs hibernate.cfg.xml If you are using Hibernate's proprietary API, you'll need the hibernate.cfg.xml. If you are using JPA i.e. Hibernate EntityManager, you'll need the persistence.xml. So you generally don't need both as you use either Hibernate proprietary API or JPA. However, if you were using Hibernate Proprietary API and already have a hibernate.cfg.xml (and hbm.xml XML mapping files) but want to start using JPA, you can reuse the existing configuration files by referencing the hibernate.cfg.xml in the persistence.xml in the hibernate.ejb.cfgfile property - and thus have both files

Introduction to Entities

Entities Entities have a client-visible, persistent identity (the primary key) that is distinct from their object reference. Entities have persistent, client-visible state. Entities are not remotely accessible. An entity s lifetime may be completely independent of an application s lifetime. Entities can be used in both Java EE and J2SE environments

package examples.entity.intro; import java.io.serializable; import javax.persistence.entity; import javax.persistence.id; @Entity Entities - example field access. public class Account implements Serializable { // The account number is the primary key @Id public int accountnumber; public int balance; private String ownername; String getownername() {return ownername; void setownername(string s) {ownername=s; This demo entity represents a Bank Account. The entity is not a remote object and can only be accessed locally by clients. However, it is made serializable so that instances can be passed by value to remote clients for local inspection. Access to persistent state is by direct /** Entities must have a public no-arg constructor */ public Account() { // our own simple primary key generation accountnumber = (int) System.nanoTime();

Entities - example public void deposit(int amount) { balance += amount; public int withdraw(int amount) { if (amount > balance) { return 0; else { balance -= amount; return amount; The entity can expose business methods, such as a method to decrease a bank account balance, to manipulate or access that data. Like a session bean class, an entity class can also declare some standard callback methods or a callback listener class. The persistence provider will call these methods appropriately to manage the entity.

Access to the entity s persistent state is by direct field access. An entity s state can also be accessed using JavaBean-style set and get methods. The persistence provider can determine which access style is used by looking at how annotations are applied. In Source 6.1, the @Id annotation is applied to a field, so we have field access.

Access to the Entity package examples.entity.intro; import java.util.list; import javax.ejb.stateless; import javax.ejb.remote; import javax.persistence.persistencecontext; import javax.persistence.entitymanager; import javax.persistence.query; @Stateless @Remote(Bank.class) public class BankBean implements Bank { @PersistenceContext private EntityManager manager; public List<Account> listaccounts() { Query query = manager.createquery ("SELECT a FROM Account a"); return query.getresultlist(); public Account openaccount(string ownername) { Account account = new Account(); account.ownername = ownername; manager.persist(account); return account;

Access to the Entity public int getbalance(int accountnumber) { Account account = manager.find(account.class, accountnumber); return account.balance; public void deposit(int accountnumber, int amount) { Account account = manager.find(account.class, accountnumber); account.deposit(amount); public int withdraw(int accountnumber, int amount) { Account account = manager.find(account.class, accountnumber); return account.withdraw(amount); public void close(int accountnumber) { Account account = manager.find(account.class, accountnumber); manager.remove(account);

Persistence.xml <?xml version= 1.0 encoding= UTF-8?> <persistence xmlns= http://java.sun.com/xml/ns/persistence > <persistence-unit name= intro /> </persistence> A persistence unit is defined in a special descriptor file, the persistence.xml file, which is simply added to the META-INF directory of an arbitrary archive, such as an Ejb-jar,.ear, or.war file, or in a plain.jar file.

datasource configuration on Wildfly https://docs.jboss.org/author/display/wfly8/ DataSource+configuration