Upgrading Tapestry version from 5.0.18 to 5.2.5: Issues and Resolutions



In this post I am going to write about the issues that we have faced during the up-gradation of the tapestry version from 5.0.18 to 5.2.5 in one our projects. Below are some of them. Hope this collection will help someone!


1. Changes in the RequestPathOptimizer file inside tapestry.


Issue Logs:-


Caused by: java.lang.ClassNotFoundException: org.apache.tapestry5.internal.services.RequestPathOptimizer from BaseClassLoader@41c491{VFSClassLoaderPolicy@1d02b85{name=vfsfile:/D:/SVN/trunk/export/tools/jboss-5.0.1.GA/server/default/deploy/ROOT.war/ .......
at org.jboss.classloader.spi.base.BaseClassLoader.loadClass(BaseClassLoader.java:422)


Solution:-


Remove all the tapestry-spring dependancies to resolve this issue.


Reference:-


Tapestry JIRA 
Mailing list URL 




2.Including the tapestry bean validator jar.


Logs:-


Caused by: java.lang.ClassNotFoundException: javax.validation.ValidatorFactory from ......
..............
real=file:/D:/SVN/trunk/export/tools/jboss-5.0.1.GA/server/default/deploy/ROOT.war/WEB-INF/lib/XmlSchema-1.4.2.jar]] delegates=null exported=[]}} at org.jboss.classloader.spi.base.BaseClassLoader.loadClass(BaseClassLoader.java:422)


Solution:-


There is new feature in Tapestry called bean validator that needs the validation api and implementation jars to be added it can be downloaded from the project homepage here.


3.Changes in the tapestry spring integration.


Logs:-


Caused by: java.lang.IllegalStateException: Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!
at org.springframework.web.context.ContextLoader.initWebApplicationContext(ContextLoader.java:179)
at org.apache.tapestry5.internal.spring.SpringModuleDef$3$1.invoke(SpringModuleDef.java:194)
at org.apache.tapestry5.ioc.internal.OperationTrackerImpl.invoke(OperationTrackerImpl.java:65)
... 91 more
java.lang.RuntimeException: Exception constructing service 'ApplicationContext': Cannot initialize context because there is already a root application context present - check whether you have multiple ContextLoader* definitions in your web.xml!


Solution:-


From Tapestry 5.2.x it will load the spring context automatically and hence we need to remove the below from web.xml. This will help in live class loading of service class. Also the spring beans should be wired and not to be injected as services.As per this there will be changes in All the Page classes and web.xml


Reference:-


Mailing list URL
Tapestry Wiki-1 
Tapestry Wiki-2


As per the article "The changes below represent an unfortunate backwards compatibility issue. If necessary, you can still use tapestry-spring version 5.0.18 with the rest of Tapestry."


If we want to continue using spring-tapestry 5.2.5 jar we have to make changes in each and every Page file where spring services are injected. Also the spring beans should be wired and not to be injected as services.




4. Using Tapestry 5.2.5 inside the JBoss Application server.


Logs:-


Caused by: java.io.IOException
at org.jboss.virtual.plugins.registry.DefaultVFSRegistry.getFile(DefaultVFSRegistry.java:125)
at org.jboss.virtual.protocol.AbstractVFSHandler.openConnection(AbstractVFSHandler.java:71)
at java.net.URL.openConnection(Unknown Source)
at java.net.URL.openStream(Unknown Source)
at org.apache.tapestry5.ioc.internal.services.ClassNameLocatorImpl.scanDirStream(ClassNameLocatorImpl.java:182)
at org.apache.tapestry5.ioc.internal.services.ClassNameLocatorImpl.scanURL(ClassNameLocatorImpl.java:131)
at org.apache.tapestry5.ioc.internal.services.ClassNameLocatorImpl.findClassesWithinPath(ClassNameLocatorImpl.java:96)
at org.apache.tapestry5.ioc.internal.services.ClassNameLocatorImpl.locateClassNames(ClassNameLocatorImpl.java:75)
... 85 more
Caused by: java.net.URISyntaxException: Illegal character in path at index 159: vfszip:/D:/SVN/trunk/export/tools/jboss-5.0.1.GA/server/default/deploy/ROOT.war/WEB-INF/lib/tapestry-upload-5.2.5.jar/org/apache/tapestry5/upload/components/PK/
at java.net.URI$Parser.fail(Unknown Source)


Solution:-


As per the below links we need to use a patch to fix it.


Mailing list URL-1
Mailing list URL-2 
Tapestry JIRA
Tapestry Wiki



5. Changes in the Locale implementation


If you use the url to load pages and your application supports the multiple languages then you need to append the locale code infront of the url.


For example:
Current url: "http://localhost/superpopup" should be changed to "http://localhost/${localeInd}/superpopup" 


Mailing List URL  


6. Tapestry handling of transients instances ValueEncoder


Mailing List URL


7. Change in the way @Secure is handled in the page classes.


Most of the applications we will have the Index page tagged with the @Secure annotation to force the usage of https protocol. Some how I could not get this done with the existing settings. To have this you need to add the below lines.


configuration.add(SymbolConstants.SECURE_ENABLED, "true");


Mailing List URL


When to replace Unit Tests with Integration Test


Its been a while I was thinking about integration vs unit testing. Lots of googling, questions in stack overflow and looking in many books. In this post I would like share with you the information I have found and what decision I arrive at this.


I think if you put this question to any Java developer, you will get an anwser supporting the unit test instantaneously. They will tell you that if you can not do unit testing, the unit of code you hava written is large and you have to bring it down to multiple testable unit. I have found these questions in Stack Overflow 1, 2, 3 and 4 useful in getting a good understanding of both terminologies.

Unit testing is widly followed in Java domain with most of the projects now also enforcing the code coverage and unit testing. Integration testing is relativly new and misunderstood concept. Even through it is practiced much less than, unit testing there can be varios uses of it. Lets take a simple user story and revisit both.

Lets consider it with a user story

User will give an INPUT in a UI form and when the submit button is clicked, the PROCESSED output should be shown in the next page. Since the results should be editable, both INPUT and OUTPUT should be saved in the database.

Technical Design

Lets assume that our application will grow rapidly in the future and we will design it now keeping that in mind. 


As shown in the above image it is a standard 4-tier design with view, service, dao. It has a application layer which contains the logic of how to convert the input into output. To implement the story we wrote 5 methods(1 in service, 2 dao to save input and output, 1 contains the business and 1 method in view layer to prepare the input.)

Writing some Unit test cases

If we were to unit test the story, we need to write 5 tests. As the different layers are dependent, we might need to use mock objects for testing. But apart from one method in application layer that does the original process, is there any need to unit test the other part? For example the method,

 public void saveInput(Input input){  
           Session session = sessionFactory.getCurrentSession();  
           session.save(input);  
 }  


When you unit test this, you will typically use a mock object of sessionFactory and the code willl always work. Hence I don't see much point in wiring a unit test here. If you observe carefully, apart from the application layer, all the other methods will be similar to what we have discussed.


What can we acheive with integration test?


Read here as a heads up for the integration test. As we have seen most of the unit tests for this story were not effective. But we can't skip testing as we want to find out the code coverage and make our code self testing. According to Martin flower in his article about Continuous Integration you should write the code that can test the other code. I fell the good integration tests can do this for you.


Lets write a simple itegration test for this situation,

 @Configurable(autowire = Autowire.BY_NAME)   
 @RunWith(SpringJUnit4ClassRunner.class)   
 @ContextConfiguration(locations = {"classpath:applicationContext.xml"})  
 public class SampleIntTest {  
      @Autowired  
      private SamService samService;  
      @Test  
      public void testAppProcessing(){  
      Input input = new Input();  
      //prepare input for the testing.  
      Output output = samService.processInputs(input);  
      //validate outpt gainst the given input.  
      if(!isValidate(input,output)){  
           Assert.fail("Validation failed!");  
      }  
 }  



I have skipped the view layer here as it not so relevent. We are expecting the INPUT from the UI in a bean Input and thats that we willl have in the service layer. Here, With this few line of coding, you can acheive the full functionality of the application from the service layer.


It is prefered to use a in-memory database like H2 for integration tests. If the table structure is complicated it may not be possible in that case,you can use a test instance of DB and prepare a script to delete all the data and run it as part of the test so that the DB state is restored back. This is important because in the next run the same data will be saved again.


Another advantage of integration tets is that if you are changing the implementation the test need not be changed because it ic concerned with the input and output.This is useful in refactoring the code without change in the test code. Also, you can schedule these tets to measure the stability of the appication and any regression issues can be caught early.


As we have seen, integration test are easy to write and are useful, but we need to make sure it does not replace the unit testing completely. When ever there is a rule base system(like the LogicalProcesser in our case) it should be mandatory because you can't cover all the scenarios with the integration test.


So as always JEE is about making choice asnd sticking to it. For the last few months we were practicing it in our teams and it is really going well. Currently we made integration test mandatory and unit tests and optional. Always review the code coverage and make sure you get good coverage in the core of the system(the LogicalProcesser in our case).

Developing Java Web Applications with Tapestry 5



In this post I would like to share my experience with  developing Java Web Applications with Tapestry 5.

Tapestry is a component oriented framework for creating dynamic, robust, highly scalable web applications in Java. Tapestry is been is here for a while now, not really taken off as a web framework for Java. In the past, it is been critisized for non compatability of its versions. After the release of version 5 in 2008 it has been more consistant and popular with developers.

I have been using Tapestry for the last 15 months and used both version 5.0.18 and 5.2.6. One of the main issues with tapestry was the learning curve and that is been some what improved now, with the exelent documentation available at the project home page here. You don't see  a lot of tapestry resources online. If you search for the tapestry resources in internet you might end up getting t3 or t4 versions which will not be usefull with the new t5 version.

Having worked in tapestry for more than one year, I must say that I have mixed opinion about tapestry. Its POJO based approach is really nice and it also scores as a component based framework. The components are easily plug-gable in all the pages. There has been a lot of improvements in the ability of unit testing the pages. Even if you don't want to depend on tapestry's test classes you can create your own integration test cases as the pages are simple java classes. It has really good integration with spring that opens your window to all other frameworks and technologies.

The biggest pain is been when you are stuck with problems, the alternatives were really difficult. For example there is a grid component in tapestry which by default provides sorting for all the columns in the grid. If you need to disable sorting, there should be hell lot of things you have to do as told here. In another example, you might need to have 3 classes construct a simple drop down in tapestry as told here. In today world of IDE tapestry don't have much of IDE support and that can be a pain while you develop a page in tapestry.

Its been really difficult to find good resouces about tapestry and I thought of sharing some links that I found useful during my learning of tapestry. As I told already the getting started page is reaaly improved and now you can really get started with tapestry in that page. The wiki page contains lots of tips and tricks on how to use tapestry features.

The Tapestry Jump Start page is great place with lots of examples that will help you get into tapestry. Howard M. Lewis Ship the creator of Tapestry writes about tapestry in his personal blog is also a good read.  Recently I have found another site with lots of exapmle in tapestry.  Even the Tapestry360 is a fresh and new concept.I  really liked Mark Shead blog post is a good collection of usefull references about tapestry5.

When you are thinking about java web framework I think tapestry should be one of the choices. If You compare tapestry with other web framework there will be lots of diffidence have a look at Matt Raible presentation about comparing jvm web frameworks also the matrix comparing the web frameworks in Java. Also there is a post from Joshua about why you should consider tapestry5.

Top 10 Java Books you don't want to miss.




We learn by reading books and experimenting on it.  So, it is imperative that you choose the best available options. In this post I would like to share my experience with some of the books and how they can help you evolve as a Java Developer.

Lets start from the floor, the first 3 books are a good starting point for any Java student. Java Programming Language helps you to get yourself familiar with Java, where Head First will help you stick the Java concepts into your brain, so that you will never forget them. I have chosen Thinking In Java 3rd book in this category but Java the Complete Reference By Herbert Schildt and Java in a nutshell  By David Flanagan are good substitutes. These books are more of a reference than a must read.


1. Java Programming Language By Ken Arnold, James Gosling, David Holmes
               
                Direct from the creators of the Java, The Java Programming Language is an indispensible resource for novice and advanced programmers alike. Developers around the world have used previous editions to quickly gain deep understanding of the Java programming language, its design goals, and how to use it most effectively in real-world development. The authors systematically conver most classes in Java's main packages, java.lang.*, java.util, and java.io, presenting in-depth explanations of why these classes work as they do, with informative examples. Several new chapters and major sections have been added, and every chapter has been updated to reflect today's best practices for building robust, efficient, and maintainable Java software.

Above are extracts from the book index page.

2. Head First Java By Kathy Sierra, Bert Bates
               
                Its unique approach not only shows you what you need to know about Java syntax, it enables and encourages you to think like a Java programmer. Mastering object oriented programming requires a certain way of thinking, not just a certain way of writing code. The latest research in cognitive science, neurobiology, and educational psychology shows that learning at the deeper levels takes a lot more than text on a page. Actively combining words and pictures not only helps in understanding the subject, but in remembering it. According to some studies, an engaging, entertaining, image-rich, conversational approach actually teaches the subject better. Head First Java puts these theories into practice with a vengeance.

Above lines are copied from Google books read more here.
               
3. Thinking In Java By Bruce Eckel
               
                Eckel introduces all the basics of objects as Java uses them, then walks carefully through the fundamental concepts underlying all Java programming -- including program flow, initialization and cleanup, implementation hiding, reusing classes, and polymorphism. Using extensive, to-the-point examples, he introduces exception handling, Java I/O, run-time type identification, and passing and returning objects. Eckel also provides an overview of the Key Technology of the Java2 Enterprise Edition platform (J2EE).

Above lines are copied from Google books read more here.               


I am not a big fan of SCJP Exam, but A Programmer's Guide to Java SCJP Certification is much more than a certification guide. It gives you an insight in to Java, the tips and tricks. SCJP Sun Certified Programmer for Java 5 Study Guide  By Kathy Sierra, Bert Bates is a go to book if you are mad about SCJP. Better to read these books than spending time in reading question dumps, these books will help you much more than clearing the exam in your career.
               
4. A Programmer's Guide to Java SCJP Certification: A Comprehensive Primer By Khalid Azim Mughal, Rolf Rasmussen
               
                 This book will help you prepare for and pass the Sun Certified Programmer for the Java Platform SE 6 (CX-310-065) Exam. It is written for any experienced programmer (with or without previous knowledge of Java) interested in mastering the Java programming language. It contains in-depth explanations of the language features. Their usage is illustrated by way of code scenarios, as required by the exam. Numerous exam-relevant review questions to test your understanding of each major topic, with annotated answers Programming exercises and solutions at the end of each chapter Copious code examples illustrating concepts, where the code has been compiled and thoroughly tested on multiple platforms Program output demonstrating expected results from running the examples Extensive use of UML (Unified Modelling Language) for illustration purposes

Above lines are copied from Google books read more here.               

               
OK, so you got to know Java and been working in it for couple of years its time to take the next step. Everything in this world has good and bad. Java language if not used the way is supposed to be, can make your life miserable. When you write code, its written for future. Writing good Java code is an art that needs lot more skill than knowledge of basic Java. Here I would like to introduce the next set of 4 books that can make you a master in the trade.
                
The Pragmatic Programmer is not really a Java book but is a self help book for any programmer. It is a great book covering various aspects of software development and is capable in transforming you to a Pragmatic Programmer.
               
5. The Pragmatic Programmer, From Journeyman To Master By Andrew Hunt, David Thomas

                Written as a series of self-contained sections and filled with entertaining anecdotes, thoughtful examples, and interesting analogies, The Pragmatic Programmer illustrates the best practices and major pitfalls of many different aspects of software development. Whether you're a new coder, an experienced programmer, or a manager responsible for software projects, use these lessons daily, and you'll quickly see improvements in personal productivity, accuracy, and job satisfaction. You'll learn skills and develop habits and attitudes that form the foundation for long-term success in your career. You'll become a Pragmatic Programmer.
               
Above lines are copied from Google books read more here.               


So, we wrote code. It is time to add some style. The elements of Java style is one of the earliest documentation on the style part of Java including its various aspects.
               
6. The elements of Java style By Scott Ambler, Alan Vermeulen

                 Many books explain the syntax and basic use of Java; however, this essential guide explains not only what you can do with the syntax, but what you ought to do. While illustrating these rules with parallel examples of correct and incorrect usage, the authors offer a collection of standards, conventions, and guidelines for writing solid Java code that will be easy to understand, maintain, and enhance. Java developers and programmers who read this book will write better Java code, and become more productive as well.

Above lines are copied from Google books read more here.
              

Now, we know how to write code in style. But is it best is class? Does it uses the best practices? Effective Java is one of the best book on best practices is a favourite book for many Java developers.
               
7. Effective Java By Joshua Bloch

                Joshua  brings together seventy-eight indispensable programmer's rules of thumb: working, best-practice solutions for the programming challenges you encounter every day. Bloch explores new design patterns and language idioms, showing you how to make the most of features ranging from generics to enums,  annotations to autoboxing. Each chapter in the book consists of several “items” presented in the form of a short, standalone essay that provides specific advice, insight into Java platform subtleties, and outstanding code examples. The comprehensive descriptions and explanations for each item illuminate what to do, what not to do, and why.

Above lines are copied from Google books read more here

Then, you know the good, it is time for the bad stuff. Bitter Java is one of the first book to bring up the Anti-patters in Java. There are various articles and books on Anti-patterns and code smells and is an area where there is lots of space to learn. There are many other books on this topic I am adding this book as a starting point.
               
8. Bitter Java By Bruce Tate

                Intended for intermediate Java programmers, analysts, and architects, this guide is a comprehensive analysis of common server-side Java programming traps (called anti-patterns) and their causes and resolutions. Based on a highly successful software conference presentation, this book is grounded on the premise that software programmers enjoy learning not from successful techniques and design patterns, but from bad programs, designs, and war stories -- bitter examples. These educational techniques of graphically illustrating good programming practices through negative designs and anti-patterns also have one added benefit: they are fun.
               
Above lines are copied from Google books read more here

Many say you need to know Design Patterns, if you want grow as a developer. So I thought of mentioning the best Design pattern book that I have read. It is not a reference book nor it contains the patters catalogue but the book explains the Object Oriented Design Principles that are as important as the patters. Use the book Design patterns: elements of reusableobject-oriented software if you are looking for a reference book.
               
9. Head First design patterns By Eric Freeman, Elisabeth Freeman, Kathy Sierra, Bert Bates

                You know you don't want to reinvent the wheel (or worse, a flat tire), so you look to Design Patterns--the lessons learned by those who've faced the same problems. With Design Patterns, you get to take advantage of the best practices and experience of others. Using the latest research in neurobiology, cognitive science, and learning theory, Head First Design Patterns will load patterns into your brain in a way that sticks. In a way that lets you put them to work immediately. In a way that makes you better at solving software design problems, and better at speaking the language of patterns with others on your team.
               
Above lines are copied from Google books read more here

If your are a master at coding and designing application using Java its time to crack the JVM. I have read that 'The Java language specification' is the best book to do that. I have not got the patience or skill to read the book but is an interesting pick if you want to cross the line.
               
10. The Java language specification

                The book provides complete, accurate, and detailed coverage of the Java programming language. It provides full coverage of all new features added in since the previous edition including generics, annotations, asserts, autoboxing, enums, for each loops, variables,  methods and static import clauses.

Above are extracts from the book index page.

In these web-years online resources may be more reachable than books, but I fell these books will help in tuning you to a better Java programmer.

Hibernate Data Fetching Options




In this post I will try to point out various ways you can fetch data in hibernate and in what scenarios each of then are is useful.


HQL in hibernate
It is the most preferred way to use that combines you the ease of SQL and flexibility of Hibernate. I don't want to add anything more but will direct you to an excellent article on HQL.


Criteria Queries
Criteria queries are less verbose and preferred by people who don't have much exposure to SQL. It is less performative compared to HQL. Read more about Criteria here.


Native SQL and Stored Procedures.
This should considered as a last option as you will loose the features of hibernate if you start using Native SQL.Also you should take care the responsibility of transforming the result set to object by yourself.
But there are situations you want to go with this approach. Read more about them here.

These typical ways can be tweaked in various ways to customize them to your requirement. Let me discus few of them that you may not find very often documented.

I have used the classes from examples from my previous post for simplicity.Read it here in case you need any explanation on the examples.

1. Partial Initialization of a bean.

Suppose you have a bean AMain, as in my previous post.

 public class AMain {  
    Integer aId;  
    String name;  
    ASub1 one2oneSubA1;  
    List<ASub3> subList;  
      //More code below...  
 }  

If you write an HQL to fetch this bean as 


 List<AMain> beanList2 = session.createQuery("from AMain am ").list();  


it will fire the below queries.


Hibernate: select amain0_.a_id as a1_1_, amain0_.name as name1_, amain0_.prop1 as prop3_1_, amain0_.prop2 as prop4_1_, 'A' as formula0_, amain0_.a_id as formula1_ from A_Main amain0_
Hibernate: select asub1x0_.as1_id as as1_2_0_, asub1x0_.sub_name as sub2_2_0_, asub1x0_.a_id as a3_2_0_ from A_Sub1 asub1x0_ where asub1x0_.a_id=?
Hibernate: select sublist0_.a_id as a3_1_, sublist0_.as3_id as as1_1_, sublist0_.as3_id as as1_4_0_, sublist0_.sub_name as sub2_4_0_, sublist0_.a_id as a3_4_0_ from A_Sub3 sublist0_ where sublist0_.a_id=?

 Also the last query can repeat number of times if the lazy loading in enabled.

Now If I have a requirement to get the partially initialized AMain bean, I mean with only the properties aId and name initialized that definitely should not take mare than 1 query as all the information is available on the AMain table. Most of the people will tend to go to Native SQL at this point.But you can achieve this using HQL.


write the HQL as   

 List<AMain> beanList2 = session.createQuery("select new AMain (aId,name) from AMain am ").list();  


Also add the corresponding constructor in class AMain as

 public AMain(Integer aId,String name) {  
           this.aId = aId;  
           this.name = name;  
      }  




Now verify the SQL output


Hibernate: select amain0_.a_id as col_0_0_, amain0_.name as col_1_0_ from A_Main amain0_


Yes..only 1 query is fired.This is very useful in when we have to fetch a snapshot of a Large object in a performative way.




2. HQL Joins on multiple columns.


If there are two related table and we have mapped them in the hbm files then the below hql is possible.


"from AMain a left outer join a.refMain ref...more joins here"


It will do a left outer join on the tables RefMain and AMain provided you have a corresponding mapping. Now if you need to add another condition in the join(to satisfy the join but which we could not add as a relationship). It can be achieved using a 'with' operator.


so, the new HQL is,


"from AMain a left outer join a.refMain ref with ref.aOrbId = 'a'...more joins here"


This way the query results can be achieved with out disturbing the original mapping.


3. Using a DTO instead on a Domain Object.

Meany times we might need a set of data that might be needed which is spread across multiple tables. Which means I don not have a Domain Object to hold the data. Using hibernate we can populate a DTO object from any SQL of HQL query using Transformers. The Transformers can convert the List of Object arrays to List of DTO that will improve the readability and are much easier to use with.

 public class AFamilyDTO {  
      Integer aId;  
      String name;  
      Integer as1Id;  
      String aSub1Name;  
      /* getter/ setters here..*/   
 }  


As you can see the bean represent a snapshot of AMain and ASub1 beans Or it can be any DTO which we have created for the easy representation of the data model. Now Lets see how we can use Transformers to populate this bean.

 SQLQuery query = session.createSQLQuery("select amain.a_id as aId , amain.name as name, " +  
               "sub1.as1_id as as1Id, sub1.sub_name as as1Name " +  
               " from A_Main amain join A_Sub1 sub1 on amain.a_id = sub1.a_id");  
        query.addScalar("aId", Hibernate.INTEGER);  
        query.addScalar("name", Hibernate.STRING);  
        query.addScalar("as1Id", Hibernate.INTEGER);  
        query.addScalar("as1Name", Hibernate.STRING);  
        query.setResultTransformer(Transformers.aliasToBean(AFamilyDTO.class));  
 List<AFamilyDTO> list = query.list();  


As I have told in the beginning of the post, there are multiple ways to fetch data in hibernate. So, before you blame hibernate for the performance issues in your application have a look all the options it provides you to fetch the data. Turn on the show sql flag on and see how many queries are getting fired. Then see if you can use any alternative ways of fetching data.

Hibernate Mapping Example



In this post I am trying to add a reference mapping project which includes most of the real world scenarios you will encounter when using hibernate.This example is primarily meant for differentiating the various types of relationships in hibernate and it is tested for the SAVE, UPDATE and SELECT features. I leave it to you to find out how to DELETE a row in the table or a member in the child list.

If you are not familiar with the hibernate get an heads up on the various object relations in from this article.
Now lets take an example and try to put a Object map and table design for the same. I am trying to provide all the relations in the same example.
As  first step create the java and hibernate files as below.

1. AMain.java

 package com.manu.hibernate.mappings.domain;
  
 import java.util.List;
  
 import java.util.Set;
  
 /**
  
  * The Main class A.
  
  */
  
 public class AMain {
  
     //Properties of A.
  
     Integer aId;
  
     String name;
  
     String prop1;
  
     String prop2;
  
     ASub1 one2oneSubA1;
  
     Set<ASub2> subSets;
  
     List<ASub3> subList;
  
     RefOnlyAMain one2oneSubRef;
  
     public AMain(String name) {
  
         this.name = name;
  
     }
  
     public AMain() {
  
     }
  
     /* Add the Getters and Setters */ 
  
     @Override
  
     public String toString() {
  
         // TODO Auto-generated method stub
  
         return " AMain with Id:"+aId+" Name:"+name;
  
     }
  
 }
  

2. ASub1.java

 package com.manu.hibernate.mappings.domain;
  
 public class ASub1 {
  
     Integer as1Id;
  
     Integer aId;
  
     String subName;
  
     AMain parent;
  
     public ASub1(String subName) {
  
         this.subName = subName;
  
     }
  
     public ASub1() {
  
     }

  /* Add the Getters and Setters */ 

     @Override
  
     public String toString() {
  
         return " ASub1 with Id:"+as1Id+" Name:"+subName+" Parent:"+parent;
  
     }
  
 }
  

3. Similarly create the classes ASub2.java, ASub3.java, RefOnlyAMain.java

4. The Mapping file ABeanTypes.hbm.xml
Note:- It is better to move the xml declaration to separate files I have put them together for easy understanding.


 <?xml version="1.0"?>
  
 <!DOCTYPE hibernate-mapping PUBLIC 
  
 "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
  
 "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
  
 <hibernate-mapping package="com.manu.hibernate.mappings.domain">
  
     <class name="AMain" table="A_Main">
  
         <id name="aId" column="a_id" unsaved-value="null">
  
             <generator class="hilo" />
  
         </id>
  
         <property name="name" />
  
         <property name="prop1" />
  
         <property name="prop2" />
  
         <one-to-one name="one2oneSubA1" class="com.manu.hibernate.mappings.domain.ASub1" cascade="all"
  
             property-ref="parent"/>
  
         <set name="subSets" inverse="true" cascade="all">
  
             <key column="a_id" />
  
             <one-to-many class="com.manu.hibernate.mappings.domain.ASub2" />
  
         </set>
  
         <list name="subList" inverse="true" cascade="all" lazy="false">
  
             <key column="a_id" />
  
             <list-index column="as3_id" />
  
             <one-to-many class="com.manu.hibernate.mappings.domain.ASub3" />
  
         </list>
  
         <one-to-one name="one2oneSubRef"
  
             class="com.manu.hibernate.mappings.domain.RefOnlyAMain" property-ref="parentARef"
  
             cascade="all" >
  
             <formula>'A'</formula>
  
             <formula>a_id</formula>
  
         </one-to-one>
  
     </class>
  
     <class name="ASub1" table="A_Sub1">
  
         <id name="as1Id" column="as1_id" unsaved-value="null">
  
             <generator class="hilo" />
  
         </id>
  
         <property name="subName" column="sub_name" />
  
         <property name="aId" column="a_id" insert="false" update="false" />
  
         <many-to-one name="parent"
  
             class="com.manu.hibernate.mappings.domain.AMain" column="a_id"
  
             unique="true" cascade="save-update" />
  
     </class>
  
     <class name="ASub2" table="A_Sub2">
  
         <id name="as2Id" column="as2_id" unsaved-value="null">
  
             <generator class="hilo" />
  
         </id>
  
         <property name="subName" column="sub_name" />
  
         <property name="aId" column="a_id" insert="false" update="false" />
  
         <many-to-one class="com.manu.hibernate.mappings.domain.AMain"
  
             name="parent" column="a_id" />
  
     </class>
  
     <class name="ASub3" table="A_Sub3">
  
         <id name="as3Id" column="as3_id" unsaved-value="null">
  
             <generator class="hilo" />
  
         </id>
  
         <property name="subName" column="sub_name" />
  
         <property name="aId" column="a_id" insert="false" update="false" />
  
         <many-to-one class="com.manu.hibernate.mappings.domain.AMain"
  
             name="parent" column="a_id" />
  
     </class>
  
     <class name="RefOnlyAMain" table="Ref_A_Main">
  
         <id name="refId" column="ref_id" unsaved-value="null">
  
             <generator class="hilo" />
  
         </id>
  
         <property name="name" />
  
         <property name="aOrbId" column="aOrb_id" insert="false"    update="false" />
  
         <property name="aOrbInd" column="aOrb_ind" />
  
         <properties name="parentARef">
  
             <property name="aOrbInd" column="aOrb_ind" insert="false"    update="false"/>
  
             <many-to-one name="parentA"
  
                 class="com.manu.hibernate.mappings.domain.AMain" column="aOrb_id"
  
                 unique="true" cascade="save-update" />
  
         </properties>
  
     </class>
  
 </hibernate-mapping>
  

5.The hibernate configuration file.

 <?xml version='1.0' encoding='utf-8'?>
  
 <!DOCTYPE hibernate-configuration PUBLIC
  
 "-//Hibernate/Hibernate Configuration DTD//EN"
  
 "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
  
 <hibernate-configuration>
  
     <session-factory>
  
         <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
  
         <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/appDB1</property>
  
         <property name="hibernate.connection.username">root</property>
  
         <property name="hibernate.connection.password">manupk</property>
  
         <property name="hibernate.connection.pool_size">10</property>
  
         <property name="show_sql">true</property>
  
         <property name="dialect">org.hibernate.dialect.MySQLDialect</property>
  
         <property name="hibernate.hbm2ddl.auto">create</property>
  
         <mapping resource="com\manu\hibernate\mappings\domain\ABeanTypes.hbm.xml" />
  
     </session-factory>
  
 </hibernate-configuration>
  

6. Test client.

 package com.manu.hibernate.mappings.client;
  
 import java.util.ArrayList;
  
 import java.util.HashSet;
  
 import java.util.List;
  
 import java.util.Set;
  
 import org.hibernate.Session;
  
 import org.hibernate.SessionFactory;
  
 import org.hibernate.Transaction;
  
 import org.hibernate.cfg.Configuration;
  
 import com.manu.hibernate.mappings.domain.AMain;
  
 import com.manu.hibernate.mappings.domain.ASub1;
  
 import com.manu.hibernate.mappings.domain.ASub2;
  
 import com.manu.hibernate.mappings.domain.ASub3;
  
 import com.manu.hibernate.mappings.domain.RefOnlyAMain;
  
 /**
  
  * @author Manupk
  
  *
  
  */
  
 public class RelationsSaveTest {
  
     /**
  
      * @param args
  
      */
  
     public static void main(String[] args) {
  
         SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  
         Session session = sessionFactory.openSession();
  
         Transaction tx = session.beginTransaction();
  
         //Create the Parent Object.
  
         AMain a = new AMain("A");
  
         //One2One Child of AMain, with shared column in both table.
  
         ASub1 as1 = new ASub1("ASub - 1");
  
         as1.setParent(a);
  
         a.setOne2oneSubA1(as1);
  
         //One2Many Using set, with shared column in both table.
  
         ASub2 as2a = new ASub2("Set - 1");
  
         ASub2 as2b = new ASub2("Set - 2");
  
         as2a.setParent(a);
  
         as2b.setParent(a);
  
         Set<ASub2> subSet = new HashSet<ASub2>();
  
         subSet.add(as2a);
  
         subSet.add(as2b);
  
         a.setSubSets(subSet);
  
         //One2Many using List, with shared column in both table.
  
         ASub3 as3a = new ASub3("List - 1");
  
         ASub3 as3b = new ASub3("List - 2");
  
         ASub3 as3c = new ASub3("List - 3");
  
         as3a.setParent(a);
  
         as3b.setParent(a);
  
         as3c.setParent(a);
  
         List<ASub3> subList = new ArrayList<ASub3>();
  
         subList.add(as3a);
  
         subList.add(as3b);
  
         subList.add(as3c);
  
         a.setSubList(subList);
  
         //One2One Child of AMain, but without a shared column. 
  
         RefOnlyAMain rfa = new RefOnlyAMain();
  
         rfa.setaOrbInd("A"); //Add the indicator to point the correct parent class.
  
         rfa.setName("Child 1 A");
  
         rfa.setParentA(a);
  
         a.setOne2oneSubRef(rfa);
  
         session.save(a);
  
         session.flush();
  
         tx.commit();
  
         session.close();
  
         //Close the session and open a new one for proper testing.
  
         session =sessionFactory.openSession();
  
         List<AMain> result1 = session.createQuery(" from AMain").list();
  
         System.out.println(result1);
  
         List<ASub1> result2 = session.createQuery(" from ASub1 ").list();
  
         System.out.println(result2);
  
         List<ASub2> result3 = session.createQuery(" from ASub2").list();
  
         System.out.println(result3);
  
         List<ASub3> result4 = session.createQuery(" from ASub3").list();
  
         System.out.println(result4);
  
         List<RefOnlyAMain> result6 = session.createQuery(" from RefOnlyAMain").list();
  
         System.out.println(result6);
  
     }
  
 }
  

In the class AMain.java; note the properties,

  ASub1 one2oneSubA1;
 Set<ASub2> subSets;
 List<ASub3> subList;
 RefOnlyAMain one2oneSubRef;


As the name implies,
        ASub1 has a One-to-One relationship with AMain. 
        ASub2 has a Many-to-One relationship with AMain and it is implemented using Set.
        ASub3 has a Many-to-One relationship with AMain and it is implemented using List.
        RefOnlyAMain a One-to-One relationship with AMain, but it does not share a column with AMain as in the above case.So we need to use the 'formula' to map this bean.

All the tables that contains the child data of AMain has the a_id column as the foreign key and all the mappings are done based on that.

Now have look at the test client.

In the test client all the properties are set and are being saved to the table.

All the table mappings are given in the ABeanType.hbm.xml file and are self explanatory.
When the Test client is executed the hibernate generates the insert scripts as below.
Note:- In the hibernate.cfg.xml file the property hibernate.hbm2ddl.auto is set as create so that hibernate automatically create the required table. Change it to update in the consecutive runs.

Hibernate automatically takes care about the referential integrity of data by inserting them in the order. All you need to do is to save the Main bean and all the child beans are automatically saved to the DB.If there is any error in the operation all the data inserts are rolled back and hibernate maintains the integrity of the data.

Hibernate: insert into A_Main (name, prop1, prop2, a_id) values (?, ?, ?, ?)
Hibernate: insert into A_Sub1 (sub_name, a_id, as1_id) values (?, ?, ?)
Hibernate: insert into A_Sub2 (sub_name, a_id, as2_id) values (?, ?, ?)
Hibernate: insert into A_Sub2 (sub_name, a_id, as2_id) values (?, ?, ?)
Hibernate: insert into A_Sub3 (sub_name, a_id, as3_id) values (?, ?, ?)
Hibernate: insert into A_Sub3 (sub_name, a_id, as3_id) values (?, ?, ?)
Hibernate: insert into A_Sub3 (sub_name, a_id, as3_id) values (?, ?, ?)
Hibernate: insert into Ref_A_Main (name, aOrb_ind, aOrb_id, ref_id) values (?, ?, ?, ?)

Hibernate: select amain0_.a_id as a1_1_, amain0_.name as name1_, amain0_.prop1 as prop3_1_, amain0_.prop2 as prop4_1_, 'A' as formula0_, amain0_.a_id as formula1_ from A_Main amain0_
Hibernate: select asub1x0_.as1_id as as1_2_0_, asub1x0_.sub_name as sub2_2_0_, asub1x0_.a_id as a3_2_0_ from A_Sub1 asub1x0_ where asub1x0_.a_id=?
Hibernate: select refonlyama0_.ref_id as ref1_5_0_, refonlyama0_.name as name5_0_, refonlyama0_.aOrb_id as aOrb3_5_0_, refonlyama0_.aOrb_ind as aOrb4_5_0_ from Ref_A_Main refonlyama0_ where refonlyama0_.aOrb_ind=? and refonlyama0_.aOrb_id=?
[ AMain with Id:1 Name:A]

Hibernate: select asub1x0_.as1_id as as1_2_, asub1x0_.sub_name as sub2_2_, asub1x0_.a_id as a3_2_ from A_Sub1 asub1x0_
[ ASub1 with Id:32768 Name:ASub - 1 Parent: AMain with Id:1 Name:A]

Hibernate: select asub2x0_.as2_id as as1_3_, asub2x0_.sub_name as sub2_3_, asub2x0_.a_id as a3_3_ from A_Sub2 asub2x0_
[ ASub2 with Id:65536 Name:Set - 2 Parent: AMain with Id:1 Name:A,  ASub2 with Id:65537 Name:Set - 1 Parent: AMain with Id:1 Name:A]

Hibernate: select asub3x0_.as3_id as as1_4_, asub3x0_.sub_name as sub2_4_, asub3x0_.a_id as a3_4_ from A_Sub3 asub3x0_
[ ASub3 with Id:98304 Name:List - 1 Parent: AMain with Id:1 Name:A,  ASub3 with Id:98305 Name:List - 2 Parent: AMain with Id:1 Name:A,  ASub3 with Id:98306 Name:List - 3 Parent: AMain with Id:1 Name:A]

Hibernate: select refonlyama0_.ref_id as ref1_5_, refonlyama0_.name as name5_, refonlyama0_.aOrb_id as aOrb3_5_, refonlyama0_.aOrb_ind as aOrb4_5_ from Ref_A_Main refonlyama0_
[ RefOnlyAMain with Id:131072 Name:Child 1 A Parent: AMain with Id:1 Name:A]


Now go ahead and play around changing the values and table structure for better understanding.

Given below the code snippet used to update the set of child beans.

         SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
  
         Session session =sessionFactory.openSession();
  
         Transaction tx = session.beginTransaction();
  
         List<AMain> result1 = session.createQuery(" from AMain").list();
  
         System.out.println(result1);
  
         //Create the Parent Object.
  
         AMain a = result1.get(0);
  
         //One2One Child of AMain, with shared column in both table.
  
         ASub1 as1 = a.getOne2oneSubA1();
  
         as1.setSubName("NEW");
  
         //One2Many using List, with shared column in both table.
  
         ASub3 as3a = new ASub3("NEW List - 1");
  
         ASub3 as3b = new ASub3("NEW List - 2");
  
         ASub3 as3c = new ASub3("NEW List - 3");
  
         as3a.setParent(a);
  
         as3b.setParent(a);
  
         as3c.setParent(a);
  
         List<ASub3> subList = new ArrayList<ASub3>();
  
         subList.add(as3a);
  
         subList.add(as3b);
  
         subList.add(as3c);
  
         subList.addAll(a.getSubList());
  
         a.setSubList(subList);
  
         //session.createQuery("delete from ASub3").executeUpdate();
  
         tx.commit();
  
         session.close();
  
         //Close the session and open a new one for proper testing.
  
         session =sessionFactory.openSession();
  
         Transaction tx2 = session.beginTransaction();
  
         session.save(a);
  
         session.flush();
  
         tx2.commit();
  
         session.close();
  

 

Universal Date Parser.


It is easy to read the Date object from a string in Java. The task can be quite tricky when you are dealing with a third party data feed and you are not really sure about the format in which the date is going to come.

The below example handles most of the date formats and returns the date object. The format supported are [dd MMM,yy], [MM/dd/yy], [MMddyy], [yyyy-MM-dd], [dd-MMM-yy], [dd MMM yy], [MMM dd, yy], [yyyyMMdd].

You can easily add more formats but needs to make sure they and not conflicted with the existing things. For example you should not add [dd/MM/yy] as it will conflict with [MM/dd/yy] but it can be replaced.