Wednesday December 21, 2005 Primary key generation in EJB 3.0blo I and John Jullion-Ceccarelli wrote a tutorial about primary key generation in EJB 2.1. It was very pretty painful stuff, you should create table with appropriate data type column, use Object primary key and other. In EJB 3.0 is generation of PK different, it's easy to use. Let's go through all options that are for this in EJB 3.0. Primary key you can define in Entity bean with @Id annotation. There are five options for GeneratorType: NONE, AUTO, IDENTITY, SEQUENCE and TABLE. First one is NONE, it means that application is responsible for generation of primary key. Next one is AUTO that leaves the job to the container. This strategy indicates that a persistence provider should pick up appropriate strategy according to the database. It means that you need not setup your id and container generates it. I would like to describe SEQUENCE and TABLE strategy in more details below. SEQUENCE or IDENTITY strategy use a database sequence or identity column. I will show this strategy for Oracle database. We need to create new sequence with this command:
CREATE SEQUENCE EMPL_ID INCREMENT BY 1 START WITH 100;
Then, this sequence can be used in entity bean like this:
@Id(generate=GeneratorType.SEQUENCE, generator="EMPL_GEN")
@SequenceGenerator(name="EMPL_GEN",sequenceName="EMPL_ID")
The sequenceName attribute specifies name of sequnce object in database. For TABLE strategy we should create table in database where primary keys will be stored:
CREATE TABLE GEN_ID(
GEN_KEY VARCHAR(20),
GEN_VALUE INTEGER,
PRIMARY KEY(GEN_KEY))
Then you can use this table in entity bean with TABLE generator strategy:
@Id(generate=GeneratorType.TABLE,generator="ORDER_GEN")
@Column(name="ID")
@TableGenerator(name="ORDER_GEN",pkColumnName="GEN_KEY",
pkColumnValue="ORDER_ID",allocationSize=1,
initialValue=1,valueColumnName="GEN_VALUE",
table=@Table(name="GEN_ID"))
All attributes are very intuitive and can be guessed from this sample.
Generation of primary key in EJB 3.0 is simple, isn't it?
Posted by pblaha
( Dec 21 2005, 06:07:37 PM CET )
Permalink
EJB 3.0 client in J2SE project Today, I would like to show how you can create client for EJB 3.0 in J2SE project. First, we will need to create a bean with remote interface. Since, we are using EJB 3.0 this is very simple. Create business interface with Remote annotation and then create bean's implementation class of your bean and specify JNDI name of this bean:
@Stateless(name="ejb/ProcessHello")
public class ProcessHelloBean implements org.netbeans.ProcessHello {
public void String getHello(){
....
Now, we have two ways how to create client. First one is using Application Client Container (ACC) and second one is without that. What is advantage of the ACC? ACC can be seen as lightweight container that is responsible for security, naming, communication with application server and especially for injection. However, the worse of this approach is that you need run your application with appclient launcher. The client that
uses ACC can be written like:
@EJB(name="ejb/ProcessHello")
private org.netbeans.ProcessHello hello;
hello.getHello();
Then you need to run your client's jar with launcher appclient -client
InitialContext ctx = new InitialContext();
Object obj = ctx.lookup("org.netbeans.ProcessHello");
ProcessHello hello = (TestTableRemote)PortableRemoteObject.narrow(obj, ProcessHello.class);
hello.getHello();
In this sample I used default JNDI name that is fully qualified classname of the remote business interface (3.0) or remote home interface (2.x). If you want to change the JNDI name use mappedName attribute for @Stateless.
Posted by pblaha
( Dec 19 2005, 06:11:29 PM CET )
Permalink
Comments [5]
Persistence in J2SE project The big advantage of the EJB 3.0 is using entity beans out of container. This new feature will allow to test your business objects outside of application server. I would like to show how you can write simple J2SE project that uses EntityManager in NetBeans 5.0. Let's create new J2SE project in NetBeans.
<persistence xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="pu1">
<!-- Provider class name is required in Java SE -->
<provider>oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider</provider>
<!-- All persistence classes must be listed -->
<class>persistence.Product</class>
<properties>
<!-- Provider-specific connection properties -->
<property name="jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="jdbc.connection.string" value="jdbc:mysql://localhost:3306/EJB"/>
<property name="jdbc.user" value="blaha"/>
<property name="jdbc.password" value="passw"/>
<!-- Provider-specific settings -->
<property name="toplink.logging.level" value="INFO"/>
</properties>
</persistence-unit>
</persistence>
36 EntityManagerFactory emF = Persistence.createEntityManagerFactory("pu1"); 37 EntityManager em = emF.createEntityManager(); 38 EntityTransaction tx = em.getTransaction(); 39 tx.begin(); 40 Product product = new Product(); 41 product.setId(1); 42 product.setPartNumber("ADSD-64464"); 43 product.setDescription("HAMMER"); 44 product.setPrice(12); 45 em.persist(product); 46 tx.commit(); 47 48 // try to find product 49 Query query = em.createQuery("select p from Product p where p.description =:descr"); 50 query.setParameter("descr","hammer"); 51 List results = query.getResultList(); 52
How to use EntityManager API in web module The javax.persistence.Entitymanager API is used for creating, finding and updating entity bean instances. I would like to show how EntityManager can be used in web module. I will focus only to Glassfish implementation. I know that Oracle App server uses a little bit different approach. They use EntityManager that is bind to java:comp/ejb/<module-name>/EntityManager.
First, some actions with EntityManager API are required to be used in a transaction, so the web module must manually demarcate the transaction using the UserTransaction API.
In objects that are managed by container like servlets, JSF beans and EJB bean you can use simple injection. Following sample explains how to use EntityManager in servlet:
@PersistenceContext
EntityManager em;
@Resource
UserTransaction tx;
....
tx.begin();
em.persist(new YourObject());
tx.commit();
This approach can't be used in helper or business delegate classes. There, we should lookup theEntityManager and the UserTransaction using the JNDI binding:
InitialContext ctx = new InitialContext();
UserTransaction tx = (UserTransaction)ctx.lookup("UserTransaction");
EntityManager em = em = (EntityManager) ctx.lookup("java:comp/env/persistence/EntityManager");
tx.begin();
YourObject o1 = em.merge(yourObject); // merge object to the new context
em.remove(o1);
tx.commit();
You'll need to define a persistence-context-ref for the component environment in which your class will run. It means add these elements in your web.xml file in web-app element:
<persistence-context-ref>
<persistence-context-ref-name>persistence/EntityManager</persistence-context-ref-name>
<persistence-unit-name>unitName</persistence-unit-name>
</persistence-context-ref>
Posted by pblaha
( Dec 14 2005, 05:47:22 PM CET )
Permalink
Comments [1]
Develop Custom Realm in NetBeans I will write simple custom realm for Sun Application server in NetBeans. This realm will be used for authentication of users. I will implement very simple realm that will check password that are stored in Hashtable. I guess, extending this realm for using JDBC or other technology is easy task.
Implementation involves the following three steps:
<!DOCTYPE project [<!ENTITY RealmTargets SYSTEM "realm-targets.xml">]>
.......
&RealmTargets;
How to use CMP beans with generated primary key I saw a question about using CMP beans with generated primary key. Therefore, I decided to write one simple application that can explain how to use this feature. More info about generating primary key values in CMP beans is avalaible here here. I would like to note that the user should never rely on the internals of the container code. And if the user chooses to use a generated PK for CMP, it means they do not care about the value, and should not try to access it (other
than as an Object).
In this post we will develop EJB module that creates product and purchase order. See Entity relationship diagram:
CREATE TABLE PRODUCT(
ID BIGINT(19) NOT NULL,
PART_NUMBER VARCHAR(19) UNIQUE NOT NULL,
DESCRIPTION VARCHAR(25),
PRICE FLOAT,
PRIMARY KEY (ID),
INDEX PART_NUMBER (PART_NUMBER)
);
CREATE TABLE PURCHASEORDER(
ID BIGINT(19) NOT NULL,
CUSTOMER VARCHAR(20) NOT NULL,
PRODUCT_ID BIGINT(19) NOT NULL,
AMOUNT FLOAT,
PRIMARY KEY (ID),
INDEX CUST (CUSTOMER),
FOREIGN KEY (PRODUCT_ID) REFERENCES PRODUCT(ID))
Primary key column should be mapped to column with NUMERIC data type with a precision of 19 or more.
public void createProduct(String partNr, String description, float price) throws EJBException {
try {
productHome.create(partNr,description, new Float(price));
} catch (CreateException ex) {
ex.printStackTrace();
throw new EJBException(ex.getMessage());
}
}
public void createOrder(String customer, String partNr, float amount) throws EJBException {
try {
ProductLocal product = productHome.findByPartNumber(partNr);
purchaseHome.create(customer,new Float(amount),product);
} catch (FinderException ex) {
ex.printStackTrace();
throw new EJBException(ex.getMessage());
}catch(CreateException ex){
ex.printStackTrace();
throw new EJBException(ex.getMessage());
}
}
LDAP authentication in Sun Application server Today, I would like to describe the steps to enable LDAP authentication in web module that is deployed in Sun Application server. Authentication is the way an entity determines that another entity is who it claims to be.
Very important for understanding security for SJAS is Realm. A realm, also called a security policy domain or security domain, is a scope over which the server defines and enforces a common security policy. In practical terms, a realm is a repository where the server stores user and group information. The Application Server comes pre-configured with three realms: file (the initial default realm), certificate, and admin-realm. In this post we will add and setup new ldap realm.
I will use open source implementation of the Lightweight Directory Access Protocol server that is avalaible here.
dn: uid=blaha,ou=people,dc=netbeans,dc=cz
uid: blaha
givenName: blaha
objectClass: top
objectClass: person
objectClass: organizationalPerson
objectClass: inetorgperson
sn: blaha
cn: Petr Blaha
userPassword: {SSHA}Z9RXgOsVA6395NtLw6ot7XjkO3dJAeUIqDdWdA==
The entry should have defined uid attribute. The container will search entry according to this attribute during authentication.
<form method="POST" action="j_security_check">
Username: <input type="text" name="j_username"/>
Password: <input type="password" name="j_password"/>
<input type="submit" value="Submit"/>
18 <security-role> 19 <role-name>USER</role-name> 20 </security-role> 21 22 <security-constraint> 23 <web-resource-collection> 24 <web-resource-name>protected area</web-resource-name> 25 <url-pattern>/index.jsp</url-pattern> 26 <http-method>GET</http-method> 27 <http-method>POST</http-method> 28 </web-resource-collection> 29 <auth-constraint> 30 <role-name>USER</role-name> 31 </auth-constraint> 32 </security-constraint> 33 34 <login-config> 35 <auth-method>FORM</auth-method> 36 <realm-name>ldaprealmperapp</realm-name><!-- name of LDAP realm--> 37 <form-login-config> 38 <form-login-page>/login.jsp</form-login-page> 39 <form-error-page>/error.jsp</form-error-page> 40 </form-login-config> 41 </login-config>
Hibernate plugin for NetBeans 5.0 Many developers don't like EJB, JDO technologies and they are using other object/relational persistance and query service for Java like Hibernate. Hibernate lets you develop persistant classes following common Java idiom. The plugin for Hibernate in NetBeans was missing. Recently, I have seen on project of my colleague.
Petr Zajac develops xdoclet plugin for NetBeans that enables Attribute-Oriented Programming for Java. The plugin parses your source code and generates many artifacts such as XML and other stuff. Based on this plugin he did Hibernate plugin.
This plugin allows you to create new POJO beans, add relationships, fields, ....code completion