Friday, April 6, 2012

[JAVA] ArrayList from array

It's easy to make array from collection, but visa-versa might look a bit more complicated. But it's not really if you know appropriate static method of certain built-in utility classes. As simple as it can be:

Integer[] arrayOfInts = new Integer[10];

List<Integer> listOfInts = Arrays.asList( arrayOfInts );

Wednesday, April 4, 2012

[JAVA] Captions disappear in NETBEANS 7.0.1 designer

Hello

Probably a little thing, but made me wonder for a while.

Problem: 


In NetBeans 7.0.1 swing designer when you set an Action for a component using Set Action menu option when you right click on the component in designer, after you reload the project in IDE the text caption on the component disappears.

Cause 


This happens because when you set up an action new separate entry gets created in properties file for a text that is going to be shown on the control.

Solution:


  


 In the Set action dialog there is a Text property which you can specify. It's going to be shown on a component.

Sunday, April 1, 2012

[Java] EJB exception while trying to traverse a relationship

Problem: 


Excpetion - Exception Description: An attempt was made to traverse a relationship using indirection that had a null Session. This often occurs when an entity with an uninstantiated LAZY relationship is serialized and that lazy relationship is traversed after serialization. To avoid this issue, instantiate the LAZY relationship prior to serialization.


Cause: 

Let's suppose we have two entity beans, each representing single tables from DB. Let's suppose further that we have one table referencing another table in ONE-to-MANY relationship. For example: Publisher - Book.Entity bean for the Publisher table is going to have a collection of Book objects as it's member. Which is logical as one publisher can have several books under it's production.

Now, let's suppose we have a session bean with a method that returns a Publisher object. If we retrieve that object on the client and then try to get Book collection inside it, the exception mentioned above is going to be thrown

Solution:


In the session bean method before you return the Publisher object you can make persistence provider manually traverse the relationship by calling size() method of Book collection inside.


@Override
  public Publisher getPublisherById(int id) {
try {
  Query query = em.createNamedQuery("Publisher.findById");
  query.setParameter("id", id);
  List<Publisher> pub_list = query.getResultList();
  Publisher b = pub_list .get(0);
  b.getBookCollection().size(); //manually traversing the relationship
    return b;
} catch (Exception ex) {
System.out.println(this.getClass().getName() + ".getAllBomItems:" + ex.getMessage());
}
return null;
}


Or you also can set up EAGER relationships for your persistence provider. But in the case of large database with a lot of relationships it might reduce the performance greatly.