• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

how to check record in db table before inserting data, whether that is available or needs to be inse

 
santosh kimothi
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
before inserting the record i want to check whether the record is present or not,
so to check this i am calling checkEmail() function, if record is there then it should return false, but its not working
public boolean insertRecord(RegistrationPojo registrationPojo) {

boolean status = false;

transaction = session.beginTransaction();
String email = registrationPojo.getEmail();
if(checkEmail(email))
{
try
{

session.save(registrationPojo);
transaction.commit();
status = true;
return status;
}
catch(Exception exception)
{

transaction.rollback();
exception.printStackTrace();
}
return status;

}
else
{
return status;
}

}
private boolean checkEmail(String email)
{
boolean valid = false;

RegistrationPojo pojo = null;
Transaction transaction = session.beginTransaction();
try{
pojo =(RegistrationPojo)session.load(RegistrationPojo.class, email);
transaction.commit();
}
catch (Exception e) {
e.printStackTrace();
}
if(pojo == null)
{
valid = true;
return valid;
}
else
{
return valid;
}
}
 
hayden wangg
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Is the "email" the PK?
From your code pojo =(RegistrationPojo)session.load(RegistrationPojo.class, email);
I think the email must be the PK, so you needn't check it.
Each time before Hibernate to insert one object, if it found the object's PK is not null, it will take this "insert" as "update" if it finds the exsiting object in the DB.
If you debug into Hibernate's source code, you would find the session.save(registrationPojo) will call the session.saveOrUpdate(registrationPojo);
 
santosh kimothi
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
no email is not a primary key, but i should be able to get data based on any column in hibernate also
 
hayden wangg
Greenhorn
Posts: 11
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
The second parameter in the session.load() and session.get() should be the primary key of the class.
I think this is just the cause you could not search any record.
 
santosh kimothi
Ranch Hand
Posts: 32
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
ya that was true, and after making the email as a primary key, it is working fine,
again thanks for your suggestions
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic