Powered by Blogger.

Friday, 12 December 2014

Sequence generator

By Unknown  |  00:06 No comments

There are different ways to generate sequence
1) Automatic
2) Custom

1) Automatic
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE,generator= "countryid-gen")
@SequenceGenerator(name = "countryid-gen", sequenceName = "COUNTRY_SEQ",
              allocationSize = 1, initialValue = 0)
@Column(name = "COUNTRY_ID")

private int id;

2) Custom 
First need to create 
a) Custom Class, then 
b) implement that custom class.

a) Custom Class
package com.pristine.util;

import java.io.Serializable;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.HibernateException;
import org.hibernate.engine.spi.SessionImplementor;
import org.hibernate.id.IdentifierGenerator;

public class EmployeeCodeGenerator implements IdentifierGenerator {


    public Serializable generate(SessionImplementor session, Object object)
            throws HibernateException {

        String prefix = "E";
        Connection connection = session.connection();
        try {

            PreparedStatement ps = connection
                    .prepareStatement("SELECT nextval ('EMPLOYEE_SEQ') as nextval");

            ResultSet rs = ps.executeQuery();
            if (rs.next()) {
                int id = rs.getInt("nextval");
                String code = prefix + StringUtils.leftPad("" + id,3, '0');
                return code;
            }

        } catch (SQLException e) {
            throw new HibernateException(
                    "Unable to generate Stock Code Sequence");
        }
        return null;
    }
}


b) Implementation of Custom Class
@Id
@GenericGenerator(name="seq_id", strategy="com.pristine.util.EmployeeCodeGenerator")
@GeneratedValue(generator="seq_id")
@Column(name = "ID", nullable = false)
private String id;



Author: Unknown

Hello, I am Author, decode to know more: In commodo magna nisl, ac porta turpis blandit quis. Lorem ipsum dolor sit amet, consectetur adipiscing elit. In commodo magna nisl, ac porta turpis blandit quis. Lorem ipsum dolor sit amet.

0 comments:

Recent Articles

© 2014 Learning Java. WP themonic converted by Bloggertheme9. Published By Gooyaabi Templates
TOP