So recently i just surpassed the 5+ year mark in my career. So i dwelled upon my journey so far and wanted to pen it down ( well key it down in this instance :) ). And this is how my story goes;
Just after Uni, i started working at a start up company specializing in stock trading applications. Even today if someone asked me what was the most challenging thing you have worked on, this company will always be in the top 10. After uni, for a guy looking for a challenging career, this was just what the doctor ordered. Loved every bit of work, and also the people were very courteous and helpful in every way. From the CEO to architect to the tech leads, if you ever needed help with anything, they were always there for me.
Got my very first & only taste of C++ right in this very company. Now that was one heck of a language i must say. Keeps you thinking of every intrinsic detail. Of course looking back it might be overkill comparing with some languages now, but hey for a person just out of Uni, these are interesting stuff. Though i had an apprehensive nature on joining, the people at this company really made it easy for me to settle down.
Thoroughly enjoyed the late nights, trying to figure out why something that seems fine is just not working on production, learnt what true team work is all about.
Then came the time for me to move in pursuit of better opportunities, though my heart up until this date is still with this company because the people there were such fun loving people. The CEO was the key role whom i still look up for. My idol in the local IT sector.
One thing i never stopped was learning. Continuous learning is what keeps your value on par with the industry. If you lose your value, then your not an asset to the company any more. I wont say you should go and learn every technology or language that pops up in the news, but its more or less like engaging in the stock market. If you are not in the know of the stock movements, your bound not to capitalize on the opportunities that might arise in the future.
Few things i have observed on my journey is that often time many people focus just on the money factor. They enter the industry thinking it is a one stop stairway way to wealth. Don't get me wrong, money is important, but entering the software industry with just money being your goal and sole purpose will not take you much far.
What i always believe in is that you should learn from each experience, and with experience and time, money will come. Some people give me this incredulous look when i say that to them. But that reality i have lived is what i tell them. Believing it or not is up to them :).
And then i meet a few rock stars who are solid and sound technical people, but lack communication skills or most often have a very bad case of Asperger syndrome. Often times i see these people rise up early in their career but then be victims of ostracism due to the fact that they just do not understand that at the end of the day, without a team effort, a company will not thrive.
One thing i always believe is humility. This was one of the many gifts i inherited from my father. No matter how far you may go, you should never forget how you got there. A very important saying my father taught me was
"Be careful not to step on others' toes on your way up,
You do not know who you will meet on your way down ".
Another version goes as;
""Be careful whose toes you step on today because
they might be connected to the foot that kicks your ass tomorrow!!"
-Brandon Ramos"
No matter what you achieve in life, what i believe is that the world holds together because of the love and relationships we have with each other we meet on our journey through life.
I give my 100% to anything i set my heart to because it is when you truly believe in something that you will actually set out to achieve it. And so continues my life in the software industry with many more challenges ahead which i gladly look forward to.
All i can say is that it has been one heck of a ride up until now, and what ever path God chose for me i shall walk since "I can do all things through Christ who strengthens me. Philippians 4:13"
Have a great day everyone... Take care and God bless
Monday, October 1, 2012
Monday, August 20, 2012
Lazy/Eager loading using hibernate by example
Today's post will focus on why and how we use the concepts known as LAZY and EAGER loading in an application and how to use Spring's hibernate template to load our LAZY entities in an EAGER fashion.
And of course as the title itself suggests, we will show this by an example. The scenario is as such;
You are a parent who has a kid with a lot of toys. But the current issue is whenever you call him (we assume you have a boy), he comes to you with all his toys as well. Now this is an issue since you do not want him carrying around his toys all the time.
So being the rationale parent, you go right ahead and define the toys of the child as LAZY. Now whenever you call him, he just comes to you without his toys.
But you are faced with another issue. When the time comes for a family trip, you want him to bring along his toys because the kid will be bored with the trip otherwise. But since you strictly enforced LAZY on the child's toy, you are unable to ask him to bring along the toys. This is where EAGER fetching comes into play. Let us first see our domain classes.
The second method retrieves the Child by the primary key passed in, but does not fetch the toys.
The third method first fetches the Child and then retrieves the Child's toys using the Hibernate template's initialize() method. Note that when you call the initialize() method, hibernate will fetch you LAZY defined collection to the Child proxy you retrieved.
The final method also retrieves the Child's toys, but this time using a named query. If we go back to the Child entity's Named query, you can see that we have used "left join fetch". It is the keyword fetch that actually will initialize the toys collection as well when returning the Child entity that qualifies. Finally i have my main class to test our functionality;
That is about it for today. For anyone who wants to try out the example, i have uploaded it here.
Thank you for reading, and hope you have a great day. Cheers!!
And of course as the title itself suggests, we will show this by an example. The scenario is as such;
You are a parent who has a kid with a lot of toys. But the current issue is whenever you call him (we assume you have a boy), he comes to you with all his toys as well. Now this is an issue since you do not want him carrying around his toys all the time.
So being the rationale parent, you go right ahead and define the toys of the child as LAZY. Now whenever you call him, he just comes to you without his toys.
But you are faced with another issue. When the time comes for a family trip, you want him to bring along his toys because the kid will be bored with the trip otherwise. But since you strictly enforced LAZY on the child's toy, you are unable to ask him to bring along the toys. This is where EAGER fetching comes into play. Let us first see our domain classes.
package com.fetchsample.example.domain;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;
import javax.persistence.Table;
/**
* Holds information about the child
*
* @author dinuka.arseculeratne
*
*/
@Entity
@Table(name = "CHILD")
@NamedQuery(name = "findChildByName", query = "select DISTINCT(chd) from Child chd left join fetch chd.toyList where chd.childName=:chdName")
public class Child {
public static interface Constants {
public static final String FIND_CHILD_BY_NAME_QUERY = "findChildByName";
public static final String CHILD_NAME_PARAM = "chdName";
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
/**
* The primary key of the CHILD table
*/
private Long childId;
@Column(name = "CHILD_NAME")
/**
* The name of the child
*/
private String childName;
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
/**
* The toys the child has. We do not want the child to have the same toy more than
* once, so we have used a set here.
*/
private Set<Toy> toyList = new HashSet<Toy>();
public Long getChildId() {
return childId;
}
public void setChildId(Long childId) {
this.childId = childId;
}
public String getChildName() {
return childName;
}
public void setChildName(String childName) {
this.childName = childName;
}
public Set<Toy> getToyList() {
return toyList;
}
public void addToy(Toy toy) {
toyList.add(toy);
}
}
package com.fetchsample.example.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
/**
* Hols data related to the toys a child possess
*
* @author dinuka.arseculeratne
*
*/
@Entity
@Table(name = "TOYS")
public class Toy {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "TOY_ID")
/**
* The primary key of the TOYS table
*/
private Long toyId;
@Column(name = "TOY_NAME")
/**
* The name of the toy
*/
private String toyName;
public Long getToyId() {
return toyId;
}
public void setToyId(Long toyId) {
this.toyId = toyId;
}
public String getToyName() {
return toyName;
}
public void setToyName(String toyName) {
this.toyName = toyName;
}
@Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((toyName == null) ? 0 : toyName.hashCode());
return result;
}
@Override
/**
* Overriden because within the child class we use a Set to
* hold all unique toys
*/
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Toy other = (Toy) obj;
if (toyName == null) {
if (other.toyName != null)
return false;
} else if (!toyName.equals(other.toyName))
return false;
return true;
}
@Override
public String toString() {
return "Toy [toyId=" + toyId + ", toyName=" + toyName + "]";
}
}
So as you can see, we have two simple entities representing the child and toy. The child has a one-to-many relationship with the toys which means one child can have many toys (oh how i miss my childhood days).
Afterwards we need to interact with the data, so let us go ahead and define out DAO(Data access object) interface and implementation.
package com.fetchsample.example.dao;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.fetchsample.example.domain.Child;
/**
* The basic contract for dealing with the {@link Child} entity
*
* @author dinuka.arseculeratne
*
*/
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public interface ChildDAO {
/**
* This method will create a new instance of a child in the child table
*
* @param child
* the entity to be persisted
*/
public void persistChild(Child child);
/**
* Retrieves a child without his/her toys
*
* @param childId
* the primary key of the child table
* @return the child with the ID passed in if found
*/
public Child getChildByIdWithoutToys(Long childId);
/**
* Retrieves the child with his/her toys
*
* @param childId
* the primary key of the child table
* @return the child with the ID passed in if found
*/
public Child getChildByIdWithToys(Long childId);
/**
* Retrieves the child by the name and with his/her toys
*
* @param childName
* the name of the child
* @return the child entity that matches the name passed in
*/
public Child getChildByNameWithToys(String childName);
}
package com.fetchsample.example.dao.hibernate;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.fetchsample.example.dao.ChildDAO;
import com.fetchsample.example.domain.Child;
/**
* The hibernate implementation of our {@link ChildDAO} interface
*
* @author dinuka.arseculeratne
*
*/
public class ChildDAOHibernateImpl extends HibernateDaoSupport implements
ChildDAO {
/**
* {@inheritDoc}
*/
public void persistChild(Child child) {
getHibernateTemplate().persist(child);
}
/**
* {@inheritDoc}
*/
public Child getChildByIdWithoutToys(Long childId) {
return getHibernateTemplate().get(Child.class, childId);
}
/**
* {@inheritDoc}
*/
public Child getChildByIdWithToys(Long childId) {
Child child = getChildByIdWithoutToys(childId);
/**
* Since by default the toys are not loaded, we call the hibernate
* template's initialize method to populate the toys list of that
* respective child.
*/
getHibernateTemplate().initialize(child.getToyList());
return child;
}
/**
* {@inheritDoc}
*/
public Child getChildByNameWithToys(String childName) {
return (Child) getHibernateTemplate().findByNamedQueryAndNamedParam(
Child.Constants.FIND_CHILD_BY_NAME_QUERY,
Child.Constants.CHILD_NAME_PARAM, childName).get(0);
}
}
A simple contract. I have four main methods. The first one of course just persists a child entity to the database.The second method retrieves the Child by the primary key passed in, but does not fetch the toys.
The third method first fetches the Child and then retrieves the Child's toys using the Hibernate template's initialize() method. Note that when you call the initialize() method, hibernate will fetch you LAZY defined collection to the Child proxy you retrieved.
The final method also retrieves the Child's toys, but this time using a named query. If we go back to the Child entity's Named query, you can see that we have used "left join fetch". It is the keyword fetch that actually will initialize the toys collection as well when returning the Child entity that qualifies. Finally i have my main class to test our functionality;
package com.fetchsample.example;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.fetchsample.example.dao.ChildDAO;
import com.fetchsample.example.domain.Child;
import com.fetchsample.example.domain.Toy;
/**
* A test class
*
* @author dinuka.arseculeratne
*
*/
public class ChildTest {
public static void main(String[] args) {
ApplicationContext context = new ClassPathXmlApplicationContext(
"com/fetchsample/example/spring-context.xml");
/**
* First we initialize a child
*/
Child child = new Child();
/**
* A cool ben 10 action figure
*/
Toy ben10 = new Toy();
ben10.setToyName("Ben 10 figure");
/**
* A even more cooler spider man action figure
*/
Toy spiderMan = new Toy();
spiderMan.setToyName("Spider man figure");
child.setChildName("John");
/**
* Add the toys to the collection
*/
child.addToy(ben10);
child.addToy(spiderMan);
ChildDAO childDAO = (ChildDAO) context.getBean("childDAO");
childDAO.persistChild(child);
Child childWithoutToys = childDAO.getChildByIdWithoutToys(1L);
// The following line will throw a lazy initialization error since we have
// defined fetch type as LAZY in the Child domain class.
// System.out.println(childWithToys.getToyList().size());
Child childWithToys = childDAO.getChildByIdWithToys(1L);
System.out.println(childWithToys.getToyList().size());
Child childByNameWithToys = childDAO.getChildByNameWithToys("John");
System.out.println(childByNameWithToys.getToyList().size());
}
}
Defining your base Entity as LAZY is a good practice since in many occasions, you might not want the collections within an entity, but just want to interact with the data in your base entity. But in the event of you needing the data of your collections, then you can use either of the methods mentioned before.That is about it for today. For anyone who wants to try out the example, i have uploaded it here.
Thank you for reading, and hope you have a great day. Cheers!!
Friday, April 20, 2012
Setting up JNDI with Jetty (Embedded)
I was running embedded Jetty on my development work-space saving some time on vicious cycle of compiling and deployment. I have not worked with Jetty much and the ease of use made me hook on to it. I was in need to setup JNDI in order to retrieve a connection pool for my database related activities. Though there were comprehensive documentation in some places, most were scattered. So this post is intended to be your one stop place for the requirement of setting up JNDI with Jetty. If it does not, please do leave a comment and i will be glad to help you out.
So starting off, first let us see how to setup Jetty to run as an embedded server. The folder structure of my eclipse project is as follows;
The etc folder will consist of all the configuration files required by jetty. You can download jetty from here. For this example i have used jetty-6.1.26.
Include the following jars from the given folder locations;
For my example, i have set up mysql and therefore mysql-connector jar is also included in my library path.
Copy all the files residing in your jetty installation's etc directory to the etc directory of your eclipse project.
In order to enable JNDI, we first need to include jetty-plus. There are many ways you can do this such as providing it as a run-time argument, including it within your own jetty-env.xml residing in your WEB-INF or copying and pasting the required xml snippets from the jetty-plus.xml to your jetty.xml. I have chosen the latter. Hence, i have included the following snippet within my jetty.xml;
-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000
This will enable you to remote debug your application on port 8000. If there are any queries please do leave a comment and i will be more than happy to help anyone. And ofcourse if you do see any error, leave a reply too which again is much appreciated :).
Good day to you all and thank you for taking the time to read!!
So starting off, first let us see how to setup Jetty to run as an embedded server. The folder structure of my eclipse project is as follows;
Include the following jars from the given folder locations;
lib
|
jetty-x.x.xx.jar, jetty-util-x.x.xx.jar,servlet-api-x.x.jar
|
lib/plus
|
jetty-plus-x.x.xx.jar
|
lib/naming
|
jetty-naming-x.x.xx.jar
|
For my example, i have set up mysql and therefore mysql-connector jar is also included in my library path.
Copy all the files residing in your jetty installation's etc directory to the etc directory of your eclipse project.
In order to enable JNDI, we first need to include jetty-plus. There are many ways you can do this such as providing it as a run-time argument, including it within your own jetty-env.xml residing in your WEB-INF or copying and pasting the required xml snippets from the jetty-plus.xml to your jetty.xml. I have chosen the latter. Hence, i have included the following snippet within my jetty.xml;
<Array id="plusConfig" type="java.lang.String">
<Item>org.mortbay.jetty.webapp.WebInfConfiguration</Item>
<Item>org.mortbay.jetty.plus.webapp.EnvConfiguration</Item>
<Item>org.mortbay.jetty.plus.webapp.Configuration</Item>
<Item>org.mortbay.jetty.webapp.JettyWebXmlConfiguration</Item>
<Item>org.mortbay.jetty.webapp.TagLibConfiguration</Item>
</Array>
<call name="addLifeCycle">
<arg>
<new class="org.mortbay.jetty.deployer.WebAppDeployer">
<set name="contexts"><ref id="Contexts"></ref></set>
<set name="webAppDir"><systemproperty default="." name="jetty.home">/webapps</systemproperty></set>
<set name="parentLoaderPriority">false</set>
<set name="extract">true</set>
<set name="allowDuplicates">false</set>
<set name="defaultsDescriptor"><systemproperty default="." name="jetty.home">/etc/webdefault.xml</systemproperty></set>
<set name="configurationClasses"><ref id="plusConfig"></ref></set>
</new>
</arg>
</call>
Next up, you need to add the XML fragment related to your data-source into your jetty.xml. I have added the snippet required for mysql. For any other database, please check this link.
<New id="myds" class="org.mortbay.jetty.plus.naming.Resource">
<Arg>jdbc/MySQLDS</Arg>
<Arg>
<New class="com.mysql.jdbc.jdbc2.optional.MysqlConnectionPoolDataSource">
<Set name="Url">jdbc:mysql://localhost:3306/test</Set>
<Set name="User">root</Set>
<Set name="Password">password</Set>
</New>
</Arg>
</New>
Now that we have setup everything, all you need to do is run jetty in your embedded environment. Following code shows you how to run Jetty in the embedded mode as part of your main class;
import java.io.File;
import org.mortbay.jetty.Handler;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.handler.DefaultHandler;
import org.mortbay.jetty.handler.HandlerList;
import org.mortbay.jetty.webapp.WebAppContext;
import org.mortbay.xml.XmlConfiguration;
public class JettyTest {
public static void main(String[] args) throws Exception {
Server jetty = new Server();
String[] configFiles = {"etc/jetty.xml"};
for(String configFile : configFiles) {
XmlConfiguration configuration = new XmlConfiguration(new File(configFile).toURI().toURL());
configuration.configure(jetty);
}
WebAppContext appContext = new WebAppContext();
appContext.setContextPath("/myapp");
File rd = new File("path_to_your_war_file");
appContext.setWar(rd.getAbsolutePath());
HandlerList handlers = new HandlerList();
handlers.setHandlers(new Handler[]{ appContext, new DefaultHandler()});
jetty.setHandler(handlers);
jetty.start();
}
}
Thats about it. Now you can look up your data-source which is exposed from Jetty. For ease, i have configured it with Spring's JNDIObjectFactoryBean. One important aspect to note is the jndi provider URL and the initial context factory entries required for Jetty.
<bean id="jndiTemplate" class="org.springframework.jndi.JndiTemplate">
<property name="environment">
<props>
<prop key="java.naming.factory.initial">org.mortbay.naming.InitialContextFactory</prop>
<prop key="java.naming.provider.url">org.mortbay.naming</prop>
</props>
</property>
</bean>
<bean id="jndiDataSource" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiTemplate">
<ref bean="jndiTemplate"/>
</property>
<property name="jndiName">
<value>jdbc/MySQLDS</value>
</property>
</bean>
With that you have all that you need to configure JNDI and access it through Spring's JNDI template.
One other thing i was interested in was remote debugging with jetty server. After some searching i found that you need to include the following in your runtime configuration as VM arguments;
-Xdebug -Xnoagent -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=8000
This will enable you to remote debug your application on port 8000. If there are any queries please do leave a comment and i will be more than happy to help anyone. And ofcourse if you do see any error, leave a reply too which again is much appreciated :).
Good day to you all and thank you for taking the time to read!!
Wednesday, January 11, 2012
Understanding Java References
Playing around with Java References:
I could not pay attention to the blog in the recent times and first and foremost I must apologize for not staying in touch with you all in the world of technology. I recently stumbled upon the java.lang.ref package which was available since Java 1.2 but ironically i got to know about it just a few days back. Going through a few articles explaining about the various reference types and the java doc as well, I was very much intrigued and was anxious to get my hands dirty with some reference related code.
Im not going to talk about each reference class available within the java.lang.ref package as it is already very well explained here. Let us take a look at the following code snippet which I wrote to understand the basic operation of a WeakReference.
During the execution of the program, a weak reference will be the first to be garbage collected if there are no soft or strong references binding to it. So if memory is considerably low, or when and if the garbage collector deems appropriate, the weak reference is garbage collected and this is why I have included the else statement within my code to show the occurrence of that situation. Run this by setting minimum –Xms and –Xmx to understand how it works since otherwise you will have to wait a longer period to get an out of memory exception. And then change the WeakReference implementation to a SoftReference implementation and see that the program actually crashes after a few iterations. This is due to the fact that SoftReferences only gurantee to clean up memory just before a OutOfMemory error occurs. But with the WeakReference, the program continues to function without halting because it is almost always eligible for garbage collection and we can reinitialize the cache and continue to repopulate our cache.
The good thing about weak reference is that in my opinion it is one of the best ways to implement an in-memory cache which we usually implement ourselves when we need to keep data that do not consistently change but frequently accessed in memory and when the cost of going for a fully-fledged caching implementation like the JBoss cache or EHCache is too much. Quite often I have implemented caching solutions and have also seen production code similar to the following code snippet;
This is just a very basic level implementation to put out the idea across that we sometimes do use Maps to construct in-memory caching implementations. The fact that we have to note is that though there is nothing intrinsically wrong with this implementation, in an instance where your application is running low on memory, it would be a ideal if the garbage collector could remove this from memory to free up some for the other processes that need it. But since this map is a strong reference, there is no way the garbage collector can mark this reference as eligible for collection. A better solution would be to change the caching implementation from HashMap to a WeakHashMap.
The Javadoc specifies the following about the WeakHashMap;
"A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations."
So in retrospect, I believe whenever you are in need of an in-memory caching implementation and memory is of utmost importance to you, using a WeakHashMap would be beneficial.
That concludes my findings on the Reference package and I invite you all to share your experience in this regard which is highly appreciated.
Cheers
I could not pay attention to the blog in the recent times and first and foremost I must apologize for not staying in touch with you all in the world of technology. I recently stumbled upon the java.lang.ref package which was available since Java 1.2 but ironically i got to know about it just a few days back. Going through a few articles explaining about the various reference types and the java doc as well, I was very much intrigued and was anxious to get my hands dirty with some reference related code.
Im not going to talk about each reference class available within the java.lang.ref package as it is already very well explained here. Let us take a look at the following code snippet which I wrote to understand the basic operation of a WeakReference.
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.Map;
public class ReferencesTest {
private WeakReference<Map<Integer, String>> myMap;
public static void main(String[] args) {
new ReferencesTest().doFunction();
}
private void doFunction() {
Map<Integer, String> map = new HashMap<Integer, String>();
myMap = new WeakReference<Map<Integer, String>>(map);
map = null;
int i = 0;
while (true) {
if (myMap != null && myMap.get() != null) {
myMap.get().put(i++, "test" + i);
System.out.println("im still working!!!!");
} else {
System.out
.println("*******im free*******");
}
}
}
}
First I have defined a weak reference instance variable to which I assign an instance of a HashMap initialized within the doFunction() method. Then data is input to the map via the weak reference instance and not directly through the concrete instance of the hashmap we created. We check for the map being null due to the fact of the way WeakReferences work. During the execution of the program, a weak reference will be the first to be garbage collected if there are no soft or strong references binding to it. So if memory is considerably low, or when and if the garbage collector deems appropriate, the weak reference is garbage collected and this is why I have included the else statement within my code to show the occurrence of that situation. Run this by setting minimum –Xms and –Xmx to understand how it works since otherwise you will have to wait a longer period to get an out of memory exception. And then change the WeakReference implementation to a SoftReference implementation and see that the program actually crashes after a few iterations. This is due to the fact that SoftReferences only gurantee to clean up memory just before a OutOfMemory error occurs. But with the WeakReference, the program continues to function without halting because it is almost always eligible for garbage collection and we can reinitialize the cache and continue to repopulate our cache.
The good thing about weak reference is that in my opinion it is one of the best ways to implement an in-memory cache which we usually implement ourselves when we need to keep data that do not consistently change but frequently accessed in memory and when the cost of going for a fully-fledged caching implementation like the JBoss cache or EHCache is too much. Quite often I have implemented caching solutions and have also seen production code similar to the following code snippet;
import java.util.HashMap;
import java.util.Map;
public class CacheTest {
private Map<String, Object> myAwesomeCache = new HashMap<String, Object>(100);
public Object getData(String id){
Object objToReturn = null;
if(myAwesomeCache.containsKey(id)){
objToReturn = myAwesomeCache.get(id);
}else{
// retrieve from the database and populate the in memory cache map
}
return objToReturn;
}
}
This is just a very basic level implementation to put out the idea across that we sometimes do use Maps to construct in-memory caching implementations. The fact that we have to note is that though there is nothing intrinsically wrong with this implementation, in an instance where your application is running low on memory, it would be a ideal if the garbage collector could remove this from memory to free up some for the other processes that need it. But since this map is a strong reference, there is no way the garbage collector can mark this reference as eligible for collection. A better solution would be to change the caching implementation from HashMap to a WeakHashMap.
The Javadoc specifies the following about the WeakHashMap;
"A hashtable-based Map implementation with weak keys. An entry in a WeakHashMap will automatically be removed when its key is no longer in ordinary use. More precisely, the presence of a mapping for a given key will not prevent the key from being discarded by the garbage collector, that is, made finalizable, finalized, and then reclaimed. When a key has been discarded its entry is effectively removed from the map, so this class behaves somewhat differently from other Map implementations."
So in retrospect, I believe whenever you are in need of an in-memory caching implementation and memory is of utmost importance to you, using a WeakHashMap would be beneficial.
That concludes my findings on the Reference package and I invite you all to share your experience in this regard which is highly appreciated.
Cheers
Tuesday, November 8, 2011
Hibernate by Example - Part 2 (DetachedCriteria)
So last time we helped out justice league to effectively manage their super heroes. Today we focus on how The Avengers will be using Hibernate's Detached Criteria to find out their enemies with respect to each superhero so as to protect their super heroes. You can download the working example from here.
In this example we take only two entities into consideration. The Avenger & The Villain. We build a relationship between the two using a join table. Let us have a look at the domain mappings used in this example.
Our primary objective is to retrieve The Avenger to whom a villain belongs to. Note that this assumes the same villain cannot be a villain to more than one superhero. So moving on i give below the method that retrieves an avenger based on the villain name passed.
The power of the Criteria API is such that you can create dynamic queries with ease which would be a hassle if we were to use pure HQL which would require substantial string concatenations in order to achieve the same.
A sample test class called AvengerTest.java is given with the attachment which you can find at the top of the most. Note that you need to remove the comment on avenger-context.xml in order to create the tables needed for this example. So that is about it.
The Avengers can be risk averse now that they have a system by which they can relate any super villain to a super hero within their league.
As always your comments and suggestions are always welcome and appreciated.
Thank you for taking the time to read!!!!
In this example we take only two entities into consideration. The Avenger & The Villain. We build a relationship between the two using a join table. Let us have a look at the domain mappings used in this example.
package com.avengers.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
/**
* The domain class representing each member of the avengers
*
* @author Dinuka.Arseculeratne
*
*/
@Entity
@Table(name = "Avengers")
public class Avenger implements Serializable {
/**
* The primary key of the Avenger table
*/
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "avenger_id")
private Long avengerId;
/**
* The name of the avenger member
*/
@Column(name = "avenger_name")
private String avengerName;
/**
* A flag which holds whether the avenger's powers are awesome
*/
@Type(type = "yes_no")
@Column(name = "is_awesome")
private boolean isAwesome;
/**
* The list of enemies the avenger has
*/
@OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
@JoinTable(name = "AVENGERS_AND_VILLAINS", joinColumns = { @JoinColumn(name = "avenger_id") }, inverseJoinColumns = { @JoinColumn(name = "villain_id") })
private List<Villain> enemyList = new ArrayList<Villain>();
public Long getAvengerId() {
return avengerId;
}
public void setAvengerId(Long avengerId) {
this.avengerId = avengerId;
}
public String getAvengerName() {
return avengerName;
}
public void setAvengerName(String avengerName) {
this.avengerName = avengerName;
}
public boolean isAwesome() {
return isAwesome;
}
public void setAwesome(boolean isAwesome) {
this.isAwesome = isAwesome;
}
public List<Villain> getEnemyList() {
return enemyList;
}
public void addEnemy(Villain enemy) {
enemyList.add(enemy);
}
@Override
public String toString() {
return "Avenger [avengerId=" + avengerId + ", avengerName="
+ avengerName + ", isAwesome=" + isAwesome + ", enemyList="
+ enemyList + "]";
}
}
This class maps an avenger. I have used minimal fields in order to keep this example as simple and short as possible. And the Villain domain looks as follows;
package com.avengers.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
/**
* This class represents the Villain forces against the avengers
*
* @author Dinuka.Arseculeratne
*
*/
@Entity
@Table(name = "Villains")
public class Villain implements Serializable {
/**
* The primary key of the Enemy table
*/
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "villain_id")
private Long villaiId;
/**
* The name of the enemy
*/
@Column(name = "villain_name")
private String villainName;
/**
* A flag which checks whether the villain is super awesome
*/
@Type(type = "yes_no")
@Column(name = "is_awesome")
private boolean isAwesome;
public Long getVillaidId() {
return villaiId;
}
public void setVillaidId(Long villaidId) {
this.villaiId = villaidId;
}
public String getVillainName() {
return villainName;
}
public void setVillainName(String villainName) {
this.villainName = villainName;
}
public boolean isAwesome() {
return isAwesome;
}
public void setAwesome(boolean isAwesome) {
this.isAwesome = isAwesome;
}
@Override
public String toString() {
return "Villain [villaiId=" + villaiId + ", villainName=" + villainName
+ ", isAwesome=" + isAwesome + "]";
}
}
Ok now that we have defined our domains, let us see how data retrieval happens with DetachedCriteria. I have used DetachedCriteria here because The Avengers were very specific and said they do not want anything to do with the Hibernate session, so hence i used DetachedCriteria which does not require a hibernate session to be present.Our primary objective is to retrieve The Avenger to whom a villain belongs to. Note that this assumes the same villain cannot be a villain to more than one superhero. So moving on i give below the method that retrieves an avenger based on the villain name passed.
public Avenger retrieveAvengerByVillainName(String villainName) {
Avenger avenger = null;
/**
* Selected a detached criteria so we do not need a session to run it
* within.
*/
DetachedCriteria criteria = DetachedCriteria.forClass(Avenger.class);
/**
* Here we are doing an inner join with the Villain table in order to do
* a name comparison with the villainName passed in as a method
* parameter
*/
DetachedCriteria villainCriteria = criteria.createCriteria("enemyList");
villainCriteria.add(Restrictions.eq("villainName", villainName));
villainCriteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
@SuppressWarnings("unchecked")
List<Avenger> avengerList = getHibernateTemplate().findByCriteria(
criteria);
if (!avengerList.isEmpty()) {
avenger = avengerList.get(0);
getHibernateTemplate().initialize(avenger.getEnemyList());
}
return avenger;
}
In this method what we do is first we create a criteria for our master class which in this case is Avenger.class. Then we need to do a join with the Villain table and hence we create a sub criteria from our main criteria with the name of the list we defined within the Avenger domain class.
Then it is a matter of equaling the property of the Villain domain to the villain name passed in.The power of the Criteria API is such that you can create dynamic queries with ease which would be a hassle if we were to use pure HQL which would require substantial string concatenations in order to achieve the same.
A sample test class called AvengerTest.java is given with the attachment which you can find at the top of the most. Note that you need to remove the comment on avenger-context.xml in order to create the tables needed for this example. So that is about it.
The Avengers can be risk averse now that they have a system by which they can relate any super villain to a super hero within their league.
As always your comments and suggestions are always welcome and appreciated.
Thank you for taking the time to read!!!!
Tuesday, September 6, 2011
Hibernate by Example - Part 1 (Orphan removal)
So i thought to do a series of hibernate examples showing various features of hibernate. In the first part i wanted to show about the Delete Orphan feature and how it may be used with the use of a story line. So let us begin :)
Prerequisites:
In order for you to try out the following example you will need the below mentioned JAR files:
For anyone who want the eclipse project to try this out, you can download it with the above mentioned JAR dependencies here.
Introduction:
Its year 2011. And The Justice League has grown out of proportion and are searching for a developer to help with creating a super hero registering system. A developer competent in Hibernate and ORM is ready to do the system and handle the persistence layer using Hibernate. For simplicity, He will be using a simple stand alone application to persist super heroes. This is how this example will layout:
Table Design:
The design consists of three simple tables as illustrated by the diagram below;
As you can see its a simple one-to-many relationship linked by a Join Table. The Join Table will be used by Hibernate to fill the Super hero list which is in the domain class which we will go on to see next.
Domain classes and Hibernate mappings:
There are mainly only two domain classes as the Join table in linked with the primary owning entity which is the Justice League entity. So let us go on to see how the domain classes are constructed with annotations;
We use Hibernate's @Type annotation to represent true & false as Y & N within the database field. Hibernate has many @Type implementations which you can read about here. In this instance we have used this type.
Ok now that we have our class to represent the Super Heroes, lets go on to see how our Justice League domain class looks like which keeps tab of all super heroes who have pledged allegiance to the League.
So what does that do exactly? Ok so say that you have a group of Super Heroes in your League. And say one Super Hero goes haywire. So we need to remove Him/Her from the League. With JPA cascade this is not possible as it does not detect Orphan records and you will wind up with the database having the deleted Super Hero(s) whereas your collection still has a reference to it.
Prior to JPA 2.0 you did not have the orphanRemoval support and the only way to delete orphan records was to use the following Hibernate specific(or ORM specific) annotation which is now deprecated;
@org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
But with the introduction of the attribute orphanRemoval, we are now able to handle the deletion of orphan records through JPA. Now that we have our Domain classes
DAO & Service classes:
To keep with good design standards i have separated the DAO(Data access object) layer and the service layer. So let us see the DAO interface and implementation. Note that i have used HibernateTemplate through HibernateDAOSupport so as to keep away any Hibernate specific detail out and access everything in a unified manner using Spring.
According to the JPA spec you need a valid transaction for insert/delete/update functions.
So lets take a look at the DAO implementation;
Ok lets move on to the service layer implementation. The service layer in this instance is just acting as a mediation layer to call the DAO methods. But in a real world application you will probably have other validations, security related procedures etc handled within the service layer.
And we have auto wired the JusticeLeagueDAO and defined an @Qualifier so that it will be bound to the Hibernate implementation.
The value of the Qualifier should be the same name we gave the class level Qualifier within the DAO Implementation class. And Lastly let us look at the Spring configuration which wires up all these together;
Spring configuration for the application:
I have also used auto creation of tables by hibernate for simplicity purposes. The packagesToScan property instructs to scan through all sub packages(including nested packaged within them) under the root package com.justice.league.**.* to be scanned for @Entity annotated classes.
We have also bounded the session factory to the justiceLeagueDAO so that we can work with the Hibernate Template. For testing purposes you can have the tag <prop key="hibernate.hbm2ddl.auto">create</prop> initially if you want, and let hibernate create the tables for you. Ok so now that we have seen the building blocks of the application, lets see how this all works by first creating some super heroes within the Justice League
A simple main class to show how it all works:
As the first example lets see how we are going to persist the Justice League with a couple of Super Heroes;
Again if we query the database we will see that batman has been removed now as per the following;
So that's it. The story of how Justice League used Hibernate to remove Batman automatically without being bothered to do it themselves.
Next up look forward to how Captain America used Hibernate Criteria to build flexible queries in order to locate possible enemies. Watch out!!!!
Have a great day people and thank you for reading!!!!
If you have any suggestions or comments pls do leave them by.
Prerequisites:
In order for you to try out the following example you will need the below mentioned JAR files:
- org.springframework.aop-3.0.6.RELEASE.jar
- org.springframework.asm-3.0.6.RELEASE.jar
- org.springframework.aspects-3.0.6.RELEASE.jar
- org.springframework.beans-3.0.6.RELEASE.jar
- org.springframework.context.support-3.0.6.RELEASE.jar
- org.springframework.context-3.0.6.RELEASE.jar
- org.springframework.core-3.0.6.RELEASE.jar
- org.springframework.jdbc-3.0.6.RELEASE.jar
- org.springframework.orm-3.0.6.RELEASE.jar
- org.springframework.transaction-3.0.6.RELEASE.jar.
- org.springframework.expression-3.0.6.RELEASE.jar
- commons-logging-1.0.4.jar
- log4j.jar
- aopalliance-1.0.jar
- dom4j-1.1.jar
- hibernate-commons-annotations-3.2.0.Final.jar
- hibernate-core-3.6.4.Final.jar
- hibernate-jpa-2.0-api-1.0.0.Final.jar
- javax.persistence-2.0.0.jar
- jta-1.1.jar
- javassist-3.1.jar
- slf4j-api-1.6.2.jar
- mysql-connector-java-5.1.13-bin.jar
- commons-collections-3.0.jar
For anyone who want the eclipse project to try this out, you can download it with the above mentioned JAR dependencies here.
Introduction:
Its year 2011. And The Justice League has grown out of proportion and are searching for a developer to help with creating a super hero registering system. A developer competent in Hibernate and ORM is ready to do the system and handle the persistence layer using Hibernate. For simplicity, He will be using a simple stand alone application to persist super heroes. This is how this example will layout:
- Table design
- Domain classes and Hibernate mappings
- DAO & Service classes
- Spring configuration for the application
- A simple main class to show how it all works
Table Design:
The design consists of three simple tables as illustrated by the diagram below;
As you can see its a simple one-to-many relationship linked by a Join Table. The Join Table will be used by Hibernate to fill the Super hero list which is in the domain class which we will go on to see next.
Domain classes and Hibernate mappings:
There are mainly only two domain classes as the Join table in linked with the primary owning entity which is the Justice League entity. So let us go on to see how the domain classes are constructed with annotations;
package com.justice.league.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Type;
@Entity
@Table(name = "SuperHero")
public class SuperHero implements Serializable {
/**
*
*/
private static final long serialVersionUID = -6712720661371583351L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "super_hero_id")
private Long superHeroId;
@Column(name = "super_hero_name")
private String name;
@Column(name = "power_description")
private String powerDescription;
@Type(type = "yes_no")
@Column(name = "isAwesome")
private boolean isAwesome;
public Long getSuperHeroId() {
return superHeroId;
}
public void setSuperHeroId(Long superHeroId) {
this.superHeroId = superHeroId;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPowerDescription() {
return powerDescription;
}
public void setPowerDescription(String powerDescription) {
this.powerDescription = powerDescription;
}
public boolean isAwesome() {
return isAwesome;
}
public void setAwesome(boolean isAwesome) {
this.isAwesome = isAwesome;
}
}
As i am using MySQL as the primary database, i have used the GeneratedValue strategy as GenerationType.AUTO which will do the auto incrementing whenever a new super hero is created. All other mappings are familiar to everyone with the exception of
the last variable where we map a boolean to a Char field in the database.We use Hibernate's @Type annotation to represent true & false as Y & N within the database field. Hibernate has many @Type implementations which you can read about here. In this instance we have used this type.
Ok now that we have our class to represent the Super Heroes, lets go on to see how our Justice League domain class looks like which keeps tab of all super heroes who have pledged allegiance to the League.
package com.justice.league.domain;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
@Entity
@Table(name = "JusticeLeague")
public class JusticeLeague implements Serializable {
/**
*
*/
private static final long serialVersionUID = 763500275393020111L;
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "justice_league_id")
private Long justiceLeagueId;
@Column(name = "justice_league_moto")
private String justiceLeagueMoto;
@Column(name = "number_of_members")
private Integer numberOfMembers;
@OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER, orphanRemoval = true)
@JoinTable(name = "JUSTICE_LEAGUE_SUPER_HERO", joinColumns = { @JoinColumn(name = "justice_league_id") }, inverseJoinColumns = { @JoinColumn(name = "super_hero_id") })
private List<SuperHero> superHeroList = new ArrayList<SuperHero>(0);
public Long getJusticeLeagueId() {
return justiceLeagueId;
}
public void setJusticeLeagueId(Long justiceLeagueId) {
this.justiceLeagueId = justiceLeagueId;
}
public String getJusticeLeagueMoto() {
return justiceLeagueMoto;
}
public void setJusticeLeagueMoto(String justiceLeagueMoto) {
this.justiceLeagueMoto = justiceLeagueMoto;
}
public Integer getNumberOfMembers() {
return numberOfMembers;
}
public void setNumberOfMembers(Integer numberOfMembers) {
this.numberOfMembers = numberOfMembers;
}
public List<SuperHero> getSuperHeroList() {
return superHeroList;
}
public void setSuperHeroList(List<SuperHero> superHeroList) {
this.superHeroList = superHeroList;
}
}
The important fact to note here is the annotation @OneToMany(cascade = { CascadeType.ALL }, fetch = FetchType.EAGER, orphanRemoval = true). Here we have set orphanRemoval = true.So what does that do exactly? Ok so say that you have a group of Super Heroes in your League. And say one Super Hero goes haywire. So we need to remove Him/Her from the League. With JPA cascade this is not possible as it does not detect Orphan records and you will wind up with the database having the deleted Super Hero(s) whereas your collection still has a reference to it.
Prior to JPA 2.0 you did not have the orphanRemoval support and the only way to delete orphan records was to use the following Hibernate specific(or ORM specific) annotation which is now deprecated;
@org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.DELETE_ORPHAN)
But with the introduction of the attribute orphanRemoval, we are now able to handle the deletion of orphan records through JPA. Now that we have our Domain classes
DAO & Service classes:
To keep with good design standards i have separated the DAO(Data access object) layer and the service layer. So let us see the DAO interface and implementation. Note that i have used HibernateTemplate through HibernateDAOSupport so as to keep away any Hibernate specific detail out and access everything in a unified manner using Spring.
package com.justice.league.dao;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.justice.league.domain.JusticeLeague;
@Transactional(propagation = Propagation.REQUIRED, readOnly = false)
public interface JusticeLeagueDAO {
public void createOrUpdateJuticeLeagure(JusticeLeague league);
public JusticeLeague retrieveJusticeLeagueById(Long id);
}
In the interface layer i have defined the Transaction handling as Required. This is done so that whenever you do not need a transaction you can define that at the method level of that specific method and in more situations you will need a transaction
with the exception of data retrieval methods. According to the JPA spec you need a valid transaction for insert/delete/update functions.
So lets take a look at the DAO implementation;
package com.justice.league.dao.hibernate;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import com.justice.league.dao.JusticeLeagueDAO;
import com.justice.league.domain.JusticeLeague;
@Qualifier(value="justiceLeagueHibernateDAO")
public class JusticeLeagueHibernateDAOImpl extends HibernateDaoSupport
implements JusticeLeagueDAO {
@Override
public void createOrUpdateJuticeLeagure(JusticeLeague league) {
if (league.getJusticeLeagueId() == null) {
getHibernateTemplate().persist(league);
} else {
getHibernateTemplate().update(league);
}
}
@Transactional(propagation = Propagation.NOT_SUPPORTED, readOnly = false)
public JusticeLeague retrieveJusticeLeagueById(Long id){
return getHibernateTemplate().get(JusticeLeague.class, id);
}
}
Here i have defined an @Qualifier to let Spring know that this is the Hibernate implementation of the DAO class. Note the package name which ends with hibernate. This as i see is a good design concept to follow where you separate your implementation(s) into
separate packages to keep the design clean.Ok lets move on to the service layer implementation. The service layer in this instance is just acting as a mediation layer to call the DAO methods. But in a real world application you will probably have other validations, security related procedures etc handled within the service layer.
package com.justice.league.service;
import com.justice.league.domain.JusticeLeague;
public interface JusticeLeagureService {
public void handleJusticeLeagureCreateUpdate(JusticeLeague justiceLeague);
public JusticeLeague retrieveJusticeLeagueById(Long id);
}
package com.justice.league.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import com.justice.league.dao.JusticeLeagueDAO;
import com.justice.league.domain.JusticeLeague;
import com.justice.league.service.JusticeLeagureService;
@Component("justiceLeagueService")
public class JusticeLeagureServiceImpl implements JusticeLeagureService {
@Autowired
@Qualifier(value = "justiceLeagueHibernateDAO")
private JusticeLeagueDAO justiceLeagueDAO;
@Override
public void handleJusticeLeagureCreateUpdate(JusticeLeague justiceLeague) {
justiceLeagueDAO.createOrUpdateJuticeLeagure(justiceLeague);
}
public JusticeLeague retrieveJusticeLeagueById(Long id){
return justiceLeagueDAO.retrieveJusticeLeagueById(id);
}
}
Few things to note here. First of all the @Component binds this service implementation with the name justiceLeagueService within the spring context so that we can refer to the bean as a bean with an id of name justiceLeagueService.And we have auto wired the JusticeLeagueDAO and defined an @Qualifier so that it will be bound to the Hibernate implementation.
The value of the Qualifier should be the same name we gave the class level Qualifier within the DAO Implementation class. And Lastly let us look at the Spring configuration which wires up all these together;
Spring configuration for the application:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<context:component-scan base-package="com.justice.league" />
<context:annotation-config />
<tx:annotation-driven />
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
<property name="packagesToScan">
<list>
<value>com.justice.league.**.*</value>
</list>
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
<prop key="hibernate.connection.driver_class">com.mysql.jdbc.Driver</prop>
<prop key="hibernate.connection.url">jdbc:mysql://localhost:3306/my_test</prop>
<prop key="hibernate.connection.username">root</prop>
<prop key="hibernate.connection.password">password</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
</props>
</property>
</bean>
<bean id="justiceLeageDAO"
class="com.justice.league.dao.hibernate.JusticeLeagueHibernateDAOImpl">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<bean id="transactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
</beans>
Note that i have used the HibernateTransactionManager in this instance as i am running it stand alone. If you are
running it within an application server you will almost always use a JTA Transaction manager.I have also used auto creation of tables by hibernate for simplicity purposes. The packagesToScan property instructs to scan through all sub packages(including nested packaged within them) under the root package com.justice.league.**.* to be scanned for @Entity annotated classes.
We have also bounded the session factory to the justiceLeagueDAO so that we can work with the Hibernate Template. For testing purposes you can have the tag <prop key="hibernate.hbm2ddl.auto">create</prop> initially if you want, and let hibernate create the tables for you. Ok so now that we have seen the building blocks of the application, lets see how this all works by first creating some super heroes within the Justice League
A simple main class to show how it all works:
As the first example lets see how we are going to persist the Justice League with a couple of Super Heroes;
package com.test;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.justice.league.domain.JusticeLeague;
import com.justice.league.domain.SuperHero;
import com.justice.league.service.JusticeLeagureService;
public class TestSpring {
/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"spring-context.xml");
JusticeLeagureService service = (JusticeLeagureService) ctx
.getBean("justiceLeagueService");
JusticeLeague league = new JusticeLeague();
List<SuperHero> superHeroList = getSuperHeroList();
league.setSuperHeroList(superHeroList);
league.setJusticeLeagueMoto("Guardians of the Galaxy");
league.setNumberOfMembers(superHeroList.size());
service.handleJusticeLeagureCreateUpdate(league);
}
private static List<SuperHero> getSuperHeroList() {
List<SuperHero> superHeroList = new ArrayList<SuperHero>();
SuperHero superMan = new SuperHero();
superMan.setAwesome(true);
superMan.setName("Clark Kent");
superMan.setPowerDescription("Faster than a speeding bullet");
superHeroList.add(superMan);
SuperHero batMan = new SuperHero();
batMan.setAwesome(true);
batMan.setName("Bruce Wayne");
batMan.setPowerDescription("I just have some cool gadgets");
superHeroList.add(batMan);
return superHeroList;
}
}
And if we go to the database and check this we will see the following output;
mysql> select * from superhero; +---------------+-----------+-----------------+-------------------------------+ | super_hero_id | isAwesome | super_hero_name | power_description | +---------------+-----------+-----------------+-------------------------------+ | 1 | Y | Clark Kent | Faster than a speeding bullet | | 2 | Y | Bruce Wayne | I just have some cool gadgets | +---------------+-----------+-----------------+-------------------------------+ mysql> select * from justiceleague; +-------------------+-------------------------+-------------------+ | justice_league_id | justice_league_moto | number_of_members | +-------------------+-------------------------+-------------------+ | 1 | Guardians of the Galaxy | 2 | +-------------------+-------------------------+-------------------+So as you can see we have persisted two super heroes and linked them up with the Justice League. Now let us see how that delete orphan works with the below example;
package com.test;
import java.util.ArrayList;
import java.util.List;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.justice.league.domain.JusticeLeague;
import com.justice.league.domain.SuperHero;
import com.justice.league.service.JusticeLeagureService;
public class TestSpring {
/**
* @param args
*/
public static void main(String[] args) {
ApplicationContext ctx = new ClassPathXmlApplicationContext(
"spring-context.xml");
JusticeLeagureService service = (JusticeLeagureService) ctx
.getBean("justiceLeagueService");
JusticeLeague league = service.retrieveJusticeLeagueById(1l);
List<SuperHero> superHeroList = league.getSuperHeroList();
/**
* Here we remove Batman(a.k.a Bruce Wayne) out of the Justice League
* cos he aint cool no more
*/
for (int i = 0; i < superHeroList.size(); i++) {
SuperHero superHero = superHeroList.get(i);
if (superHero.getName().equalsIgnoreCase("Bruce Wayne")) {
superHeroList.remove(i);
break;
}
}
service.handleJusticeLeagureCreateUpdate(league);
}
}
Here we first retrieve the Justice League record by its primary key. Then we loop through and remove Batman off the League and again call the createOrUpdate method. As we have the remove orphan defined, any Super Hero not in the list which is in the database will be deleted.Again if we query the database we will see that batman has been removed now as per the following;
mysql> select * from superhero; +---------------+-----------+-----------------+-------------------------------+ | super_hero_id | isAwesome | super_hero_name | power_description | +---------------+-----------+-----------------+-------------------------------+ | 1 | Y | Clark Kent | Faster than a speeding bullet | +---------------+-----------+-----------------+-------------------------------+
So that's it. The story of how Justice League used Hibernate to remove Batman automatically without being bothered to do it themselves.
Next up look forward to how Captain America used Hibernate Criteria to build flexible queries in order to locate possible enemies. Watch out!!!!
Have a great day people and thank you for reading!!!!
If you have any suggestions or comments pls do leave them by.
Saturday, August 13, 2011
Lessons i learnt playing Angry Birds
So i finally saved up and bought my first smart phone a few weeks back(A samsung galaxy s i9000 to be specific). I heard about the game Angry Birds even before i had a smart phone but never got a chance to play it. The hype about it was very true. The game is addictive :D. Anyhow my objective of this article is not to disseminate news how awesome Angry Birds is, which is quite obvious with the plethora of download rates it is getting, but to write about a few things that crossed my mind whilst playing it.
- Plan before execute
As a developer this is a very interesting point. Sometimes i rush into writing a piece of code. But if i had looked at a few possible obstacles, other possible solutions, i believe most of the time i could have come up with a much better design.
- Efficiency in resource utilization
As a developer, i should know my strengths and weaknesses and apply them accordingly when given a particular task, and look at what i lack and gain knowledge in areas where i lack in order to fill the gap.
As a project manager you should know the skills of your resources and utilize them to the tasks at hand efficiently in order to achieve the end goal of delivering a stable product to the customer. Not everyone is good at everything, so identifying your resource pool enables you to make better decisions and improve and refine your resources' knowledge base as you go on.
- How to handle the task with minimum effort
As a developer, when given a task i must strive to see ways in which i could achieve it with minimum effort. This does not mean your a lazy bum, but that you opt to work smarter than harder. You can thereby save up time to do other things like gain knowledge on other new technologies, contribute to some open source project you love etc. In the birds example, you are left with a few birds because you used your targets efficiently. In the same way, if you apply the solution you devised in the correct manner, you will be left with some time to spare(this might depend on your supervisor ofcourse :) )
- Go ahead with what works for you
As a developer, when designing a particular module/project, there always are many ways in which that can be achieved. But in the end you have to decide on what will work for you and go ahead with it. When presented with many solutions you have to decide on what will work for you and stick to the plan to achieve the end goal. Again as the birds example sometimes the one you chose might not work, so you refine your solution and come up with a successful one in the end.
- Perseverance
When you embark on a mission, sometimes you cannot complete it in one shot. You need to keep on trying and eventually you will get there and make the pigs pay.
As a developer sometimes i might not be able to come up with a viable solution for the problem at hand. But you should not be discouraged and give up. Breaking the problem into smaller understandable components might let you see things in a new perspective. So keep on trying and eventually you will get there.
Thats it for now guys. Ofcourse im still on level 2-17 at the time of writing this post, so i might learn a few more things as i go on :)...
Thank you for reading and please do leave by your thoughts if you have the time. Have a great day guys!!!
Subscribe to:
Posts (Atom)


