2

I am working on Spring boot Application with hibernate to create simple invoice. I want to generate invoice number through hibernate in the following format as below

YEAR/MONTH/Number(Will Increase)

The above sequence is dependent on invoice date.

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.

I have tried to Sequence Generator , table Generator . My Code snippet is as below :

@Id
@GeneratedValue(strategy = GenerationType.AUTO, generator = "year_gen")
@GenericGenerator(name = "year_gen", strategy = "com.example.generator.CustomGenerator")
@Column(name = "invoice_no")
private String invoiceno;

But I am not getting any idea that how to make it dependable on Invoice Date. My Generator is below :

public class CustomGenerator  implements IdentifierGenerator { 

    @Override
    public Serializable generate(SharedSessionContractImplementor sessionImpl, Object data)
    throws HibernateException {
        Serializable result = null;
        Connection connection = null;
        Statement statement = null;
        ResultSet resultSet = null;
        try {
            String prefix = "";

            DateTimeFormatter newPattern = DateTimeFormatter.ofPattern("yyyyMM"); 

            LocalDate ldObj = LocalDate.now();
            String yyyymm = newPattern.format(ldObj).toString();
            prefix = "INV/"+yyyymm+"/";
            connection = sessionImpl.connection();
            statement = connection.createStatement();                   
             try {  
                 resultSet = statement.executeQuery("select max(id)+1 from invoice");
             } catch(Exception ex) {

             }

            if(resultSet.next()) {
                int nextValue = resultSet.getInt(1);                
                String suffix = String.format("%05d", nextValue + 1);               
                result = prefix.concat(suffix);
                System.out.println("Custom generated Sequence value : "+result);
            } else
            {
                 int nextValue = 1;                
                 String suffix = String.format("%05d", nextValue + 1);               
                 result = prefix.concat(suffix);    
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return result;
    }


}
Shiv1987
  • 21
  • 4

0 Answers0