Showing posts with label Spring. Show all posts
Showing posts with label Spring. Show all posts

Thursday, May 10, 2012

Too L@zy for Debug

If you use JPA in your application and have @Lazy fetching on your Entities properties, please note that debugging might be impossible.

for example:
@Entity
public class Order[
@OneToMany(fetch=FetchType.LAZY,mappedBy = "order")
Set items;
//...
}
I encounter the issue with Spring IDE (STS 2.9), Spring 3.1 and JUnit 4.
When running a JUnit test  against the Service layer which needed to read lazy properties - same line of code (the invocation of a Lazy property) failed on Debug (exception) however succeeded on Run mode.

The problematic line is something like that:
Order order = getOrderById(orderId);
order.getItems(); // Exception on debug

Black magic indeed.

Hope this save time to someone..



Saturday, April 14, 2012

Judgement day weapon for circular autowiring dependency error

On recent post I demonstrated a way to resolve circular dependency error.
However, sometimes, even the mentioned solution  is not enough and redesign is not possible.

I would like to suggest a solution of Dependency Injection which will be as much loyal as possible to the Spring IoC way and will help to overcome the circular dependency error.

This means that we will have a single class that will have a reference to all the classes which need to be injected and will be responsible for the injection.

I'll try to walk you through the steps.

Assuming we have the following service classes which cause the circular error:

@Service
public class ServiceA{

@Autowire
ServiceB serviceB;
@Autowire
ServiceC serviceC;

}

@Service
public class ServiceB{

@Autowire
ServiceA serviceA;
@Autowire
ServiceC serviceC;
}

First step is to remove the @Autowire annotations, so we will move the wiring responsibility out of Spring hands.

Second step is to create a class which will hold a reference to all the classes to inject.
Such as:
@Component
public class BeansManager{

@Autowire
private ServiceA serviceA;
@Autowire
private ServiceB serviceB;
@Autowire
private ServiceC serviceC;

get...
set... 
}


Third step is to create an interface name Injectable with method inject.
public interface Injectable{
public void inject(BeansManager beansManager);
}


Forth step is to set each service class/interface to implement the injectable interface.

e.g. :

@Service
public class ServiceA implements Injectable{

ServiceB serviceB;
ServiceC serviceC;
//method to inject all the beans which were previously were injected by Spring
public void inject(BeansManager beansManager){
this.serviceB =  beansManager.getServiceB();
this.serviceC = beansManager.getServiceC(); 
}

}


Fifth and final step is to set the BeansManager to be ready for the injection.
But take a moment to think -
It's obvious that we need  a reference of all the classes which need to be injected in the BeansManager, however, how can we make sure that the following sequence is maintained:
1. All Service classes are initiated
2. BeansManager is initiated with all the services injected by Spring
3. After BeansManager initiated and exist in its steady state, call all the service classes which need injection and inject the relevant service.

Step 3 can be achieved by a method which executed after constructor finished (via @PostConstruct annotation), however the big question here is how to make sure the BeansManager is initiated last? (after all the relevant services are initiated)
The trick is to have @Autowire on the Injectable set. This way Spring will make sure that:
a. All the injectable classes are subscribed to the BeansManager for the injection
b. The BeansManager will be initiated last (after all injectable services are initiated)

public class BeansManager

//This line will guarantee the BeansManager class will be injected last
@Autowired
private Set<Injectable> injectables = new HashSet();

//This method will make sure all the injectable classes will get the BeansManager in its steady state,
//where it's class members are ready to be set
@PostConstruct
private void inject() {
   for (Injectable injectableItem : injectables) {
       injectableItem.inject(this);
   }
}

}

Make sure you understand all the magic that happened in the fifth step, it's really cool.

Note:
If you think on a way to implement even more generic mechanism that will achieve the same, please drop me a note.

Good luck!

acknowledgement:
http://stackoverflow.com/questions/7066683/is-it-possible-to-guarantee-the-order-in-which-postconstruct-methods-are-invoke

Friday, January 20, 2012

Advanced QBE pattern (common using generics)

On previous post I introduced the QBE pattern.

The pattern saves us a lot of tedious binding code.
However, one still need to implement the same method for each Entity.

To save us the redundant work of defining the same QBE method for each entity, where only the entity is changed, we could utilize Generics.

Using Generics we will implement only one method in a base class, and each concrete QBE (on certain @Entity) will inherit from that base class.


Lets see that in action.

First, we define the interface for the base class:

public interface BaseDAO {

   

    /**
     * Perform a query based on the values in the given object.
     * Each (String) attribute will be searched based on the Like comparison.
     * Comply the QueryByExample (QBE) pattern
     * @param modelEntity The Entity with values to search
     * @param propertiesToExclude Any property which the search will ignored.
     * @return Instances that answer the given parameters values (empty if none)
     */
    public List getByElementsLike(T modelEntity, List propertiesToExclude);   

    /**
     * Perform a query based on the values in the given object.
     * Each attribute will be searched based on the Equality comparison.
     * Comply the QueryByExample (QBE) pattern
     * @param modelEntity The Entity with values to search
     * @param propertiesToExclude Any property which the search will ignored
     * @return Instances that answer the given parameters values (empty if none)
     */
    public List getByElementsEqual(T modelEntity, List propertiesToExclude);

}



 Second step is to write the Base class implementation

public class BaseDaoImpl implements BaseDAO {
//Get DB session access using Spring 3.1 Entity Manger
     @PersistenceContext
    protected EntityManager em;
  
    protected Class entityClass;

   
     //Initialize the entity class
     @SuppressWarnings("unchecked")
    public BaseRepositoryImpl() {
            ParameterizedType genericSuperclass = (ParameterizedType) getClass().getGenericSuperclass();
            this.entityClass = (Class) genericSuperclass.getActualTypeArguments()[0];
        }

    protected Class getEntityClass() {
        return entityClass;
    }   
  

    public List getByElementsLike(T modelEntity,List propertiesToExclude) {

        // get the native hibernate session
        Session session = (Session) em.getDelegate();

        // create an example from our model-entity, exclude all zero valued numeric properties
        Example example = Example.create(modelEntity).excludeZeroes().enableLike(MatchMode.ANYWHERE);

        for (String property : propertiesToExclude) {
            example.excludeProperty(property);
        }       

        // create criteria based on the customer example
        Criteria criteria = session.createCriteria(getEntityClass()).add(example);

        // perform the query       
        return criteria.list();

    }

    public List getByElementsEqual(T modelEntity,List propertiesToExclude) {

        // get the native hibernate session
        Session session = (Session) em.getDelegate();

        // create an example from our customer, exclude all zero valued numeric properties
        Example example = Example.create(modelEntity).excludeZeroes();

        for (String property : propertiesToExclude) {
            example.excludeProperty(property);
        }   

        // create criteria based on the customer example
        Criteria criteria = session.createCriteria(getEntityClass()).add(example);

        // perform the query       
        return criteria.list();
    }

}


Third step is to extend the base class:
@Entity

public class Order{
..
}

 

@Entity
public class Item{
..
}

 
public class OrderDaoImpl extends BaseDaoImpl implements
        BaseDao{

//No need to implement the QBE again here

}

public class ItemDaoImpl extends BaseDaoImpl implements
        BaseDao{

//No need to implement the QBE again here

}


Kindly let me know for any further improvements.

Thursday, December 29, 2011

Unit Test on Spring via Maven - configuration tips



 This post is for newbies who set their project to run Spring powered Unit Tests via Maven.

There are many blogs who mention how to do it.
I would recommend to install STS IDE and create new Spring Template project.
It usually comes with built in Test package. The test package can be executed via JUnit.

The tricky part comes when you want to run the tests via Maven and set the Spring configuration xml file in your custom folder.

Using default setting, Maven might raise an exception complaining the Spring xml configuration file could not be found or Tests could not be found.

So, my two cents are:
cent 1: Make sure your test classes ends with Test (and not ending with Tests, for example, as it comes with the Spring default project)
cent 2: configuration can be resolved while defining the spring configuration path.
 The trick is to use the relative location as it is in the source folder, and not in the target compilation folder. Also note to use backslash as folder separation and not dots.

Configuration using classpath relative path:

@ContextConfiguration (value = "classpath:/com/company/app/OrderPersistenceTests-context.xml")

 @RunWith(SpringJUnit4ClassRunner.class)

public class OrderPersistenceTest {

...

}

or

Configuration using project relative path:

@ContextConfiguration (value = "file:src/test/resources/com/company/app/OrderPersistenceTests-context.xml ") 
@RunWith(SpringJUnit4ClassRunner.class)
public class OrderPersistenceTest {



...

} 


Run tests using maven:
If pom.xml has the skipTest tag with true as value, e.g.:

       

            

                org.apache.maven.plugins

                maven-surefire-plugin

                2.6

                 

                1.5

                1.7

               true

            

            

...


...

Then no test will be executed, even when explicitly executing maven with test goal


Good luck !