开发者

Problem in Hibernate

开发者 https://www.devze.com 2023-01-31 07:16 出处:网络
I have written a programto insert a row in the contact database which has a table called contact. When I execute the program, it runs without any errors and gives the following output --

I have written a program to insert a row in the contact database which has a table called contact. When I execute the program, it runs without any errors and gives the following output --

Hibernate: insert into CONTACT (FIRSTNAME, LASTNAME, EMAIL, ID) values (?, ?, ?, ?)

However, when I actually do a select * from contact; in mysql, I am not able to see the entries I entered through Hibernate. This is a bit surprising because there are no exceptions when I run my program. Any ideas on what I 开发者_Python百科am missing. I really appreciate your help in getting this resolved.

Below is the code:

public static void main(String[] args) {
Session session = null;

try{
// This step will read hibernate.cfg.xml and prepare hibernate for use
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
session =sessionFactory.openSession();
Contact contact = new Contact();
contact.setId(1);
contact.setFirstName("asdad");
contact.setLastName("Kumar");
contact.setEmail("deepak");
session.save(contact);
}catch(Exception e){
System.out.println(e.getMessage());
e.printStackTrace();
}finally{
session.flush();
session.close();

}

}


It seems you forgot to create a transaction:

SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
using (ISession session = sessionFactory.OpenSession())
{
 using (ITransaction transaction = session.BeginTransaction())
 {
  Contact contact = new Contact();
  contact.setId(1);
  contact.setFirstName("asdad");
  contact.setLastName("Kumar");
  contact.setEmail("deepak");
  session.save(contact);
  transaction.Commit();
 }
}

You might want to have a look at the nhibernate tutorial.


What is your mapping for Contact class? How does you Hibernate configuration look like? There is a possibility that you do not have connection with database.


 Session session =  new Configuration().configure().buildSessionFactory(); 
Transaction transaction = session.beginTransaction();   
transaction.begin();
Contact contact = new Contact(); 
contact.setId(1); 
contact.setFirstName("asdad"); 
contact.setLastName("Kumar"); 
contact.setEmail("deepak");
session.save(contact);
transaction.commit();
session.close();
0

精彩评论

暂无评论...
验证码 换一张
取 消