JPA - Primary key prefix - java

We have a table where the ID is generated by a trigger -
ID = year+month+sequence
I mapped the table via JPA and I would like to use the same PK generation in my code as well. I tried the following options:
#Id
#SequenceGenerator(name = "assetSeq", sequenceName = "ASSET_SEQ")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "assetSeq")
#Transient
private long id;
and also tried to change the setter
public void setId(long id) {
String finalId=getIdPrefix()+id;
this.id = Long.parseLong(finalId);
}
private String getIdPrefix() {
DateFormat df = new SimpleDateFormat("YYYYMM");
Date today = Calendar.getInstance().getTime();
return df.format(today);
}
but non of them worked. I just want to insert new record in the database and do not want to use the id later. I use Hibernate for JPA

You can do this if you implement custom Hibernate generator. This blog has almost identical example to what you need. I'll post here the code from the blog adjusted to your needs (might not work if you copy-paste it, but it will be close)
public class CustomIdGenerator implements IdentifierGenerator {
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {
String prefix = getIdPrefix();
Connection connection = session.connection();
try {
PreparedStatement ps = connection
.prepareStatement("SELECT nextval ('ASSET_SEQ') as nextval"); // could be different, depending on database vendor
ResultSet rs = ps.executeQuery();
if (rs.next()) {
int id = rs.getInt("nextval");
String code = prefix + id;
return code;
}
} catch (SQLException e) {
throw new HibernateException(
"Unable to generate ID");
} finally {
if (ps != null) {
try {
ps.close();
} catch (Throwable e) {
// log error, or rethrow exception
}
}
}
return null;
}
private String getIdPrefix() {
DateFormat df = new SimpleDateFormat("YYYYMM");
Date today = Calendar.getInstance().getTime();
return df.format(today);
}
}
#Id
#GenericGenerator(name="seq_id", strategy="my.package.CustomIdGenerator")
#GeneratedValue(generator="seq_id")
// don't put that #Transient here
private long id;
Hope this helps.

Related

How to map resultset into composite object in mapper class

I have query which will return 8 columns for order placement POC, First 4 will be same for few rows(person details) and remaining 4 alone will differ(order details). Its a non normalized table.
COL1 COL2 COL3 COL4 COL5 COL6 COL7 COL8
-----------------------------------------------------
a aaa bbb ccc ddd eee fff ggg
a aaa bbb ccc hhh iii jjj kkk
My object looks like
class OrderBook{
int id;
int name;
String age;
String mailId;
List<Order> orderList;
}
class Order{
String productName;
int price;
int quantity;
String address;
}
how can i loop through the result set and map the rows into the Orderbook object. Response should look something like below
{
"id": 1,
"name": "dude",
"age" : 22,
"mailId": "dude#abc.com",
"orderList": [
{
"productName": "Milk",
"price":23,
"quantity":2,
"address": "dude, 1st street"
},
{
"productName": "Egg",
"price":5,
"quantity":10,
"address": "dude, 1st street"
}
]
}
I dont know how to loop it here
while(rs.next()){
???
}
You should convert resultset to DataObject (OrderBook) firstly.
List<OrderBook> list = new ArrayList<>();
while(rs.next()){
OrderBook orderBook = mapToOrderBook(rs);
list.add(orderBook);
}
Few basic functions which you should write.
private List<OrderBook> getOrderBooks();
private OrderBook mapToOrderBook(ResultSet rs);
If you don't know how to get data from resultset:
https://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
Then you can use jackson to convert List to json data.
Spring mvc already handled it for you.
#RequestMapping("/orderbooks")
public List<OrderBook> getOrderBooks() {
return orderbookService.getOrderBooks();
}
If you are using ResultSet directly you have to implement transformers directly from RS to Object instance. And use it from your DAO layer Something like:
#Override
public User getByID(int id) {
OrderBook book = new OrderBook();
try {
PreparedStatement select = OrderBookTransformer.getInstance().getSelectStatementById(id);
ResultSet rs = select.executeQuery();
while (rs.next()) {
book = OrderBookTransformer.getInstance().fromRsToObject(rs);
}
} catch (SQLException e) {
log.error(e);
}
return book;
}
Where OrderBookTransformer could be like:
#Override
public OrderBook fromRsToObject(ResultSet rs) {
OrderBook book = new OrderBook();
try {
user.setId(rs.getInt("id"));
user.setName(rs.getInt("name"));
user.setAge(rs.getString("age"));
// set other fields
} catch (SQLException e) {
log.error(e);
}
return user;
}
For the initialisation transformer I used the Singleton pattern:
public class OrderBookTransformer implements BaseTranformer<OrderBook> {
private static final Logger log = Logger.getLogger(OrderBookTransformer.class);
private static OrderBookTransformer instance = null;
protected OrderBookTransformer() {
}
public static OrderBookTransformer getInstance() {
if (instance == null) {
instance = new OrderBookTransformer();
}
return instance;
}
And select statement something like:
#Override
public PreparedStatement getSelectStatementById(int id) {
PreparedStatement select = null;
try (Connection connection = ConnectionManager.getConnection()) {
select = connection
.prepareStatement("SELECT FROM order_books WHERE id = ?");
select.setInt(1, id);
} catch (SQLException e) {
log.error(e);
}
return select;
}
My suggestion will be to use Spring Data instead of processing the Result Set directly.
You will need to do just a few more steps:
add spring data dependency to your build tool
add JPA annotations to your model with relations to it:
#Entity
class OrderBook {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private Integer name;
private String age;
private String mailId;
#ElementCollection(targetClass = Order.class, fetch = FetchType.EAGER)
#CollectionTable(name = "orders", joinColumns = #JoinColumn(name = "book_id"))
private List<Order> orderList;
// no args constructor + getters/setters
}
#Entity
class Order {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private String productName;
private Integer price; // consider use Double here
private Integer quantity;
private String address;
}
create a repository for this class:
public OrderBookRepository implements JpaRepository<OrderBook, Integer> {}
and use it for retrieving data from DB.

Need to save two tables from different jsp pages with foreign key relationship using hibernate dao implementation method

Image of table relationship reference
After submit from bank jsp page and after submit from card jsp all in one image because of limitation of newbie
I am new to stackoverflow as well SPRING. I have tried to create two tables with foreign key concept . I have followed some examples on stackoverflow as well as from other resourcefull websites and manged to create two tables with onetomany relationship. But the problem is i have to get the first row id under cart_id column when i submit from card jsp page. Instead after submit from card jsp page there is new row created under bankadmin table and it's id is being returned. I am confused and have no idea how to correct ot resolve this issue. Please be kind and guide me. And also i have been searching for a week in stackoverflow couldn't find anything that helped me. Thanks in advance.
Bankadmin Model
#Entity
#Table(name = "bankAdmin")
public class bankAdmin implements Serializable{
#GeneratedValue(strategy=GenerationType.AUTO)
#Column (name = "bcode", nullable=false)
#Id private int bcode;
#Column (name = "bname")
private String bname;
#Column (name = "address")
private String address;
#Column (name = "phno")
private int phno;
#OneToMany(mappedBy="bankAdmin",cascade = CascadeType.ALL)
private Set<Cards> cards;
Card model
#Entity
#Table(name = "cards")
public class Cards implements Serializable {
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="cname", unique=true)
#Id private int cname;
#Column (name = "ctype")
private String ctype;
#Column (name = "min_sal")
private int min_sal;
#Column (name = "year_fee")
private int year_fee;
#Column (name = "rewards")
private String rewards;
#Column (name = "jperks")
private String jperks;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="cart_id", nullable=false)
private bankAdmin bankAdmin;
public Cards(){}
public Cards(String ctype, int min_sal, int year_fee, String rewards, String jperks, bankAdmin b){//int cname,
this.ctype=ctype;
this.min_sal=min_sal;
this.year_fee=year_fee;
this.jperks=jperks;
this.rewards=rewards;
this.bankAdmin=b;
}
public bankAdmin getBankAdmin() {
return bankAdmin;
}
public void setBankAdmin(bankAdmin bankAdmin) {
this.bankAdmin = bankAdmin;
}
CardDaoImpl
public class CardsDaoImpl implements CardsDao{
#Autowired
SessionFactory sessionfactory;
public void save(Cards cards) {
Session session = null;
Transaction tx = null;
try
{
session = this.sessionfactory.openSession();
tx = session.beginTransaction();
bankAdmin bankadmin =new bankAdmin(); //=null;
String _ctype = cards.getctype();
int _min_sal = cards.getmin_sal();
int _year_fee = cards.getyear_fee();
String _rewards = cards.getrewards();
String _jperks = cards.getjperks();
Set<Cards> card = new HashSet<Cards>();
Cards config = new Cards(_ctype,_min_sal,_year_fee,_rewards,_jperks,bankadmin);
card.add(config);
bankadmin.setcards(card);
// System.out.println("bankadmin: before " + bankadmin);
// bankadmin.setbname(bankadmin.getbname());// "SBI"
// bankadmin.setphno(bankadmin.getphno());//1234567890
// bankadmin.setaddress(bankadmin.getaddress());//Bengaluru
// System.out.println("bankadmin: after " + bankadmin);
// int _cname = cards.getcname();
// int bankadmin = bankadmin.getbcode();
//_cname,_ctype,_min_sal,_year_fee,_rewards,_jperks,bankadmin
// card.add(config);
// config.setBankAdmin(cards.getBankAdmin(bankadmin));
// config.setcname(cards.getcname());
// config.setctype(cards.getctype());
// config.setmin_sal(cards.getmin_sal());
// config.setyear_fee(cards.getyear_fee());
// config.setrewards(cards.getrewards());
// config.setjperks(cards.getjperks());
// config.setBankAdmin(cards.getBankAdmin());
session.save(bankadmin);
session.save(config);
tx.commit();
}
catch (HibernateException e)
{
e.printStackTrace();
}
finally
{
session.close();
}
}
// get lms lights config from DB
public List<Cards> Ccards() {
Session session = null;
// Transaction tx = null;
List<Cards> Ccards = null;
try{
session = this.sessionfactory.openSession();
Ccards = session.createQuery("FROM Cards").list();
System.out.println("cards dao impl executed...");
System.out.println("cards config : "+ Ccards.toString());
}
catch (Exception e)
{
System.out.println("bankAdmin Dao impl Ex : " + e);
}
finally
{
session.close();
}
return Ccards;
}
}
BankDaoImpl
public class bankAdminDaoImpl implements bankAdminDao{
#Autowired
SessionFactory sessionfactory;
public void save(bankAdmin badmin) {
Session session = null;
Transaction tx = null;
try
{
session = this.sessionfactory.openSession();
tx = session.beginTransaction();
// bankAdmin bankadmin = new bankAdmin();
bankAdmin config = new bankAdmin();
config.setbcode(badmin.getbcode());
config.setbname(badmin.getbname());
config.setaddress(badmin.getaddress());
config.setphno(badmin.getphno());
session.save(config);//save//persist
tx.commit();
}
catch (HibernateException e)
{
e.printStackTrace();
}
finally
{
session.close();
}
}
// get lms lights config from DB
public List<bankAdmin> BbankAdmin() {
Session session = null;
// Transaction tx = null;
List<bankAdmin> BbankAdmin = null;
try{
session = this.sessionfactory.openSession();
BbankAdmin = session.createQuery("FROM bankAdmin").list();
System.out.println("bankAdmin dao impl executed...");
System.out.println("bankAdmin config : "+ BbankAdmin.toString());
}
catch (Exception e)
{
System.out.println("bankAdmin Dao impl Ex : " + e);
}
finally
{
session.close();
}
return BbankAdmin;
}
}
Okay. I have posted the solution to your problem.
First of all, Spring framework is wonderful to work with. The framework got a lot of features, that you should take advantage of. I am not sure if I will be able to cover everything in this post, so please feel free to ask me.
I have created a simple Spring Boot application. I got total of 6 files that are important which is posted below.
Notice that I renamed your classes to CamelCase with capital starting letter. such as BankAdmin. This is considered the standard way of writing java classes. Also note that i renamed Cards to Card, so remember to rename your table in the database aswell. Also remember to rename the bankadmin table to bank_admin.
There are thee annotations that you have to look into. #Transactional, #Autowired, and PersistenceContext.
So a quick and easy explanation. #Transactional manages all transactions for you, so you do not have to begin and commit transactions. #Autowired creates objects for you, so you do not have to manage your object dependencies yourself. PersistenceContext basically creates and EntityManager for you and manages it for you. You do not have to create session nor EntitManagerFactory. These three annotations are explained very brief, so you should read about them yourself.
I also removed #Table(name = "bankAdmin") and #Table(name = "cards"). JPA can lookup these tables automatically if you follow the standard way of naming classes and database tables. It is actually pretty simple, but I still encourage you to look into this by yourself. In short, capital camelcase is turned into lowercase with _ inbetween each word that start with a capital letter. I.e. If your class name is BankAdmin then JPA will automatically look for table named bank_admin in your database.
application.properties - details about your database
spring.datasource.url=jdbc:mysql://localhost:3306/stackoverflow?useSSL=false
spring.datasource.username = root
spring.datasource.password = root
spring.jpa.show-sql = true
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.ddl-auto = update
The below code is only written to test the functionality
#SpringBootApplication
public class StackoverflowApplication {
public static void main(String[] args) {
ApplicationContext ctx = SpringApplication.run(StackoverflowApplication.class, args);
//Calling a class that is only made with the purpose of testing
Verification ts = ctx.getBean(Verification.class);
ts.run();
}
}
#Component
class Verification{
#Autowired
private BankAdminDao bad;
#Autowired
private CardsDao cd;
void run(){
//Create a new BankAdmin
BankAdmin ba = new BankAdmin();
ba.setAddress("someStreet");
ba.setPhno(12341234);
ba.setBname("myBanker");
//Create two cards and add them to a HashSet.
Card c1 = new Card("Visa", 1000, 1999, "Alot of", "Babes", ba);
Card c2 = new Card("Master Card", 2000, 500, "someThing", "anotherThing", ba);
Set<Card> cardList = new HashSet<>();
cardList.add(c1);
cardList.add(c2);
//Create a associatio between the BankAdmin and list of Cards
ba.setCards(cardList);
//Save them to the database.
bad.save(ba);
//Here we add a Card to an existing BankAdmin with the id 6 in the database.
//Create a new Card.
//The BankAdmin is set to null, because we not have not yet loaded the BankAdmin
Card c3 = new Card("Visa", 9999, 1337, "Alot of", "Male Babes", null);
//Save Card c3 with the BankAdmin id 6
cd.save(c3, 6);
}
}
BankAdmin
#Entity
public class BankAdmin implements Serializable{
#GeneratedValue(strategy=GenerationType.AUTO)
#Column (name = "bcode", nullable=false)
#Id private int bcode;
#Column (name = "bname")
private String bname;
#Column (name = "address")
private String address;
#Column (name = "phno")
private int phno;
#OneToMany(mappedBy="bankAdmin",cascade=CascadeType.ALL)
private Set<Card> cards;
//Getters and Setters have been removed to reduce the amount of code.
}
BankAdminDao
#Repository
//Transactional makes transaction automatical, so you do not have to begin and commit transactions yourself!
#Transactional
public class BankAdminDao{
//This makes your life a lot eaier!
//It will take care of your EntitManagerFactory and Sessions
#PersistenceContext
EntityManager em;
public void save(BankAdmin bank) {
em.merge(bank);
}
//get lms lights config from DB
public List<BankAdmin> getAllBankAdmin() {
List<BankAdmin> bankList = (List<BankAdmin>)em.createQuery("SELECT b FROM BankAdmin b");
return bankList;
}
public BankAdmin getBankAdmin(int bankId) {
return em.find(BankAdmin.class, bankId);
}
}
Card
#Entity
public class Card implements Serializable {
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="cname", unique=true)
#Id private int cname;
#Column (name = "ctype")
private String ctype;
#Column (name = "min_sal")
private int min_sal;
#Column (name = "year_fee")
private int year_fee;
#Column (name = "rewards")
private String rewards;
#Column (name = "jperks")
private String jperks;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name="cart_id", nullable=false)
private BankAdmin bankAdmin;
public Card(){}
public Card(String ctype, int min_sal, int year_fee, String rewards, String jperks, BankAdmin b){
this.ctype=ctype;
this.min_sal=min_sal;
this.year_fee=year_fee;
this.jperks=jperks;
this.rewards=rewards;
this.bankAdmin=b;
}
public BankAdmin getBankAdmin() {
return bankAdmin;
}
public void setBankAdmin(BankAdmin bankAdmin) {
this.bankAdmin = bankAdmin;
}
}
CardDao
#Repository
#Transactional
public class CardsDao{
#PersistenceContext
EntityManager em;
#Autowired
BankAdminDao bad;
public void save(Card cards, int bankId) {
BankAdmin bank = bad.getBankAdmin(bankId);
cards.setBankAdmin(bank);
bank.getCards().add(cards);
em.merge(bank);
}
public List<Card> getAllCards() {
List<Card> cardList = (List<Card>)em.createQuery("SELECT c FROM Cards c");
return cardList;
}
public Card getCard(int cardId){
return em.find(Card.class, cardId);
}
}

Hibernate not save Entity to oracle db

I made a small crud app using struts2,spring,hibernate with oracle db.
action class add methos is this.
public String addorgs() throws Exception {
t.setAO_CreatedBy("me");
t.setAO_Name("ok");
orgdao.addOrg(t);
// emplist = empdao.showEmployuee();
return SUCCESS;
}
Entity class for test:
#Entity
#Table(name="test")
public class Test {
#Id
#Column(name = "AO_ID")
#SequenceGenerator(name = "SequenceIdGenerator", sequenceName = "SEQ_AT_ORGANISATION",allocationSize=1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SequenceIdGenerator")
private int AO_ID;
#Column(name = "AO_Name")
private String AO_Name;
#Column(name = "AO_CreatedBy")
private String AO_CreatedBy;
public int getAO_ID() {
return AO_ID;
}
public void setAO_ID(int aO_ID) {
AO_ID = aO_ID;
}
public String getAO_Name() {
return AO_Name;
}
public void setAO_Name(String aO_Name) {
AO_Name = aO_Name;
}
public String getAO_CreatedBy() {
return AO_CreatedBy;
}
public void setAO_CreatedBy(String aO_CreatedBy) {
AO_CreatedBy = aO_CreatedBy;
}
}
DAO method :
public void addOrg(Test t) {
//System.out.println("save : "+org);
Session session = null;
session = sessionfactory.openSession();
try {
System.out.println("before save : "+t.getAO_ID());
session.save(t);
System.out.println("after save : "+t.getAO_ID());
} catch (Exception e) {
e.printStackTrace();
}
I didn't get any errors and data is not go to db. I test this code with mysql and it works fine. I think problem is with sequence.
out put is like this.
before save : 0
Hibernate:
select
SEQ_AT_ORGANISATION.nextval
from
dual
after save : 1
Can you try
public void addOrg(Test t) {
//System.out.println("save : "+org);
Session session = sessionfactory.openSession();
Transaction tx;
try {
tx = session.beginTransaction();
session.save(t);
tx.commit();
System.out.println("after save : "+t.getAO_ID());
} catch (Exception e) {
if (tx!=null) tx.rollback();
e.printStackTrace();
}finally {
session.close();
}

comparing time in sql server through hibernate

I am trying to compare time through hibernate in SQL Server 2008.
The following code returns this error : The data types time and datetime are incompatible in the less than or equal to operator.
crit = session.createCriteria(ObdBlackoutHours.class);
Criterion start = Restrictions.le("blackoutStart", new Date());
Criterion end = Restrictions.gt("blackoutEnd",new Date());
List list = crit.add(Restrictions.conjunction().add(start).add(end))
.list();
if(list.isEmpty())
return false;
else
return true;
The table design is the following:
CREATE TABLE [dbo].[obd_blackout_hours](
[id] [int] NOT NULL,
[blackout_end] [time](7) NOT NULL,
[blackout_start] [time](7) NOT NULL)
I understand that the db contains only 10:17:37 and what I am passing is something like this Thu Nov 14 10:17:37 IST 2013 which it is unable to compare. I tested the same code in mysql which seems to be working very fine. But SQL Server 2008 is creating the problem. I also tried passing
currentDate = new SimpleDateFormat("HH:mm:ss").parse(new SimpleDateFormat("HH:mm:ss").format(Calendar.getInstance().getTime()));
and
new ObdBlackoutHours(1,new Date(),new Date()).getBlackoutStart()
instead of the just the Date() object. This also fails. How should I compare time and get results.
The following is the entity class
#Entity
#Table(name = "obd_blackout_hours", schema = "dbo", catalog = "IVR_Data")
public class ObdBlackoutHours implements java.io.Serializable {
private int id;
private Date blackoutStart;
private Date blackoutEnd;
private Set<Service> services = new HashSet<Service>(0);
public ObdBlackoutHours() {
}
public ObdBlackoutHours(int id, Date blackoutStart, Date blackoutEnd) {
this.id = id;
this.blackoutStart = blackoutStart;
this.blackoutEnd = blackoutEnd;
}
public ObdBlackoutHours(int id, Date blackoutStart, Date blackoutEnd,
Set<Service> services) {
this.id = id;
this.blackoutStart = blackoutStart;
this.blackoutEnd = blackoutEnd;
this.services = services;
}
#Id
#Column(name = "id", unique = true, nullable = false)
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
#Temporal(TemporalType.TIME)
#Column(name = "blackout_start", nullable = false, length = 16)
public Date getBlackoutStart() {
return this.blackoutStart;
}
public void setBlackoutStart(Date blackoutStart) {
this.blackoutStart = blackoutStart;
}
#Temporal(TemporalType.TIME)
#Column(name = "blackout_end", nullable = false, length = 16)
public Date getBlackoutEnd() {
return this.blackoutEnd;
}
public void setBlackoutEnd(Date blackoutEnd) {
this.blackoutEnd = blackoutEnd;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "obdBlackoutHours")
public Set<Service> getServices() {
return this.services;
}
public void setServices(Set<Service> services) {
this.services = services;
}
}
Refer to the following blog:
http://blogs.msdn.com/b/jdbcteam/archive/2010/04/08/using-time-and-date-data-types-part-1-what-time-is-it.aspx
Need to add the following to your hibernate connection url string
I am not sure if it's true/false just play with it.
sendTimeAsDateTime=false

Can I create my own sequence in Hibernate?

Can I create my own sequence in Hibernate, like I have a database sequence and I have to add 2 characters before the sequence?
You can create your own identifier generator. Have a look at this blog post which is basically showing how to do something similar to what you're looking for (unless I misundertsood the question):
Custom Hibernate Sequence Generator for Id field
I have a table with a primary key in
the format M001, M002 etc (lets not
think about what happens after M999
for now). I’m using Hibernate
Annotations, and I found a great way
of generating the Primary Key value
for new Records:
First I created a database sequence to
use. Then I implemented
org.hibernate.id.IdentifierGenerator;
public class StockCodeGenerator implements IdentifierGenerator {
private static Logger log = Logger.getLogger(StockCodeGenerator.class);
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException {
String prefix = "M";
Connection connection = session.connection();
try {
PreparedStatement ps = connection
.prepareStatement("SELECT nextval ('seq_stock_code') as nextval");
ResultSet rs = ps.executeQuery();
if (rs.next()) {
int id = rs.getInt("nextval");
String code = prefix + StringUtils.leftPad("" + id,3, '0');
log.debug("Generated Stock Code: " + code);
return code;
}
} catch (SQLException e) {
log.error(e);
throw new HibernateException(
"Unable to generate Stock Code Sequence");
}
return null;
}
}
Then, in my entity class, I simply
annotate the id field like this:
#Id
#GenericGenerator(name="seq_id", strategy="my.package.StockCodeGenerator")
#GeneratedValue(generator="seq_id")
#Column(name = "stock_code", unique = true, nullable = false, length = 20)
public String getStockCode() {
return this.stockCode;
}
Try this one. With Date and Calender
public class StockCodeGenerator
implements IdentifierGenerator
{
private static Logger log = Logger.getLogger(StockCodeGenerator.class);
public StockCodeGenerator() {}
public int generateCustId()
{
Random random = new Random();
return random.nextInt(100);
}
public Serializable generate(SessionImplementor session, Object object)
throws HibernateException
{
String prefix = "Custom_String";
Connection connection = session.connection();
System.out.println(session.connection());
Date date = new Date();
Calendar calendar = Calendar.getInstance();
return prefix + "_" + generateCustId() + "_" + calendar.get(1);
}
}
And then use it in your #GenericGenerator annotation
#Id
#GenericGenerator(name="seq_id",strategy="com.mvc.StockCodeGenerator.
StockCodeGenerator")
#GeneratedValue(generator="seq_id")

Categories

Resources