1

Im working with hibernate and mysql, and i got it working to put data in the DB via hibernate, but when i try to retrieve data it always returns null...

Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
User user = (User) session.get(User.class, username);
session.getTransaction().commit();

User is a class with annotations, but the variable user will always be null, even if i put a username that i know exists in the DB. Username is the ID of the table, so it should find it

EDIT

Can it be that i use <property name="hbm2ddl.auto">create</property> in the config? What should i use so the DB create the table only if it does not exist?

Afra
  • 2,502
  • 3
  • 24
  • 27
  • what is the SQL being generated at the time of `session.get()` do you have `hibernate.show.sql` set to true – frictionlesspulley Oct 31 '11 at 02:17
  • Thanks, when i put it in and i get: Hibernate: drop table if exists user Hibernate: create table user (username varchar(255) not null, age integer, name varchar(255), password varchar(255), sex varchar(255), surname varchar(255), primary key (username)) when it does this: Session session = HibernateUtil.getSessionFactory().getCurrentSession(); Thus it is recreating the table :S – Afra Oct 31 '11 at 16:47

1 Answers1

1

the create schema option will delete all the existing data!
Check out the documentation : here

Following are the specified options:

  • validate: validate the schema, However no changes are made to the database.
  • update: update the schema.
  • create: creates the schema, destroying previous data.
  • create-drop: drop the schema at the end of the session.

Try using the update version. The rest of the code snippet looks fine to me.

Hope this helps

frictionlesspulley
  • 11,070
  • 14
  • 66
  • 115
  • checkout http://stackoverflow.com/questions/438146/hibernate-question-hbm2ddl-auto-possible-values-and-what-they-do which was asked along the same lines. – frictionlesspulley Oct 31 '11 at 17:35
  • Thanks, it worked! Is it an good idea using this method for serious development and deployment? – Afra Oct 31 '11 at 19:40