2

Please help me here. I am new to Hibernate. Done the setup successfully. But when I run the code with different values, the values in the table are getting over written. I've no idea what is going wrong. Here is my code:

UserDetails.java

package com.hibernate;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
@Table(name="User_Details")
public class UserDetails {

    @Id
    private int id;
    private String name;
    private String phonenumber;

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getPhonenumber() {
        return phonenumber;
    }
    public void setPhonenumber(String phonenumber) {
        this.phonenumber = phonenumber;
    }
    public int getId() {
        return id;
    }
    public void setId(int id) {
        this.id = id;
    }


}

GetUserDetails.java

package com.hibernate;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;

@SuppressWarnings("deprecation")

public class GetUserDetails {

    public static void main(String[] args) {
        UserDetails ud = new UserDetails();
        ud.setId(3);
        ud.setName("User3");
        ud.setPhonenumber("9988555774");

        SessionFactory sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
        Session session = sessionFactory.openSession();

        session.beginTransaction();
        session.save(ud);
        session.getTransaction().commit();
        session.close();
        sessionFactory.close();
    }

}

When I run the above code, with the values "3", "User3", "9988555774" is getting inserted into the table.

But if I run the code again with the values "4", "User4", "9988547774", then the old value is getting over written and the new values are inserted correctly.

Please help me as I don't know what I'm missing.

Alexis C.
  • 91,686
  • 21
  • 171
  • 177

1 Answers1

0

I beleive you've added the following line in your hibernate.cfg.xml.

<property name="hbm2ddl.auto">create</property>

Try changing "create" to "update", as shown below:

<property name="hbm2ddl.auto">update</property>

Refer the following link for more info about the above property values:

Hibernate hbm2ddl.auto possible values and what they do?

Hibernate: hbm2ddl.auto=update in production?

Community
  • 1
  • 1
Gokul Nath KP
  • 15,485
  • 24
  • 88
  • 126
  • Yes, I've that line. But if I do not add, then table is not getting created. Does changing to "update" create table? – user3046536 Nov 28 '13 at 15:56