scbcd-5 q&a with explanations - 2

43
QUESTIONS FOR SCBCD 5.0 FORM 2 Location: > Section 1: EJB 3.0 Overview > Objective 1.1 > Question 1 Which statement correctly identifies the architectural goals of the designers of the EJB architecture? A The EJB architecture supports the development, deployment, and use of web services. B The EJB architecture only supports interoperability with programs written in the Java language. C The EJB architecture addresses the development and deployment of EJB components, but the runtime aspect is left completely to the discretion of the container providers. D The EJB architecture requires that users be aware of the low-level connection pooling aspects and multi-threading characteristics of the Java EE platform. Reference Option A is correct. (See section 2.1 "Overall Goals" in the Core Specification.) Option B, C, and D are incorrect because they are NOT listed as goals in section 2.1 Location: ... > Section 1: EJB 3.0 Overview > Objective 1.2 > Question 2 When a programmer is creating an EJB container, which two APIs should be available or be provided by the EJB Container Provider or the EJB Server Provider? (Choose two.) A EJB 2.1 APIs B Common Annotations C JavaServer Faces APIs D JavaServer Pages APIs E Java Data Objects APIs Reference Options A and B are correct. (See the Simplified Specification 2.2. and the Core Specification 21.1.1.) Option C, D, and E are NOT mentioned in the Specifications so are incorrect. Location: ... > Section 1: EJB 3.0 Overview > Objective 1.3 > Question 3 What programming restrictions are defined in the EJB specifications? A An enterprise bean must NOT attempt to listen on a socket. B A session bean class must NOT have any superclasses and/or superinterfaces. C An enterprise bean can directly read a file descriptor. D An entity bean class need NOT implement a public zero-argument constructor.

Upload: api-19783879

Post on 27-Apr-2015

207 views

Category:

Documents


3 download

TRANSCRIPT

Page 1: SCBCD-5 Q&A With Explanations - 2

QUESTIONS FOR SCBCD 5.0 FORM 2 Location: > Section 1: EJB 3.0 Overview > Objective 1.1 > Question 1

Which statement correctly identifies the architectural goals of the designers of the EJB architecture?

A The EJB architecture supports the development, deployment, and use of web services.

B The EJB architecture only supports interoperability with programs written in the Java language.

C The EJB architecture addresses the development and deployment of EJB components, but the runtime aspect is left completely to the discretion of the container providers.

D The EJB architecture requires that users be aware of the low-level connection pooling aspects and multi-threading characteristics of the Java EE platform.

Reference

Option A is correct. (See section 2.1 "Overall Goals" in the Core Specification.) Option B, C, and D are incorrect because they are NOT listed as goals in section 2.1

Location: ... > Section 1: EJB 3.0 Overview > Objective 1.2 > Question 2

When a programmer is creating an EJB container, which two APIs should be available or be provided by the EJB Container Provider or the EJB Server Provider? (Choose two.)

A EJB 2.1 APIs

B Common Annotations

C JavaServer Faces APIs

D JavaServer Pages APIs

E Java Data Objects APIs

Reference

Options A and B are correct. (See the Simplified Specification 2.2. and the Core Specification 21.1.1.)

Option C, D, and E are NOT mentioned in the Specifications so are incorrect.

Location: ... > Section 1: EJB 3.0 Overview > Objective 1.3 > Question 3

What programming restrictions are defined in the EJB specifications?

A An enterprise bean must NOT attempt to listen on a socket.

B A session bean class must NOT have any superclasses and/or superinterfaces.

C An enterprise bean can directly read a file descriptor.

D An entity bean class need NOT implement a public zero-argument constructor.

Page 2: SCBCD-5 Q&A With Explanations - 2

Reference

Option A is correct. (See section 21.1.2 of the Core Specification)

Option B is incorrect because it may well have them. (See section 4.6.2)

Option C is incorrect. It must NOT attempt to read (or write) a file descriptor. (See 21.1.2 of the Core Specification.)

Option D is incorrect because it must do so. (See section 8.6.2.)

Location: ... > Section 1: EJB 3.0 Overview > Objective 1.4 > Question 4

Which two roles defined by the EJB architecture typically modify the metadata associated with an ejb-jar in the creation, integration, and deployment of the ejb-jar as part of a larger application? (Choose two.)

A Application Assembler

B System Administrator

C Enterprise Bean Provider

D Persistence Provider

E EJB Container Provider

Reference

Options A and C are correct. (See the Core Specification, section 2.2.) The assembler is responsible for combining enterprise beans and the provider for creating the bean. Both would typically manipulate the metadata.

Option B is incorrect because this role refers to someone who configures the enterprises computing and network infrastructure.

Option D is incorrect because this role refers to the provider of the persistence runtime.

Option E is incorrect because this role refers to the provider of the EJB container.

Location: ... > Section 1: EJB 3.0 Overview > Objective 1.5 > Question 5

An enterprise bean packaged in an ejb-jar returns instances of a Television class as a result for one of its business methods. The developer has been asked to create an associated ejb-client JAR file.

What files must be placed in this ejb-client JAR for it to be valid?

A The ejb-jar file (by inclusion or by reference)

B The Television class (by inclusion or by reference)

C Stubs of all enterprise classes referenced by the ejb-client

D The DTDs and schemas of all XML messages used by the client

Page 3: SCBCD-5 Q&A With Explanations - 2

Reference

Option B is correct. (See section 20.4 and 20.3 of the Core Specification.)

Option A is incorrect. The developer typically places the ejb-client in the ejb-jar, NOT vice-versa.

Option C is incorrect. Stubs are generated and should NOT be packaged by a developer.

Option D is incorrect. This has nothing to do with EJB technology.

Location: ... > Section 1: EJB 3.0 Overview > Objective 1.6 > Question 6

An enterprise bean has a set of interceptor classes defined for it in two ways: First, the interceptor classes were specified in the deployment descriptor for the enterprise bean. Second, the classes were specified using the @Interceptor annotation on the enterprise bean itself.

Which statement describes the runtime and deployment-time use of these metadata?

A A conflicting-metadata exception will be thrown by the deployment tools.

B The deployment descriptor metadata will override the annotation metadata.

C The annotation metadata will override the deployment descriptor metadata.

D The result is NOT specified and will be vendor-specific.

Reference

Option B is correct. (See the Simplified Specification 2.1 or the Core Specification 12.1.) Because B is correct, A, C, and D are necessarily incorrect.

Location: ... > Section 2: General EJB 3.0 Enterprise Bean Knowledge > Objective 2.1 > Question 7

Which statement about life-cycle callback methods is correct?

A Life-cycle callback methods must be implemented in the bean class.

B Life-cycle callback methods can have public, private, protected, or package-level access.

C A life-cycle callback method can only have a single callback annotation. In other words, you cannot define a single method and give it two different callback annotations.

D Life-cycle callback methods can be declared as static.

Reference

See 3.4.1 Simplified Specification for all of these.

Option A is incorrect. They can be implemented in an interceptor class too.

Option B is correct.

Option C is incorrect. It can have multiple callback annotations.

Option D is incorrect. They cannot be static (or final).

Page 4: SCBCD-5 Q&A With Explanations - 2

Location: ... > Section 2: General EJB 3.0 Enterprise Bean Knowledge > Objective 2.2 > Question 8

A non-transient String field in an interceptor associated with a stateful session bean is set to "Hello" when the stateful session bean is passivated.

What will the state of the field be after the bean is again activated?

A The specification states that the value will be undefined.

B It will be set to null.

C It is set to "Hello".

D The bean will be associated with an arbitrary interceptor instance after activation, and so can have whatever value the field is set to in that interceptor instance.

Reference

Option C is correct. (See section 4.2.1 of the Core Specification.) The state of the interceptor is effectively bound to the state of the stateful session bean, that is both states will be preserved across passivation/activation.

Option A is incorrect because it will be defined. See Option C.

Option B is incorrect because it will be defined. See Option C.

Option D is incorrect because the interceptor state is bound to the state of the session bean in question, NOT some other arbitrary one.

Location: ... > Section 2: General EJB 3.0 Enterprise Bean Knowledge > Objective 2.3 > Question 9

As a developer of an enterprise bean you want to ensure that the value of an entry from a bean's environment is injected into the bean. The entry's name is myDS and the entry's type is javax.sql.DataSource. Assume that the bean's deployment descriptor correctly defines the entry.

Which two code snippets ensure that this environment resource is successfully injected? (Choose two.)

A @Resource public javax.sql.DataSource getMyDS() { return myDS; } public void setFoo(javax.sql.DataSource myDS) { this.myDS = myDS; }

B @Resource (type=javax.sql.DataSource.class) Object myDataSource;

C @Resource(name="myDS") private javax.sql.DataSource myDS;

D @Resource(name="myDS") public javax.sql.DataSource myDS;

E @EJB public javax.sql.DataSource myDS;

Page 5: SCBCD-5 Q&A With Explanations - 2

Reference

Options C and D are correct. (See Core Specification 16.2.2.) There is no problem if the field is public, private, and so on.

Option A is incorrect because you should put the @Resource annotation on the setter, NOT the getter. (Simplified Specification. 8.1.2)

Option B is incorrect because the name of the variable does not coincide with name of the entry.

Option E is incorrect. The developer does NOT use the @EJB annotation to do this, but the @Resource one.

Location: ... > Section 2: General EJB 3.0 Enterprise Bean Knowledge > Objective 2.4 > Question 10

The EJB Timer service can be used to ensure that the EJB container invokes a timeout method on a bean at a specified time or after a specified period.

Which two types of beans support this Timer service? (Choose two.)

A Stateless session beans

B Stateful session beans

C EJB 2.1 entity beans

D EJB 3.0 entities

Reference

Option A and Option C are correct. (See Core Specification 18.2.) Message -driven beans are supported too.

Option D and B are incorrect because these beans are not supported.

Location: ... > Section 2: General EJB 3.0 Enterprise Bean Knowledge > Objective 2.5 > Question 11

Consider the following excerpt from a session bean with one business method, roast:

10. @Stateful

11. public class OvenBean implement Oven {

12. @Resource SessionContext ctx;

13. @Resource public void setTemperature(Temp temp) {

14. //

15. }

20. public void roast() {

21.

Page 6: SCBCD-5 Q&A With Explanations - 2

22. }

23. @PostConstruct

24. void potatoes() {

25. }

99. }

Assume that the associated descriptor has a dependency of type Temp and name temperature.

What order of invocation occurs if a client creates such a bean and invokes the roast method?

A roast will be called, followed by the container injecting ctx and calling setTemperature, followed by potatoes being called.

B ctx will be injected and setTemperature called. roast will then be called. potatoes will NOT be called at all.

C ctx will be injected. This will be followed by a call to potatoes, and finally to roast. setTemperature will NOT be called.

D ctx will be injected and setTemperature called. potatoes will then be called, followed by roast.

Reference

Option D is correct. According to the Simplified Specification 8.1.1, 9.3.1 and the Core Specification (for example, 4.3.10), after a new instance is created the SessionContext (if applicable) and other resources are injected. According to 4.1.4, the PostConstruct life-cycle callback is invoked after any dependency is injected and before any business method is invoked. So this reflects the correct order of invocation.

Options A, B, and C contradict this order, and so are necessarily incorrect. The PostConstruct method is valid and is called, as is the setter-type resource injection.

Location: ... > Section 2: General EJB 3.0 Enterprise Bean Knowledge > Objective 2.6 > Question 12

Which statement about EJB 2.x and EJB 3.0 API interoperability is correct?

A A stateless session bean written to the EJB 3.0 API can be adapted to an EJB 2.1 client interface.

B The developer cannot mix APIs. For example, the developer cannot write an EJB 3.0 session bean while also implementing an EJB 2.1 EJBHome interface.

C The EJB 2.1 API requires the use of a stateful session bean's home interface to obtain a reference to the bean's component interface. The developer cannot use dependency injection to obtain a reference to such a home interface in an EJB 3.0 client of such a bean.

D An adapter class has to be used when accessing EJB 2.0 environment variables of a stateless session bean, when such a bean is deployed in an EJB 3.0 container.

Page 7: SCBCD-5 Q&A With Explanations - 2

Reference

Option A is correct. (See section 9.3 in the Simplified Specification.)

Option B is incorrect. The developer can do this. (See 9.4 in the Simplified Specification.)

Option C is incorrect. The developer can use dependency injection on old-style EJB 2.1 home interfaces. (See 3.6.1 of the Core Specification.)

Option D is incorrect. There is no such requirement.

Location: ... > Objective 3.1 > Question 13

Which statement characterizes stateful session beans?

A They allow the PostConstruct, PreDestroy, and PrePassivate life-cycle callbacks.

B They require home interfaces.

C When a client looks up a stateful session bean in the JNDI, the same bean is returned every time.

D They are asynchronous message consumers.

Reference

Option A is correct. (See 5.1.4.)

Option B is incorrect. Session beans do not require home interfaces (See the Simplified Specification 3.5.) Option C is incorrect. (See 4.4 of the Core Specification.) A different bean is returned every time.

Option D is incorrect. Message-driven beans are asynchronous message consumers. (See 2.4.2 of the Core Specification.)

Location: ... > Objective 3.2 > Question 14

Which statement is correct about session beans?

A Stateless and stateful session beans can implement the javax.ejb.SessionSynchronization interface to receive transaction synchronization notifications.

B The remote business interface of an EJB 3.0 session bean can be specified using the @RemoteHome annotation.

C The same business interface cannot be both a local and a remote business interface of a bean.

D A bean class cannot have more than one remote business interface.

Page 8: SCBCD-5 Q&A With Explanations - 2

Reference

Option A is incorrect. Stateless beans must NOT implement the interface. (See 4.5 of the Core Specification.)

Option B is incorrect. @RemoteHome is used to specify a home interface for EJB 2.1 client views. (See 10.3 of the Simplified Specification.)

Option C is correct. (See 3.2 of the Simplified Specification.)

Option D is incorrect. (See 3.2 of the Simplified Specification.)

Location: ... > Objective 3.3 > Question 15

Given an interface:

5. public interface ValueInt {

6. public int getVal();

7. int getBarPackage();

8. }

Here is an excerpt from a stateless session bean that implements this interface:

10. @Stateless

11. public class FloatBean implements ValueInt {

12. public int getVal() { return 4; }

13. public int getBarPackage() { return 2; }

50. }

What methods are exposed to local clients of this stateless session bean?

A no methods are exposed

B getVal

C getBar

D getVal and getBarPackage

Reference

Option D is correct. Both methods are exposed. It also does not matter that there is no @Local on the interface. (See 10.2 of the Simplified Specification.)

Option A, B, and C are incorrect because this is a valid session bean exposing two methods.

Page 9: SCBCD-5 Q&A With Explanations - 2

Location: ... > Objective 3.4 > Question 16

A programmer constructs a stateful session bean that contains, in addition to the business methods, the following three life-cycle callback methods:

@PostConstruct

public void initConnection() {

// add a new unique record into a database, and keep primary key

// in the local state of this stateful session bean.

}

@PreDestroy

public void zapConnection() {

// retrieve the primary key from the local state of this stateful session

// bean and remove the record.

}

@Remove

public void zap() {

}

The initConnection method simply adds a new record to a database table and stores its primary key in the local state of the stateful session bean. If, for example, the bean can be passivated and reactivated, and later when the bean is removed and the PreDestroy life-cycle method called, the record can be removed.

What circumstances lead to the database record NOT being deleted?

A A timeout of the bean occurs while the bean instance is active.

B The method zap is called while the bean instance is active.

C A timeout of the bean occurs while the bean instance is passivated.

D The method zap is called when the bean instance is passivated.

Reference

Option A is incorrect because the PreDestroy should be called here, resulting in the database record being deleted. Option B is incorrect because the PreDestroy method should be called here, resulting in the database record being deleted. Option C is correct. See 4.4.3 of the Core Specification for when the PreDestroy method is NOT called. When passivated, PreDestroy is NOT called. Option D is incorrect because calling the Remove should ensure that the PreDestroy life-cycle callback method is invoked.

Page 10: SCBCD-5 Q&A With Explanations - 2

Location: ... > Objective 3.5 > Question 17

The deployment descriptor for the Foo session bean looks similar to this:

10. <enterprise-beans>

11. <session>

12. ...

13. <ejb-name>Foo</ejb-name>

14. <ejb-class>ms.FooBean</ejb-class>

15. ...

16. <resource-ref>

17. <res-ref-name>jdbc/BarDB</res-ref-name>

18. <res-type>javax.sql.DataSource</res-type>

19. <res-auth>Container</res-auth>

20. <res-sharing-scope>Shareable</res-sharing-scope>

21. </resource-ref>

22. ...

23. </session>

24.</enterprise-beans>

Assume that a deployer binds this to an actual resource. The implementation of Foo contains a reference to a Context object bound to the variable initCtx and a reference to a SessionContext object bound to the variable ctx.

Which statement successfully retrieves the datasource?

A @Resource DataSource ds;

B (DataSource) ctx.lookup("java:comp:env/jdbc/BarDB");

C initCtx.lookup("java:comp/env/jdbc/BarDB");

D @Resource(name=?jdbc/BarDB?, type=javax.sql.DataSource)

Reference

Options C is a correct way to retrieve a resource manager. (See 16.7.1.2/3 of the Core Specification for an example.) Option A fails because the datasource name does not correspond with the name on line 17. Option B uses the incorrect path to the resource. It should be jdbc/BarDB. Option D does nothing. It simply declares a reference to a resource, performing much the same task as the descriptor snippet given above. (See 16.7.1.3 and 16.7.1.2 of the Core Specification.)

Page 11: SCBCD-5 Q&A With Explanations - 2

Location: ... > Objective 3.6 > Question 18

Which statement about exposing session beans as web services is correct?

A Stateful and stateless session beans can be designated as web service endpoints (can expose a web services client view).

B A bean that implements a web service endpoint using the JAX-RPC contracts can use a method on the SessionContext to access the SOAP message for the end point.

C EJB interceptors cannot be used in beans exposed as web services.

D Session beans that provide a web services client view cannot make use of JAX-RPC message handlers.

Reference

Option A is incorrect. Only stateless beans can be.

Option B is correct. (See 4.3.6 of the Core Specification.) SessionContext.getMessageContext in fact.

Option C is incorrect. They can. They can even see the MessageContext. (See 4.3.6 of the Core Specification.)

Option D is incorrect. They can. (See 4.6.1. of the Core Specification.) Interestingly, the handlers and interceptors can share information!

Location: ... > Objective 3.7 > Question 19

A client tests two stateless session bean business interface references for identity using the equals method as follows:

10. @EJB SSb fee;

11. @EJB SSb fi;

12. if (fee.equals(fee)) { /* some code */ }

13. if (fee.equals(fi)) { /* some code */ }

Which statement is correct about this testing?

A The developer should NOT compare business interface references with the equals method.

B The tests on line 12 and 13 both always return false.

C The test on line 12 always succeeds with true, but the test on line 13 always fails with false.

D Both tests always succeed with true.

Reference Option A is incorrect. The code is valid. (See 3.4.5.2 of the Core Specification.)

Option B is incorrect because D is true. Option C is incorrect because D is true.

Option D is correct. All business object references of the same interface type for the same stateless session bean have the same object identity. (See 3.4.5.2 of the Core Specification.)

Page 12: SCBCD-5 Q&A With Explanations - 2

Location: ... > Objective 4.1 > Question 20

A message-driven bean can have an instance of a MessageDrivenContext injected.

Which method can be successfully invoked on this interface from a message-driven bean?

A getEJBHome

B getCallerPrincipal

C isCallerInRole

D getEJBLocalHome

Reference

Option B is correct. (See 5.4.4 of the Core Specification.)

Option A, C, and D should NOT be called. (See 5.4.4 of the Core Specification.)

Location: ... > Objective 4.2 > Question 21

Which statement is true about message-driven beans?

A A message-driven bean can register with the EJB Timer Service for timeout callback notifications.

B A message-driven bean must implement the javax.ejb.MessageDrivenBean interface.

C Message-driven beans only support the PostConstruct life-cycle callback interceptor.

D Message-driven beans do NOT support the AroundInvoke business method interceptors.

Reference Option A is correct. (See 5.4.7 of the Core Specification.)

Option B is incorrect. This is optional. (See 5.4.6 of the Core Specification.)

Option C is incorrect. It also supports PreDestroy. (See 5.4.5 of the Core Specification.)

Option D is incorrect. They do. (See 5.4.9 of the Core Specification.)

Location: ... > Objective 4.3 > Question 22

A developer is given a JMS message-driven bean, which has no descriptors or metadata that describe acknowledge modes or subscription durability. In addition, the message-driven bean uses bean-managed transactions and is subscribed to a topic.

What two message-driven bean behaviors can the developer expect to see? (Choose two.)

A If a message is received, the container automatically acknowledges it.

B If a message is received, the container does NOT automatically acknowledge it.

C Messages will NOT be missed, even if the EJB server is NOT running.

D Messages can be missed if the EJB server is NOT running.

E Specifying subscription durability for a topic has no effect.

Page 13: SCBCD-5 Q&A With Explanations - 2

Reference

Option A is correct. (See 5.4.14 of the Core Specification.)

Option D is correct. (See 5.4.16 of the Core Specification.) So the default is non-durable subscription and automatic acknowledgment.

Option C is incorrect because D is correct. Option B is incorrect because A is true.

Option E is incorrect. The developer certainly can specify a durability for a topic. (See 5.14.16 of the Core Specification.)

Location: ... > Objective 4.4 > Question 23

Given a snippet of a JMS message-driven bean, configured to listen on a queue.

@MessageDriven

public class LetterBean implements MessageListener {

@Resource MessageDrivenContext ctx;

public void onMessage(Message msg) {

ctx.setRollbackOnly();

}

}

A JMS server receives a message and delivers it to this queue. After executing the onMessage method, no exceptions are thrown.

Which statement is correct about this message-driven bean?

A The message-bean is using bean-managed transactions.

B The server receives an acknowledgment sent by the LetterBean instance.

C The JMS server sends the same message more than once.

D The LetterBean instance that receives the message immediately moves into the "does NOT exist" state.

Reference

Option A is incorrect because no exceptions are thrown when setRollbackOnly is invoked. (See 5.4.4 of the Core Specification.)

Option B is incorrect. It will NOT because setRollbackOnly is used. (See 5.4.4 of the Core Specification.)

Option C is correct. The setRollbackOnly ensures that no acknowledgment is sent, so the JMS server tries to resend.

Option D is incorrect. (See 5.4.17 for when this occurs.)

Page 14: SCBCD-5 Q&A With Explanations - 2

Location: ... > Section 5: Java Persistence API Entities > Objective 5.1 > Question 24

Given an excerpt of a Book entity (it is just missing the import statements):

10. @Entity

11. public class Book implements Serializable {

12. @Id

13. @GeneratedValue(strategy = GenerationType.AUTO)

14. private Integer id;

15. String bookName;

16. protected int price;

17. enum Status {IN, OUT};

18. @Enumerated( EnumType.ORDINAL )

19. Status status;

20. transient int bar;

21. java.util.Map<Integer, String> comments;

22. protected Book() {};

23. }

No descriptors are used.

Which statement is correct about this entity?

A There is an error on line 11. It must NOT implement Serializable.

B Adding a single @Transient annotation makes this entity valid.

C The visibility declarations on some of the variables causes an exception.

D The enumeration or its field definition on lines 17, 18, or 19 is NOT valid.

E There is an error in the identity definition on lines 12, 13, or 14.

Reference

Option A is incorrect. It can. (See 2.1 of the JPA Specification.)

Option B is correct. Adding it to line 21 does the job. java.util.Map is NOT a valid persistent field type unless of course it is for a collection-based relationship. (See the end of 2.1. of the JPA Specification.)

Option C is incorrect. The visibilities are private/protected/package which is fine. (See 2.1 of the JPA Specification.) Option D is incorrect. The field definition is fine. (See 9.1.21 of the JPA Specification.)

Option E is incorrect. This identity definition is fine.

Page 15: SCBCD-5 Q&A With Explanations - 2

Location: ... > Section 5: Java Persistence API Entities > Objective 5.2 > Question 25

Given an excerpt from an embeddable class:

10. @Embeddable

11. public class Mattress {

12. int x;

13. String y;

14. /* ... */

15. }

It is referenced from an entity class Hotel. Given the full excerpt containing the reference:

20. @Entity

21. public class Hotel {

22. //

23. Mattress spring;

24. public Mattress getSpring() { return spring; }

25. public void setSpring(Mattress bounce) { spring = bounce; }

26. /* ... */

27. }

No deployment descriptors are used.

Which statement is correct about this class?

A The Mattress class should define an identity field.

B An annotation needs to be placed on line 22 for the Hotel entity to be valid.

C A different entity class, for example Shop, can also use the Mattress class as the type of one of its persistent fields.

D The Mattress class cannot be used as the type of a field, when that field is annotated with @EmbeddedId.

Reference Option A is incorrect. It should NOT define one. These classes do not have an identity, but are associated with their referencing entity. (See 2.1.5 of the JPA Specification and also see the footnote on 9.1.14.) Option B is incorrect. Just having the type annotated is enough. (See 2.1.6 of the JPA Specification.) Option C is correct. Although 2.1.5 JPA Specification says "attempting to share an embedded object across entities has undefined semantics" this refers to instances. It is acceptable for the type to be shared (promoting reuse).

Option D is incorrect. It can be used because it has the @Embeddable attribute. (See 9.1.14.)

Page 16: SCBCD-5 Q&A With Explanations - 2

Location: ... > Section 5: Java Persistence API Entities > Objective 5.3 > Question 26

All of the entities in a persistence unit have the following two lines defining their primary keys:

10. @GeneratedValue(generator="MyGenerator", strategy = GenerationType.TABLE)

11. private int id;

The deployment descriptor has only the following few lines pertaining to primary keys:

20. <table-generator>

21. <name>MyGenerator</name>

22. <table>MyTable</table>

23. <pk-column-name>NAME</pk-column-name>

24. </table-generator>

Which statement is correct?

A Only AUTO, TABLE, and IDENTITY generation types are made available by a persistence provider.

B The different entities within the persistence unit can share the same generator.

C The provider must generate a suite of tables when it processes the table-generator tag.

D The MyTable table is accessed each time a new entity is persisted to the database to ensure that a unique identifier is assigned for the entity.

Reference

See 9.1.38 and 9.19 of JPA Specification.

Option A is incorrect. There is also SEQUENCE.

Option B is correct. It can. A single table-generator stores a number of ID sequences (such as the last chunk of IDs used), one for each entity.

Option C is incorrect. The table-generator tag does not generator tables. It defines tables that will be used to generate ID values.

Option D is incorrect. Chunks of ID values are allocated. The default chunk size is 50. (See 9.1.38.)

Page 17: SCBCD-5 Q&A With Explanations - 2

Location: ... > Section 5: Java Persistence API Entities > Objective 5.4 > Question 27

There are two tables in a database, Celery and Carrot. Celery contains a foreign key to Carrot. Each table has a primary key, and there are no other constraints on the tables. No descriptors are used, and in the following options each scenario depicts all the mapping information pertaining to the relationship.

Which entities accurately model this database scenario?

A @Entity Celery {

/* ... */

}

@Entity Carrot {

@ManyToOne

Celery celery;

/* ... */

}

B @Entity Celery {

@ManyToOne

Carrot carrot;

/* ... */

}

@Entity Carrot {

/* ... */

}

C @Entity Celery {

@OneToOne

Carrot carrot;

/* ... */

} @Entity Carrot {

/* ... */

}

Page 18: SCBCD-5 Q&A With Explanations - 2

D @Entity Celery {

/* ... */

}

@Entity Carrot {

@OneToOne

Carrot carrot;

/* ... */

}

Reference

Option B is correct. The question states that Celery has a foreign key constraint to Carrot. So entities mapped to Celery are able to point to entities mapped to Carrot. This is almost enough for a unidirectional one-to-one mapping used in Option C and Option D, but for a *one-to-one* mapping you need a *unique key constraint* on the foreign key, but that does not exist here, so it is NOT Option C or Option D. Furthermore, unidirectional mappings only have an owning side, which contains the foreign key). In this case, the owning side is Celery. (See 2.1.8.3 of the JPA Specification.) Option A is incorrect because of this too. The unidirectional mapping must have an owning side containing the foreign key (see 2.1.8.3.1 of the JPA Specification) and in Option A the @ManyToOne is on the incorrect entity (table). (See 2.1.8.3.2 for another example.)

Location: ... > Section 5: Java Persistence API Entities > Objective 5.5 > Question 28

A domain model comprises two entities: Dog and Flea. The developer is required to construct these entities so that the Dog and Flea entities are in a unidirectional one-to-many relationship.

Which statement about implementing this model is NOT correct?

A The @OneToMany annotation must be placed in the Dog entity.

B The @ManyToOne annotation must NOT be used on the Flea entity.

C A join table can be used to implement this relationship.

D The Flea entity will be the owning side of the relationship.

Page 19: SCBCD-5 Q&A With Explanations - 2

Location: ... > Section 5: Java Persistence API Entities > Objective 5.5 > Question 28

A domain model comprises two entities: Dog and Flea. The developer is required to construct these entities so that the Dog and Flea entities are in a unidirectional one-to-many relationship.

Which statement about implementing this model is NOT correct?

A The @OneToMany annotation must be placed in the Dog entity.

B The @ManyToOne annotation must NOT be used on the Flea entity.

C A join table can be used to implement this relationship.

D The Flea entity will be the owning side of the relationship.

Reference

Option D is correct.

For an example of this scenario, see 2.1.8.5 and 2.1.8.5.1 of the JPA Specification. Option D is the option that is NOT true here. The owning side will be Dog. The @OnetoMany annotation will certainly be placed on Dog, and the @ManyToOne annotation must NOT be used because this relationship is unidirectional.

Location: ... > Section 5: Java Persistence API Entities > Objective 5.6 > Question 29

Here are excerpts from a class hierarchy, where some of the classes are abstract and others concrete:

10. @MappedSuperclass

11. public abstract class FooSuperDuper {

12. int foosuperduper;

13. }

20. public class FooSuper extends FooSuperDuper{

21. int foosuper;

22. }

30. @Entity

31. public class Foo extends FooSuper {

32. int foo;

33. /* ... */

34. }

Page 20: SCBCD-5 Q&A With Explanations - 2

Which statements about these classes is correct?

A All of the fields foo, foosuper, and foosuperduper will be persisted.

B Only the fields foo and foosuper will be persisted.

C Only the fields foo and foosuperduper will be persisted.

D FooSuperDuper can be the target of a persistent relationship defined in a different entity.

E FooSuper instances can be persisted.

Reference

Option C is correct, which makes Option B and Option A incorrect. (See 2.1.9.3.) The non-entity class FooSuper simply contributes behavior (in this case, none), and NOT persistent state.

Option D is incorrect. It cannot be the target. (See 2.1.9.2 of the JPA Specification.)

Option E is incorrect. The developer cannot persist a non-entity superclass. (See 2.1.9.2 of the JPA Specification.)

Location: ... > Section 5: Java Persistence API Entities > Objective 5.7 > Question 30

Given the definition for an entity, Book:

10. @Entity

11. public class Book {

12. @Id Integer id;

13. @Column(name="NAMEBOOK")

14. String bookName;

15. public java.util.Date loanDate;

16. }

The associated descriptor file has the following snippet pertaining to this entity:

20. <entity class="Book" metadata-complete="true">

21. <table name="BOOKTB"/>

22. <attributes>

23. <basic name="bookName">

24. <column name="TOMENAME"/>

25. </basic>

26. <basic name="loanDate">

27. <temporal>DATE</temporal>

Page 21: SCBCD-5 Q&A With Explanations - 2

28. </basic>

29. </attributes>

30. </entity>

No other parts of the deployment descriptor affect this configuration.

Which statement about the persistent unit and descriptor is correct?

A The descriptor will ensure that the table BOOKTB is used to map the entity Book, and that bookName is mapped to column NAMEBOOK within this table.

B The descriptor ensures that the table BOOKTB is used to map the entity Book, and that bookName is mapped to column TOMENAME within this table.

C This persistent unit does NOT deploy because an annotation is missing on the Book entity class.

D This persistent unit does NOT deploy because the descriptor information is NOT complete.

Reference

Option D is correct. The entity has the metadata-complete attribute, which means that the metadata should be completely specified within the descriptor as the metadata on the class will be ignored. This is an entity, therefore a primary key must be indicated, and the descriptor does not do this. As a result, you cannot successfully deploy this code. (See 10.1.3.1.)

Option A, B, and C are incorrect because D is correct. The descriptor does NOT ensure that a particular table or column is used because the descriptor will NOT allow this to be deployed.

Location: ... > Section 6: Java Persistence Entity Operations > Objective 6.1 > Question 31

Which statement is correct about the EntityManager API?

A The merge, persist, remove, and getReference methods must be invoked within a transaction context.

B It is safe (no exception is thrown) to call merge or getTransaction on a JTA EntityManager instance.

C The getReference method may throw an EntityNotFoundException.

D Runtime exceptions thrown by the refresh and createQuery methods of the EntityManager interface do NOT cause the transaction to be rolled back.

Reference

Option A is incorrect. getReference does NOT need to be invoked within a transaction context. (See 3.1.1 of the JPA Specification.)

Option B is incorrect. An exception is thrown if you call getTransaction on a JTA transaction manager. (See 3.1.1 interface listing.)

Option C is correct. Even though in general this behaves as a lazy proxy to an entity, an EntityNotFoundException can be thrown. (See interface documentation in 3.1.1 of the JPA Specification.) Option D is incorrect. It causes the exception to roll back. (See 3.1.1.)

Page 22: SCBCD-5 Q&A With Explanations - 2

Location: ... > Section 6: Java Persistence Entity Operations > Objective 6.2 > Question 32

Entities can be in a new, managed, detached, or removed state. Which statement is correct about these states?

A Removing an entity in the removed state, causes an IllegalArgumentException to be thrown.

B Detached entities are associated with a persistence context, but no longer have a persistent identity.

C If an entity in the new state is removed, any cascaded removes to referenced objects from this new entity, are still carried out.

D Immediately removing an entity after creating and persisting it, within the same transaction, causes an IllegalArgumentException to be thrown.

Reference

Option A is incorrect. It is just ignored. (See 3.2.2 of the JPA Specification.)

Option B is incorrect. They are no longer associated with a persistent context, but do have a persistent identity. (See 3.2 of the JPA Specification.)

Option C is correct. Cascades work on objects that are still new! (See 3.2.2 of the JPA Specification.)

Option D is incorrect. If an entity has just been created, it is in the new state. It is then persisted, so it moves to a managed state. Removing managed entities is allowed. They become removed. (See 3.2.2 of the JPA Specification.)

Location: ... > Section 6: Java Persistence Entity Operations > Objective 6.3 > Question 33

Which statement does NOT correctly identify when an entity becomes detached when a transaction-scoped persistence context is used?

A Managed entities become detached when the transaction commits.

B Pre-existing managed entities (instances that were persistent in the database at the start of the transaction) become detached when the transaction commits.

C Executing EntityManager.clear or EntityManager.flush causes all managed entities to become detached.

D If the entity manager is used outside of a transaction, all entities loaded from the database by the EntityManager.find method of that entity manager are detached.

Reference

Option A and Option B both reflect what actually happens to managed instances at transaction commit/rollback. (See 3.3.1 and 3.3.2 of the JPA Specification.)

Option C is correct because EntityManager.flush does NOT cause all managed entities to become detached. It simply synchronizes the context with the database. (See 3.1.1.) Option D reflects what actually happens. They are detached. It is legal to do this. (See notes on find in 3.1 of the JPA Specification.)

Page 23: SCBCD-5 Q&A With Explanations - 2

Location: ... > Section 6: Java Persistence Entity Operations > Objective 6.4 > Question 34

Given a method from a stateless session bean manipulating Book entities that have a persistent name field. Moreover, the Book entity has a life-cycle callback for PrePersist, PostPersist, PreRemove, PostRemove, and PostUpdate. It runs in a REQUIRES_NEW transactional context, and em is bound to a entity manager:

10. public void bookDance() {

11. Book b = new Book("Tango");

12. em.persist(b);

13. Book d = (Book) em.createQuery("select b from Book b").getSingleResult();

14. d.setBookName("Jive");

15. em.remove(d);

16. Book q = new Book("Salsa");

17. em.persist(q);

18. }

The method completes without any exception and the transaction commits.

Which statement corresponds to a possible order of callback method invocation that would occur during this method?

A PostLoad, PrePersist, PostPersist, PreRemove, PrePersist, PostPersist, PostRemove

B PrePersist, PostPersist, PrePersist, PostPersist, PreRemove, PostRemove

C PrePersist, PostPersist, PreRemove, PrePersist, PostUpdate, PostPersist, PostRemove

D PrePersist, PostPersist, PostLoad, PrePersist, PostPersist, PreRemove, PostUpdate, PostRemove

Reference The key here is that you can rely on the order of some life-cycle callbacks (because they are invoked as part of the synchronous persist/remove operations) but NOT on others. For example, PostRemove, which is invoked after the actual database change occurs, might be at some stage in the future. Option A is incorrect because of the PostLoad at the start. Nothing loads any entity before an entry persists here. Option B is incorrect because of the reordering. The Specification clearly states that PrePersist and PreRemove are invoked before the respective EntityManager persist and remove operations are executed. So the order of PreRemove and PrePersist must follow the order of the calls, which in this case is persist (line 12), remove (line 15), persist (line 17). Option C is correct. The order of the PrePersists and PreRemoves follow the code. The update might seem to occur in an odd place, but it is quite valid because the Specification indicates that it occurs after the *database* update, which can occur at any time that the state is flushed. Finally, the PostRemove occur too because of the corresponding PreRemove on line 15. As the Specification indicates, these can occur directly after the operation or at transaction commit time (as in this case). (See 3.5.2 of the JPA Specification.) Option D is incorrect because of the reordering. See Option B. There are other valid orders. For example, you can remove PostUpdate from Option C.

Page 24: SCBCD-5 Q&A With Explanations - 2

Location: ... > Section 6: Java Persistence Entity Operations > Objective 6.5 > Question 35

Which statement about locking is correct?

A JPA assumes a default repeated-read database isolation level.

B Optimistic locking cannot be used in extended persistence context.

C When an entity with a version attribute is flushed to the database, an OptimisticLockException is thrown if its version attribute is stale.

D Persistence providers only generate OptimisticLockException exceptions when a transaction commits.

Reference

Option A is incorrect. It assumes a read-committed isolation level. (See 3.4 of the JPA Specification.)

Option B is incorrect. There are no restrictions similar to this in the Specification. It works in an extended context. Option C is correct. This is the general use case for merging detached objects. (See 3.4.2 of the JPA Specification.)

Option D is incorrect. They can be generated when the flush method is called too.

Location: ... > Section 7: Persistence Units and Persistence Contexts > Objective 7.1 > Question 36

Given: 10. import javax.persistence.*;

11. public class BookViews {

12. public static void main (String[] args) {

13. EntityManagerFactory emf = Persistence.createEntityManagerFactory("Book");

14. EntityManager em = emf.createEntityManager();

15. em.getTransaction().begin();

16. Book b = (Book) em.createQuery("SELECT b FROM Book b").getSingleResult();

17. b.setAccessed(b.getAccessed() + 1);

18. em.getTransaction().commit();

19. em.close();

20. emf.close();

21. }

22. }

Page 25: SCBCD-5 Q&A With Explanations - 2

Assume that the Book entity exists, that the appropriate configuration files are in place, and that there is a Book entity in the persistent store.

Which statement about this code, and about resource-local/JTA entity managers in general, is correct?

A This code compiles and executes fine in a Java SE environment.

B The calls on line 15 and 18 are illegal.

C It is illegal to write this sort of resource-local entity manager code in a Java EE environment.

D The default entity-manager transaction type should have been set on line 13.

Reference Option A is correct. It is an example of a resource-local entity manager being used.

Option B is incorrect. This is how you use the EntityTransaction interface. (See 5.5.2.1 of the JPA Specification.)

Option C is incorrect. The developer is allowed to use resource-local entity managers in a Java EE environment. (See 6.2.1.2 of the JPA Specification.)

Option D is incorrect. It defaults to resource-local in a Java SE environment such as this.

Location: ... > Section 7: Persistence Units and Persistence Contexts > Objective 7.2 > Question 37

Which statement about container-managed persistence contexts is NOT correct?

A Container-managed persistence contexts propagate with the JTA transaction within the container.

B Container-managed persistence contexts can have a lifetime that is scoped to a single transaction or that spans multiple transactions.

C The developer can create extended persistence contexts in a stateful session bean.

D The developer can create extended persistence contexts in a stateless session bean.

Reference

Option D is the option that is NOT true. The developer can only create extended persistence contexts in a stateful session bean. (See 5.6.2 of the JPA Specification.) Option A and Option B are correct. It propagates with the JTA transaction and it can be transaction or extended scoped. (See 5.6 of the JPA Specification.) Option C is also correct. (See 5.6.2 of the JPA Specification.)

Location: ... > Section 7: Persistence Units and Persistence Contexts > Objective 7.3 > Question 38

Which method of the EntityManager API is used to control the life-cycle of an application-managed persistence context?

A EntityManager.remove

B EntityManager.refresh

C EntityManager.joinTransaction

D EntityManager.getReference

Page 26: SCBCD-5 Q&A With Explanations - 2

Reference

Option C is correct. For example, a JPA application-managed entity manager could be created outside the scope of a JTA transaction and later associated with one. (See 5.7 and 3.1.1 of the JPA Specification.) Other methods used to manage the entity manager include close, isOpen, and getTransaction. Option A, B, and D are incorrect because remove, refresh, and getDelegate are NOT used to control the life-cycle of (any kind of) persistence context, but rather to manage entities within the scope of a persistence context.

Location: ... > Section 7: Persistence Units and Persistence Contexts > Objective 7.4 > Question 39

Given an excerpt from a session bean that uses a configured resource-local entity manager:

10. @Stateless

11. public class SpamBean implements SpamService {

12. @PersistenceUnit(unitName="spammer")

13. EntityManagerFactory emf;

14.

15. public void createSpam(String msg) {

16. EntityManager em = emf.createEntityManager();

17. try {

18. Spam s = new Spam(msg);

19. em.getTransaction().begin();

20. em.persist(s);

21. em.getTransaction().commit();

22. } catch (Exception oh) {

23.

24. } finally {

25. em.close();

26. }

27. }

28. }

Page 27: SCBCD-5 Q&A With Explanations - 2

Spam is an entity. Assume that the spammer persistence unit is set up correctly.

What happens when another session bean running on the same server, executing in a JTA transactional context, makes a call to the createSpam method?

A An exception is thrown before line 16 is executed.

B An exception is thrown on line 19.

C The JTA transactional context is suspended on line 19 and a new transaction is created.

D An exception is thrown on line 21.

E If the datasources underlying the entity manager are appropriately configured, the code executes without error.

Reference Option E is correct. The key here is that this is a *resource-local* entity manager. So the transaction is mapped to the resource that underlies the entity manager, probably a datasource in this case. The other important point to note is that these entity managers are unaware of any JTA transaction that might be taking place. (See 5.5 and 5.5.2 of the JPA Specification.) The code is fine and is a good example of using an application-managed, resource-local entity manager. However, the developer should configure your datasources appropriately. In this example, the developer would configure datasources appropriately by ensuring that the entity manager uses a non-JTA datasource. Otherwise, conflicts occur.

Option A, B, C, and D are incorrect because no exceptions are generated, as explained above.

Location: ... > Section 7: Persistence Units and Persistence Contexts > Objective 7.5 > Question 40

Which statement about persistence units and packaging is correct?

A Every persistence unit must always have the persistence.xml and orm.xml configuration files.

B The persistence.xml file can be used to define more than one persistence unit.

C Mapping metadata for a class can be specified using annotations, or in the XML configuration files, but NOT in both.

D When a persistence unit is packaged in a WAR, the persistence.xml file must be located in the /META-INF directory off the root of the WAR package.

Reference

Option A is incorrect. orm.xml is optional. It is NOT needed. (See 6.2.1.6 of the JPA Specification.)

Option B is correct. (See 6.2.)

Option C is incorrect. The developer can specify mapping metadata using both annotations and XML metadata. (See 6.2.1 of the JPA Specification.)

Option D is incorrect. It can either be in a jar file in WEB-INF/lib, or in the META-INF directory off the WEB-INF/classes directory. (See 6.2 of the JPA Specification.)

Page 28: SCBCD-5 Q&A With Explanations - 2

Location: ... > Section 7: Persistence Units and Persistence Contexts > Objective 7.6 > Question 41

Which exception will NOT cause an existing transaction to roll back?

A PersistenceException

B RollbackException

C EntityExistsException

D NoResultException

E OptimisticLockException

Reference

Option D is correct. (See 3.6.1 of the JPA Specification.)

Option A, B, C, and E are incorrect. (See 3.6.1 of the JPA Specification.) Although NoResultException is a PersistenceException, it does NOT roll the transaction back. All the others do.

Location: ... > Section 8: Java Persistence Query Language > Objective 8.1 > Question 42

Given an excerpt from an entity:

10. @Entity

11. public class Koala {

12. int children;

13. @Id

14. private Integer id;

15. /* ... */

16. }

The following code was written to find the sum and average number of children across all Koala entities (assume the variable em is bound to a valid EntityManager instance):

20. String query = "SELECT SUM(k.children), AVG(k.children) from Koala k";

21. Query q = em.createQuery(query);

22. Object[] res = (Object []) q.getSingleResult();

Which two statements are correct? (Choose two.)

A If there are no Koala entities in the database, the variable res is set to null after the code exits on line 22.

B If there are no Koala entities in the database, the variable res contains an array of two null values.

Page 29: SCBCD-5 Q&A With Explanations - 2

C If there are no Koala entities in the database, the variable res contains an array holding the values null and 0 respectively.

D If there are Koala entities, the variable res contains an array with values of type Long and Double, respectively.

E This code throws a runtime exception.

Reference

Option B and Option D are correct. An array with two values of types Long and Double, respectively, is returned. (See 4.8.4 of the JPA Specification.) If there are no entities, SUM and AVG return null, respectively.

Option A, C, and E are incorrect because Option A and D are correct. In particular, the JPQL syntax is valid and there is no runtime exception.

Location: ... > Section 8: Java Persistence Query Language > Objective 8.2 > Question 43

A User entity is in a one-to-many relationship with a Book entity. Given an excerpt from the Book entity showing the relationship:

10. @Entity

11. public class Book {

12. @ManyToOne

13. @JoinColumn(name="user_id")

14. private User owner;

15. /* ... */

16. }

Given an excerpt from the User entity showing the relationship:

20. @Entity

21. public class User {

22. @OneToMany(mappedBy="owner", fetch=FetchType.EAGER)

23. Collection<Book> books;

24. }

A developer wants to retrieve all Book entities that are associated with User entities and writes the following query:

SELECT b FROM User u JOIN u.books b

Page 30: SCBCD-5 Q&A With Explanations - 2

Which statement about this query is correct?

A The syntax of this query is invalid.

B The syntax is valid, but the query does NOT return the correct set of books.

C The query works and return the correct set of books.

D The query only works if the metadata for the classes is changed.

Reference

Option C is correct. This is a valid query and indeed returns only those books that are assigned to users. (See 4.4.5.) This is actually an instance of join_collection_valued_path_expression.

Option A is incorrect, the syntax is valid.

Option B is incorrect, the query works as expected.

Option D is incorrect, the query works as expected with the above metadata.

Location: ... > Section 8: Java Persistence Query Language > Objective 8.3 > Question 44

A domain model for a corporation includes a User entity that is in a one-to-many relationship with a Pen entity. A developer wants to select all User entities that have a single Pen.

Which two queries will do this? (Choose two.)

A SELECT u from User u WHERE 1 = ANY(SELECT COUNT(p) from u.pens p)

B SELECT u from User u WHERE ANY(1 = SELECT COUNT(p) from u.pens p)

C SELECT u from User u WHERE 1 = ALL(SELECT COUNT(p) from u.pens p)

D SELECT u from User u WHERE SOME(1 = SELECT COUNT(p) from u.pens p)

E SELECT u from User u WHERE 1 = ANY(SELECT COUNT(u.pens))

Reference Option A and Option C are correct. For the ALL operator, the comparison on the left side of the = operator and all subquery results must be true for the overall condition to be true. In this case the subquery returns the count of the pens for the particular user, so the entire predicate is true when the user has a single pen. For the same reason, the ANY operator will also work in this case. (See 4.6.14 of the JPA Specification.)

Option B is syntactically incorrect. ANY should be part of a predicate. (See the BNF for comparison_expression in 4.14 of the JPA Specification.)

Option D is syntactically incorrect. SOME should be part of a predicate.

Option E is syntactically incorrect. The SELECT statement is NOT complete.

Page 31: SCBCD-5 Q&A With Explanations - 2

Location: ... > Section 8: Java Persistence Query Language > Objective 8.4 > Question 45

A Leopard entity is in a one-to-many bidirectional relationship with a Spot entity. Given an excerpt from the Leopard entity denoting this:

10. @OneToMany(mappedBy="spoton", fetch=FetchType.LAZY)

11. Collection<Spot> spots;

The following code is found in a stateless session bean, intended to delete all leopards:

20. public void removeAllLeopards() {

21. em.createQuery("DELETE FROM Leopard l").executeUpdate();

22. }

Which statement about this code is correct?

A The syntax of the DELETE FROM JPQL statement is invalid.

B The executeUpdate method is the wrong method to call on the Query object under these circumstances.

C It is NOT necessary to execute this code within a transaction.

D A foreign key integrity constraint can cause a PersistenceException

Reference

See 4.10 of JPA Specification.

Option D is correct. A bulk update similar to this maps directly to a database operation. In this case, the Spot entity is in a bidirectional mapping and so foreign keys will exist. As a result, deleting the Leopard records causes a foreign key constraint (depending on database and JPA implementation).

Option A is incorrect. The syntax is fine.

Option B is incorrect. This is the correct way to execute the update. (See 3.6.1 of the JPA Specification.)

Option C is incorrect. The JPA Specification demands that this be executed in a transaction, or else a TransactionRequiredException is thrown. (See 3.6.1 of the JPA Specification.)

Location: ... > Section 8: Java Persistence Query Language > Objective 8.5 > Question 46

Given the following entity bean:

10. @Entity

11. @NamedQuery(name="myname", query="select c from Crumble c where c.id=:val")

12. public class Crumble {

13. @Id private Integer id;

14. }

Page 32: SCBCD-5 Q&A With Explanations - 2

Each of the following Java technology statements create Query objects, where em refers to an entity manager.

Which statement returns a Crumble instance with a primary key of 20?

A em.createNativeQuery("myname").setParameter(1, "val=20")

B em.createNamedQuery("myname").setParameter("val", 20)

C em.createNamedQuery("myname").setParameter(20, 1)

D em.createNamedQuery("myname").setParameter(1, 20)

Reference Option B is correct. (See section 3.6.4 of the JPA Specification.)

Option A, C, and D are incorrect because they use an incorrect syntax for providing the parameter value.

Location: ... > Section 8: Java Persistence Query Language > Objective 8.6 > Question 47

A persistence unit defines a domain model consisting of User and Password entities. Given an excerpt from the Password entity:

10. @Entity

11. @NamedQuery(name="foo", query="select u from User u where size=2")

12. public class Password {

13. @Id private Integer id;

14. /* ... */

20. public void doBusiness() {

21. Query q = em.createNamedQuery("bar");

22. List l = q.getResultList();

23. }

Given an excerpt from the User entity:

40. @Entity

41. @NamedQueries({

42. @NamedQuery(name="bar",

43. query="select u from User u")

44. })

45. public class User {

46. @Id private Integer id;

47. int size;

Page 33: SCBCD-5 Q&A With Explanations - 2

48. /* ... */

49. }

No descriptors are used.

Which statement about this code is correct?

A This compiles and executes without exceptions.

B There is an error on line 11.

C There is an error on lines 41, 42, and 43.

D There is an error on line 21

Reference Option A is correct. (See 3.1.1 and 3.6.4 of the JPA Specification.) Named queries are scoped to a persistence unit. It does not matter that the query foo references User, or that bar is defined on User and used in Password. The query is also created and executed correctly as per 3.1.1.

Option B, C, and D are NOT correct because there are no errors.

Location: ... > Section 9: Transactions > Objective 9.1 > Question 48

Which statement is correct?

A A Java technology client using client-managed transaction demarcation can NOT ensure atomic updates across multiple databases residing at multiple EJB servers.

B The EJB architecture supports flat and hierarchical transactions.

C A stateful session bean using bean-managed transactions must commit the transaction before a business method returns.

D A session bean instance that uses bean-managed transactions must NOT invoke the commit or rollback method on the java.sql.Connection interface.

Reference Option A is incorrect. A Java client can do this. (See 13.2.4 of the Core Specification for an example.)

Option B is incorrect. It only supports flat. (See 13.1.2 of the Core Specification.)

Option C is incorrect. This is true for stateless beans, NOT stateful ones. (See 13.3.3 of the Core Specification.)

Option D is correct. The developer should NOT use resource-manager specific transaction demarcation APIs. (See 13.3.3 of the Core Specification.)

Page 34: SCBCD-5 Q&A With Explanations - 2

Location: ... > Section 9: Transactions > Objective 9.2 > Question 49

Here are two excerpts from the implementation of a session bean:

10. @TransactionAttribute(TransactionAttributeType.REQUIRES_NEW)

11. public class MySuper {

12. public void foo() {}

13. public void zip() {}

14. }

30. @Stateless

31. @TransactionAttribute(TransactionAttributeType.NOT_SUPPORTED)

32. public class MyBean extends MySuper implements MyI {

33. public void foo() {}

34. @TransactionAttribute(TransactionAttributeType.SUPPORTS)

35. public void bar() {}

36. }

No deployment descriptor is used. foo, bar, and zip are business methods defined in interface MyI.

Which statement correctly defines the transaction attributes assigned to the methods foo, bar and zip respectively?

A REQUIRED, SUPPORTS, REQUIRES_NEW

B NOT_SUPPORTED, SUPPORTS, REQUIRES_NEW

C NOT_SUPPORTED, SUPPORTS, NOT_SUPPORTED

D REQUIRES_NEW, SUPPORTS, REQUIRES_NEW

Reference

Option B is correct. (See the rules in 13.3.7.1 of the Core Specification.) foo will be NOT_SUPPORTED because of the class-level attribute and because it overrides. bar will be SUPPORTS because that is the transaction attribute applied to the method. zip will be REQUIRES_NEW because that is the attribute assigned in the superclass and it is NOT overridden. Attributes applied to a superclass only apply to business methods defined in that superclass.

Option A, C, and D are incorrect orders because Option B is the correct one.

Page 35: SCBCD-5 Q&A With Explanations - 2

Location: ... > Section 9: Transactions > Objective 9.3 > Question 50

Which statements about transaction attributes and propagation is correct?

A A message-driven bean's listener methods can only have a REQUIRED, REQUIRES_NEW, or NOT_SUPPORTED transaction attribute.

B An enterprise bean's timeout callback method can only have a REQUIRED, REQUIRES_NEW, or NOT_SUPPORTED transaction attribute.

C An enterprise bean implementing the javax.ejb.SessionSynchronization interface can only have a REQUIRES or REQUIRES_NEW transaction attribute.

D A session bean's business method cannot have a MANDATORY transaction attribute.

Reference

See 13.3.7 where these are explicitly listed.

Option A is incorrect. It cannot have REQUIRES_NEW.

Option B is correct.

Option C is incorrect. It can have MANDATORY too.

Option D is incorrect. There is no restriction on having a MANDATORY attribute.

Location: ... > Section 9: Transactions > Objective 9.4 > Question 51

Given an excerpt from the implementation of a session bean:

10. @Stateful

11. @TransactionAttribute(TransactionAttributeType.REQUIRED)

12. public class GenomeBean implements Me {

13. @TransactionAttribute(TransactionAttributeType.MANDATORY)

14. public void chromosome(String x) {}

15. public void chromosome(String x, String y) {}

16. }

The two chromosome methods are business methods. Here are the transactional settings found in the deployment descriptor for this bean:

10.

11.

12. GenomeBean

13. chromosome

Page 36: SCBCD-5 Q&A With Explanations - 2

14.

15. String

16. String

17.

18.

19. REQUIRES_NEW

20.

21.

22.

23. GenomeBean

24. *

25.

26. SUPPORTS

27.

What are the transactional behaviors placed on the two chromosome methods?

A chromosome(String x) will have a MANDATORY and chromosome(String x, String y) a REQUIRED transactional type.

B chromosome(String x) will have a MANDATORY and chromosome(String x, String y) a MANDATORY transactional type.

C chromosome(String x) will have a SUPPORTS and chromosome(String x, String y) a REQUIRES_NEW transactional type.

D chromosome(String x) will have a SUPPORTS and chromosome(String x, String y) a SUPPORTS transactional type.

E chromosome(String x) will have a SUPPORTS and chromosome(String x, String y) a MANDATORY transactional type.

Reference

Option C is correct. The descriptors override/add to the metadata annotations. In this case, they override both. The transaction tag starting on line 21 ensures that both methods have a SUPPORTS transaction. The transaction tag starting on line 11 overrides this for the chromosome(String x, String y) method because this style takes precedence. (See 13.3.7.2.1 of the Core Specification.)

Options A, B, D, and E are incorrect because they do not follow this setting, as described in Option C.

Page 37: SCBCD-5 Q&A With Explanations - 2

Location: ... > Section 9: Transactions > Objective 9.5 > Question 52

Given an excerpt from a stateful session bean:

10. @Stateful

11. public class MyStatefulBean implements MyStateful, SessionSynchronization {

12. @Resource SessionContext ctx;

13. public void afterCompletion(boolean f) {}

14. public void beforeCompletion() { ctx.setRollbackOnly(); }

15. public void afterBegin() {}

16. @Remove

17. public void inc() {}

18. }

The MyStateful interface is a local business interface that declares inc to be a business method. No deployment descriptor is used. A stateless session bean using container-managed transactions has a business method that acts as a client:

20. @TransactionAttribute(TransactionAttributeType.REQUIRED)

21. public String doIt() {

22. ms.inc();

23. }

The method doIt is called without a transactional context.

Which order properly reflects the order of method invocation?

A doIt, afterBegin, inc

B doIt, inc, afterBegin, beforeCompletion

C doIt, inc, beforeCompletion, afterBegin, afterCompletion

D doIt, inc, afterBegin, beforeCompletion, afterCompletion

E doIt, afterBegin, inc, beforeCompletion, afterCompletion

Reference Option A is correct. doIt is called first, as indicated in the question. Because this is now in a transactional context, the container invokes afterBegin before it invokes the business method. (See 13.6.2.11 of the Core Specification). The business method is annotated with @Remove, so the instance moves to "does NOT exist" immediately, without calling beforeCompletion/afterCompletion. (see Figure 5 and text in 4.4 of the Core Specification.) Option B, C, D, and E do not agree with this order, so they are incorrect.

Page 38: SCBCD-5 Q&A With Explanations - 2

Location: ... > Section 10: Exceptions > Objective 10.1 > Question 53

Which statement is true regarding business method AroundInvoke interceptors in a stateful session bean?

A AroundInvoke methods cannot throw arbitrary system exceptions.

B AroundInvoke methods should NOT suppress exceptions.

C AroundInvoke methods can throw an arbitrary checked exception.

D If a system exception escapes the interceptor chain of AroundInvoke methods, the bean instance is discarded.

Reference See 12.3.2 of the Core Specification for all of these.

Option A is incorrect because they can throw runtime exceptions.

Option B is incorrect because they can suppress exceptions.

Option C is incorrect because they can only throw checked exceptions that the business method that they are intercepting can throw.

Option D is correct.

Location: ... > Section 10: Exceptions > Objective 10.2 > Question 54

Which exception, when thrown in a transactional business method of a session bean (and declared in the throws clause of the method), does NOT cause the transaction to roll back?

A javax.persistence.PersistenceException

B javax.ejb.EJBException

C java.lang.RuntimeException

D java.sql.SQLException

Reference Options A, B, and C are all plain instances of java.lang.RuntimeException. These all cause a transaction to roll back (14.2.2 Core Specification) unless they are application exceptions too, which none of these are.

Option D is an instance of java.lang.Exception and so is considered an application exception (See 14.1.1). This causes a rollback.

Location: ... > Section 10: Exceptions > Objective 10.3 > Question 55

Given some code from a stateful session bean:

10. @Stateful

11. @TransactionAttribute(TransactionAttributeType.REQUIRED)

12. public class USBean implements US {

13. @PreDestroy

Page 39: SCBCD-5 Q&A With Explanations - 2

14. public void slashstar() {}

15. public void oops() {

16. throw new javax.persistence.PersistenceException();

17. }

18. }

It has no descriptor. A client makes a call to oops, which runs in the context of the client's transaction.

What action would you expect the container to perform, if any, after this transaction is thrown?

A The exception is rethrown.

B An EJBException is thrown by the container to the client.

C It discards the instance of the session bean.

D It performs some actions and eventually executes the slashstar method.

E It is the responsibility of the bean provider to properly catch and handle such exceptions.

Reference See Table 14 in 14.3.1 of the Core Specification. According to this:

Option C is correct. The bean will be discarded.

Option A is incorrect. It will NOT because it is NOT an application exception.

Option B is incorrect. It actually throws a TransactionRolledbackException.

Option D is incorrect. PreDestroy methods are not executed. (See Note C in that table and other places in the Specification.)

Option E is incorrect. There is no such requirement put on bean providers.

Location: ... > Section 10: Exceptions > Objective 10.4 > Question 56

Given an interface:

4. @Local

5. public interface MyI {

6. public Set go(Set s);

7. }

Given an excerpt from a stateful session bean that implements this business interface:

9. @Stateful

10. @TransactionAttribute(TransactionAttributeType.REQUIRED)

11. public class MyStatefulBean implements MyI {

12. @Resource SessionContext ctx;

Page 40: SCBCD-5 Q&A With Explanations - 2

13. public Set go(Set s) {

14. ctx.getRollbackOnly();

15. ctx.getEJBOjbect();

16. ctx.getEJBHome();

17. throw new Exception("Will I, won't I?");

18. }

50. }

No deployment descriptor is used.

Which statement is correct?

A An exception is thrown on line 14.

B An exception is thrown on line 15.

C An exception is thrown on line 16.

D An exception is thrown on line 17.

Reference

See Core Specification 4.4.1.

Option A is incorrect because there will be a meaningful transaction context. It is a stateful session bean with a REQUIRED transaction attribute.

Option B is correct. Neither getEJBObject() nor getEJBLocalObject() can be called in this case. Both apply to the EJB 2.x (and earlier) client view, NOT the EJB 3.0

business interface view. The way to get a reference to a 3.0 business interface from the SessionContext is through the getBusinessObject(Class<T> businessInterface).

Option C and Option D are incorrect because an exception is thrown on line 15 (Option B) and so execution never reached any further.

Page 41: SCBCD-5 Q&A With Explanations - 2

Location: ... > Section 10: Exceptions > Objective 10.5 > Question 57

A client, executing in the context of a transaction, makes a call to a session bean and receives a java.rmi.RemoteException.

Which statement is correct?

A The business method has NOT completed.

B The business method has completed, but there was a communication problem after completion.

C The client's transaction might have been marked for rollback.

D The client never receives such an exception. It is always wrapped in another transaction type.

Reference See 14.4.2 for the rules about this.

Option A is incorrect. It is NOT certain that the method has NOT completed. It might have.

Option B is incorrect. It is NOT certain that the method has completed either.

Option C is correct. It might have.

Option D is incorrect. It can, of course, receive a RemoteException.

Location: ... > Section 11: Security Management > Objective 11.1 > Question 58

Given an excerpt from a stateless session bean:

10. @Stateless

11. @RolesAllowed("JAMES")

12. public class YourBean implements MyI {

13. @DenyAll

14. public void spy() { /* ... */}

15. public void eye() { /* ... */ }

14. }

The methods spy and eye are defined in the business interface for this bean. The bean has an accompanying descriptor, and here is an excerpt of the relevant security portion:

<method-permission>

<role-name>BOND</role-name>

<method>

<ejb-name>YourBean</ejb-name>

<method-name>eye</method-name>

</method>

Page 42: SCBCD-5 Q&A With Explanations - 2

Which security roles can access which methods?

A JAMES can access spy and eye.

B BOND can access spy and eye.

C JAMES and BOND can access spy and eye.

D JAMES can access eye, and BOND can access spy.

E JAMES can access eye, no role can access spy.

F BOND can access eye, no role can access spy.

Reference Option F is correct. The RolesAllowed annotation tell us that the security role JAMES can access the bean (all methods). (See 17.3.2.1 of the Core Specification.) DenyAll retracts that permission for the spy method (so nobody can access it). The deployment descriptor overrides the annotation (17.3.2.2) and so only BOND is able to access eye, NOT JAMES.

Option A,B,C,D,E are incorrect because F is correct. See the reasoning for Option F.

Location: ... > Section 11: Security Management > Objective 11.2 > Question 59

Which two roles are responsible for creating or modifying security roles in a bean's annotations or deployment descriptor? (Choose two.)

A Bean Provider

B Application Assembler

C Deployer

D EJB Server Provider

E EJB Container Provider

F System Administrator

Reference Option A and B are correct. (See 17.3.1.) All the other options are incorrect because the correct options are A and B.

Location: ... > Section 11: Security Management > Objective 11.3 > Question 60

Assume ctx is a context object injected into a bean (SessionContext for session beans, EntityContext for entities).

Which business methods throw an exception if a call is made to ctx.getCallerPrinciple()?

A In a business method of a stateless session bean.

B In a PostConstruct annotated method of a stateful session bean.

C In an ejbTimeout method of an entity bean.

D In a PreDestroy annotated method of a stateless session bean.

Page 43: SCBCD-5 Q&A With Explanations - 2

Reference 17.2.5 of the Core Specification states that an exception is thrown if used in an illegal context.

Option A does NOT cause an exception to be thrown. (See Table 2 in 4.5.2 of the Core Specification.)

Option B does NOT cause an exception to be thrown either. (See Table 1 of the Core Specification.) In contrast to stateless beans, this is a meaningful security context.

Option C does NOT cause an exception. (See Table 4, section 8.5.6, of the Core Specification.)

Option D causes an exception. This is not a meaningful security context. (See Table 2 in 4.5.2 of the Core Specification.)

Location: ... > Section 11: Security Management > Objective 11.4 > Question 61

Given an excerpt from a descriptor for a stateless session bean:

10. <session>

11. <ejb-name>EN</ejb-name>

12. <ejb-class>com.sun.ejb.EClassBean</ejb-class>

13. <security-role-ref>

14. <role-name>AGENTN</role-name>

15. <role-link>AGENTL</role-link>

16. </security-role-ref>

17. </session>

If ctx is an injected SessionContext, which of the following calls would you expect to see in the bean implementation given this descriptor?

A ctx.getCallerPrincipal()=="AGENTL"

B ctx.getCallerPrincipal()=="AGENTN"

C ctx.isCallerInRole("AGENTN")

D ctx.isCallerInRole("AGENTL")

Reference

Option C is correct. (See 17.2.5.3 of the Core Specification.)

Option D is incorrect because the role-link links the reference role used in the code (AGENTN) to a real security role (AGENTL in this case).

Option A and B are incorrect because getCallerPrincipal is NOT used in this way. (See 17.2.5.1 of the Core Specification.)