Archive for December 2009

Check your spelling

Why isn’t this working?

That was my question for about a week of frustration.

Answer, I had two different variables misspelled. I won’t be making that mistace again.

Post Ratings: (No Ratings Yet)

Lazy vs. Eager Fetching in Java EE

So you have a relational database and you want to see what Addresses, Phone numbers, or Accounts are associated with a Person. By default, Java EE will only get the objects it absolutely needs; this is called lazy fetching. So solve this problem you want to fetch eagerly. In your code, find the attribute in your entity bean that you want to eagerly fetch and edit the attributes to indicate that it should eagerly fetch the information:

In the Person bean:
@OneToMany(mappedBy="person", fetch=FetchType.EAGER)
private Set accounts;
Obviously there may be some changes you need to make, @OneToOne, @ManyToOne, @ManyToMany, etc. It will vary based on the circumstance.
Post Ratings: (No Ratings Yet)

Query Without Primary Key in Java EE

It is extremely simple to get an entity bean object from a database based on the primary key:

public Person getPerson(String personId) {
 Person aPerson = manager.find(Person.class, personId);
 return aPerson;
}

But what if you don’t have the primary key, like when you want to log in and you only have the userid and the password?
For this you will need to actually write a query, but do not fear, it is very simple:

public Person getPerson(String userid, String password) {
  if(userid == null || password == null) {
   return null;
  }
  try {
   Query q = manager.createQuery("select p from Person p where p.userid = :uid and p.password = :pass");
   q.setParameter("uid", userid);
   q.setParameter("pass", password);

   Person aPerson = (Person) q.getSingleResult();
    if(aPerson == null) {
     return null;
    }
    return aPerson;
   }
  catch (Exception e) {
   return null;
  }
}

Post Ratings: (No Ratings Yet)

Comparing Two Collections

This is a valuable piece of code that I am sure I’ll be using in the future:

public boolean isSame(Collection expected, Collection actual) {
 /* first compare the sizes, if they are not the same there is no use in going further */
 if(expected.size() != actual.size()) {
  return false;
 }
 /* the count variable will increment for each match */
 int count = 0;
 /* The iterators check each object in each Collection */
 for (Iterator iterator = expected.iterator(); iterator.hasNext();) {
  Object object = (Object) iterator.next();
  for (Iterator iterator2 = actual.iterator(); iterator2.hasNext();) {
   Object object2 = (Object) iterator2.next();
   if(object2.equals(object)) {
    count++;
   }
  }
 }

 /* the count variable is the same as the size of the Collections then all items match */
 if (count != expected.size()) {
  return false;
 }
 else {
  return true;
 }
}
I wrote it to check if an expected Set was the same as an actual Set. I chose to use a Collection to make it more generic, and since a Set is a Collection it will still work.
Post Ratings: (No Ratings Yet)

Connecting Entity Beans to Set/Retrieve Data

I’ve spent the last week figuring this out, ultimately I had one line that was wrong.
When you have the database set up, and the entity beans in an EJB project, how do you connect to the server to access or update data?
  1. You should have two classes set up in your EJB project: BusinessRules.java, BusinessRulesRemote.java (or whatever you chose to call them). These files have a special method to construction, follow the list below.
    1. Secondary click the EJB project and select New > Session Bean
    2. Enter the package and class name (I chose “session” and “BusinessRules”)
    3. If you want to use a remote interface (best for scalability) you will need to select it. You may leave the local interface (best for performance) button checked or you may uncheck it, I unchecked it.
    4. Click finish.
  2. Edit your BusinessRules.java and BusinessRulesRemote.java class.
    1. Now you need to implement your business logic.

      @Stateless /*These business rules are stateless.*/
      public class BusinessRules implements BusinessRulesRemote { /*class header*/
      @PersistenceContext /*If you are using Java EE then you will need this to get the Persistent context*/
      EntityManager manager; /*The manager you'll be using*/
      
      public static final String REMOTEJNDINAME = BusinessRules.class.getSimpleName() + "/remote"; /*JNDI name so that the class can be found*/
      
      public BusinessRules() { //Default constructor
      }

Note: if you use @PersistenceUnit instead of @PersitenceContext it will not work.
You will need to have methods in the BusinessRules class in order to access your data. Here is an example of how to select a person using their primary key (continued from the code above):

public Person getPerson(String personId) {
 Person aPerson = manager.find(Person.class, personId);
 return aPerson;
}

After you do this you will just need to call an instance of your BusinessRules class (businessRules) and then call methods (e.g. businessRuless.getPerson("1");)

In order to get an Object Person as an entity from your database based on their username and password you will want to overload your method in BusinessRules (or just not use the former method since it isn’t very practical) and write a query using EJB QL. Example (continued from code above):

public Person getPerson(String userid, String password) {
 Query q = manager.createQuery("select p from Person p where p.userid = :uid and p.password = :pass");
 q.setParameter("uid", userid);
 q.setParameter("pass", password);
 Person aPerson = (Person) q.getSingleResult();
 return aPerson;
}

Resources: Sun, Enterprise JavaBeans 3.0 5th Edition 2006 Bill Burke & Richard Monson-Haefel
Post Ratings: (No Ratings Yet)