2

I'm working on simple application that uses Spring MVC 3 and hibernate 3.

I have a requirement to generate ID in the following format.

Month/Year/number(number will increase). 

Month and year values do change based on the current Date. Once the year completed, let say after the completion of one financial year the sequence again start from the beginning, like month/Year/number. Hope I'm clear.

Example:

1st Financial Year:
Mar/2011/001
Jun/2011/002
Dec/2011/003
Feb/2011/004
...
...

2nd Financial Year:
Mar/2012/001
Mar/2012/002
Aug/2012/003
..
..
..

How can I approach this problem? Please help me.

Nilesh
  • 4,137
  • 6
  • 39
  • 53
Shekar
  • 21
  • 1
  • 3

2 Answers2

1

Create a custom sequence generator. You will need to keep somewhere a record that stores the year of the last record saved. Each time you want to gerenate a new identifier check that value and if the last record saved is not from this year update that value and recreate the sequence being used underneath. If that value is not yet set you can calculate it querying the date of the newest record.

A bit of pseudocode :P

public class CustomSequenceGenerator extends SequenceStyleGenerator {

    private static Integer lastYear = null;

    public CustomSequenceGenerator (){
        super();
    }

    @Override
    public Serializable generate(SessionImplementor sessionImplementator, Object object) throws HibernateException {
        Long id = (Long)super.generate(sessionImplementator, object);
        if (lastYear == null) {
            getYearOfLastRecord();
        }
        if (lastYear != getThisYear() ) {
           recreateDatabaseSequence();
           lastYear = getThisYear();
        }
        String date = generateStringBasedOnDate();
        return date+id.toString;
    }

// Implement missing methods

[....]
}
Rafa de Castro
  • 2,474
  • 1
  • 24
  • 44
0

Look at various options provided here in the hibernate docs.

Here is a related stackoverflow thread.

Finally, your implementation will have to derive from this hibernate interface and then you can implement your custom logic in the generate method.

Community
  • 1
  • 1
Nilesh
  • 4,137
  • 6
  • 39
  • 53