In Lerneinheit 1.2 werden Sie Schritt für Schritt durch die Erstellung der erforderlichen Klassen und Schnittstellen für die Klasse StatelessCounterBean.java geführt.
// This program may be used, executed, copied, modified and distributed
// without royalty for the purpose of developing, using, marketing, or distributing.
package com.ibm.example.websphere.ejb3sample.counter;
import java.io.Serializable;
import javax.interceptor.AroundInvoke;
import javax.interceptor.InvocationContext;
public class Audit implements Serializable {
private static final long serialVersionUID = 4267181799103606230L;
@AroundInvoke
public Object methodChecker (InvocationContext ic)
throws Exception
{
System.out.println("Audit:methodChecker - About to execute method: " + ic.getMethod());
Object result = ic.proceed();
return result;
}
}
public class StatelessCounterBean {
}
Geben Sie stattdessen den folgenden Code an:
public class StatelessCounterBean implements LocalCounter, RemoteCounter {
private static final String CounterDBKey = "PRIMARYKEY";
// Containergesteuerte Persistenz verwenden - EntityManager injizieren
@PersistenceContext (unitName="Counter")
private EntityManager em;
public int increment()
{
int result = 0;
try {
JPACounterEntity counter = em.find(JPACounterEntity.class, CounterDBKey);
if ( counter == null ) {
counter = new JPACounterEntity();
counter.setPrimaryKey(CounterDBKey);
em.persist( counter );
}
counter.setValue( counter.getValue() + 1 );
em.flush();
em.clear();
result = counter.getValue();
} catch (Throwable t) {
System.out.println("StatelessCounterBean:increment - caught unexpected exception: " + t);
t.printStackTrace();
}
return result;
}
public int getTheValue()
{
int result = 0;
try {
JPACounterEntity counter = em.find(JPACounterEntity.class, CounterDBKey);
if ( counter == null ) {
counter = new JPACounterEntity();
em.persist( counter );
em.flush();
}
em.clear();
result = counter.getValue();
} catch (Throwable t) {
System.out.println("StatelessCounterBean:increment - caught unexpected exception: " + t);
t.printStackTrace();
}
return result;
}
}
Drücken Sie zum Speichern die Tastenkombination "Strg+S": // This program may be used, executed, copied, modified and distributed
// without royalty for the purpose of developing, using, marketing, or distributing.
package com.ibm.example.websphere.ejb3sample.counter;
import javax.ejb.Local;
@Local
public interface LocalCounter {
public int increment();
public int getTheValue();
}
// This program may be used, executed, copied, modified and distributed
// without royalty for the purpose of developing, using, marketing, or distributing.
package com.ibm.example.websphere.ejb3sample.counter;
import javax.ejb.Remote;
@Remote
public interface RemoteCounter {
public int increment();
public int getTheValue();
}