Saturday, May 16, 2009

Hibernate Mapping with parent child relation mapping into same tables

Consider cases when you have parent child relations in the same tables, this becomes very difficult to handle.

In most cases we seperate out mapping of maintaining this parent child relation into another table.

Lets consider an example

we have category which can have subcategories and both these persist on the same table.

Example : Electronics can have subcategory camera, and further camera can have its subcategories.

@Table(name = "t_product_category")
public class ProductCategory {

@Column(name = "f_category_id")
private int categoryId;

@Column(name = "f_category_name")
private String categoryName;

/* The following onetomany relations says that one ProductCategory can have many childrens of teh same type(ProductCategory) identified by
a collection(Set) children.
The initialisation is set to EAGER meaning when you fetch the parent product category all its childeren are automatically
loaded */

@OneToMany(mappedBy = "parent" ,fetch =FetchType.EAGER)
private Set<ProductCategory> children;

/* The following many to one relation means that many(children) of ProductCategory can have a parent of the same kind identified by
parent */

private ProductCategory parent;

public Set<ProductCategory> getChildren() {
return children;

public void setChildren(Set<ProductCategory> children) {
this.children = children;

public ProductCategory getParent() {
return parent;

public void setParent(ProductCategory parent) {
this.parent = parent;

Just by mentioning the two mapping and the corresponding getters & setters our relationship is ready.

Database table looks like this

CREATE TABLE `t_product_category` (
`F_CATEGORY_ID` int(11) NOT NULL auto_increment,
`F_CATEGORY_NAME` varchar(150) NOT NULL,
`F_PARENT` int(11) default NULL,

Getting jar name & location from loaded class

The following method with the classname passed as parameter will return the location of the jar from which the class is loaded.


public static String getJarLocation(String className) {
try {
Class cls = Class.forName(className);
ProtectionDomain pDomain = cls.getProtectionDomain();
CodeSource cSource = pDomain.getCodeSource();
URL loc = cSource.getLocation();
return loc.toString();
} catch (Exception e) {

return null;


Alternatively we can also add the following to the startup JVM paramteres , which will print all the classes loaded along with the jar names and its path.


Scheduling simple Quartz job Using Spring

Currently, Spring supports the Timer, part of the JDK since 1.3, and the Quartz Scheduler (
Both schedulers are set up using a FactoryBean with optional references to Timers or Triggers, respectively

Quartx job can be written in several ways

1. Wiring up jobs using triggers and the SchedulerFactoryBean

<bean id="sampleJob" class="com.xyx.SampleJob" />

<bean id="sampleJobTrigger" class="org.springframework.scheduling.quartz.SimpleTriggerBean">
<property name="jobDetail" ref="sampleJob" />
<property name="startDelay" value="10000" />
<property name="repeatInterval" value="50000" />


<bean id="sampleJobTrigger" class="org.springframework.scheduling.quartz.CronTriggerBean">
<property name="jobDetail" ref="exampleJob"/>
<!-- run every morning at 6 AM -->
<property name="cronExpression" value="0 0 6 * * ?"/>

<bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
<property name="triggers">
<ref bean="sampleJobTrigger" />

2. Using the JobDetailBean

<bean name="exampleJob" class="org.springframework.scheduling.quartz.JobDetailBean">
<property name="jobClass" value="com.xyx.SampleJob"/>
<property name="jobDataAsMap">
<entry key="timeout" value="5"/>

In this case com.xyx.SampleJob has to extend QuartzJobBean.

3. Using the MethodInvokingJobDetailFactoryBean

Often you just need to invoke a method on a specific object. Using the MethodInvokingJobDetailFactoryBean you can do as follows

<bean id="jobDetail" class="org.springframework.scheduling.quartz.MethodInvokingJobDetailFactoryBean">
<property name="targetObject" ref="sampleJob"/>
<property name="targetMethod" value="sampleMethod"/>

The above example will result in the sampleMethod() being called on the sampleJob object.


JMX - Exposing an mbean

JMX is an easy-to-utilize way to expose some of the key inner-workings of your application in a standardized way, so you can maximize the
manageability and monitoring facilities of your application.

A standard MBean is defined by writing a Java interface called SomethingMBean and a Java class called Something that implements that interface.
Every method in the interface defines either an attribute or an operation in the MBean. By default, every method defines an operation.

MBean Interface

public interface TestMBean
public void sayHello();
public int add(int x, int y);

By convention, an MBean interface takes the name of the Java class that implements it, with the suffix MBean added.

Meab Implementation

public class Test implements TestMBean {
public void sayHello() {
System.out.println("hello, world");

public int add(int x, int y) {
return x + y;


Creating a JMX Agent to Manage a Resource

public class Main {

public static void main(String[] args) throws Exception {

MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
ObjectName name = new ObjectName("com.example:type=Test");
Test mbean = new Test();
mbs.registerMBean(mbean, name);


System.out.println("Waiting forever...");

The object name is an instance of the JMX class ObjectName and must conform to the syntax defined by the JMX specification. Namely, the object name
must contain a domain and a list of key-properties. In the object name defined by Main, the domain is com.example (the package in which the example
MBean is contained). In addition, the key-property declares that this object is of the type Test.

An instance of a Test object, named mbean, is created. The Hello object named mbean is then registered as an MBean in the MBean server mbs with the
object name name, by passing the object and the object name into a call to the JMX method MBeanServer.registerMBean().

Running the Standard MBean Example

Run the sample application

Connect using jconsole and these operations can be directly called from there and values can be set.

Caster - XML/JAVA Object Mapping

Castor is an Open Source data binding framework for Java[tm].Castor provides Java-to-XML binding

Castor XML can marshal almost any "bean-like" Java Object to and from XML. In most cases the marshalling
framework uses a set of ClassDescriptors and FieldDescriptors to describe how an Object should be marshalled
and unmarshalled from XML.

The mapping rules can be mentioned in xml files which makes it easy for customization.

It also has features for java code generation from xml.

JAXB -Xml/Java Mapping

After looking at many options which helped me convert java classes into xml and vice versa, i found this JAXB very exciting.The Java Architecture
for XML Binding provides a powerful and practical way of working with XML content from within Java applications. The newly released JAXB 2.0 offers
many new features, including full support of all XML Schema features, significantly fewer generated classes, generated classes that are easier to
manipulate, and a more flexible validation mechanism.

JAXB prerequisites

To get started with JAXB 2.0 you need:

1 Java Platform, Standard Edition 5: JAXB 2.0 relies heavily on features of Java SE 5, such as annotations and generics
2. An implementation of JAXB 2.0

I chose this implementation -

To start with the JAXb we first need to generate java classes using the xsd.This can be easily done ussing the xjc compiler

syntax : $xjc .xsd -p -d

Once this command are exceuted the classes are generated in teh given package.These can be used to marshel and unmarshel the xml quite easily.

First we create a JAXBContext

JAXBContext jaxbContext = JAXBContext.newInstance("package.of.the.generated.classes");

Then carete a unmarsheller using the context

Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();

Use the unmarshellor to get the data objects for the xml

DataObj data = (DataObj) unmarshaller.unmarshal(url);

url is URL which returns the xml response.Also xml can be given from a file directly

this data object can ve used to access all other valuse presnt in the xml response.

Ref :

Simple java Regular Expression matching

This simple regular expression matching code just checks for all hyper links in the input string and converts it into proper clickable links in html.

import java.util.regex.*;

public static void main(String args[]) {

String test=" jisds sdsds sds";
Pattern pattern = Pattern.compile("(http://)?www.[a-zA-Z0-9./]*");
Matcher matcher = pattern.matcher(test);

boolean found = false;

while (matcher.find()) {

String a = test.substring(0,matcher.start()-1);
String b =test.substring(matcher.end());
String c=a+"<a href=\"""\">""</a> "+b;


found = true;

if (!found) {
System.out.println("No match found.");


Free Domain Names @!