tags:

views:

33

answers:

2

I am new in Hibernate.when i save particular entity then it rewrite data from existing one.

I have used ID as auto generated as below:

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
@Column(name="id")
private int id;

Here i save Entity as below:

class StudDAO() {

public static void main(String[] args){
     StudDAO obj = new StudDAO();
     Stud stud = new Stud();
     stud.setName("Test");
     stud.setCity("Mumbai");
     obj.createStud(stud);
}

public void createStud(Stud stud) {
  try {

    Session session = HibernateSessionFactory.getSessionFactory().openSession();
    Transaction transaction = session.beginTransaction();
    session.save(stud);
    transaction.commit();

    } catch (Exception e) {
      // TODO: handle exception
       e.printStackTrace();
       transaction.rollback();
    }
}

}

if i will change entity value next time then it should generate next id rather than starting form 1st id.

any time result would be same like

mysql> select * from stud;

+----+--------+------+
| id | city   | name |
+----+--------+------+
|  1 | Mumbai | Test |
+----+--------+------+

1 row in set (0.00 sec)

what i want is in result like below:

mysql> select * from stud;
+----+--------+------+
| id | city   | name |
+----+--------+------+
|  1 | Mumbai | Test |
|  2 | Mumbai | Test |
+----+--------+------+
2 rows in set (0.00 sec)

Please help me for same..

A: 

If you are wanting to do an update rather than adding a new row to the database each time then you need to retrieve the desired entity, make any desired updates, and then save the entity again.

Derek Greer
A: 

Try using saveOrUpdate(..)

Note that JPA (Hibernate) entities are identified by their @Id. If your object has the same id as the one in the db, an update will occur. Otherwise, logically, insert will happen.

Bozho
From his example, it looks like he is running a command line example and expecting subsequent executions to not add new entries to the database.
Derek Greer
Yes that's true..but is there any other way for that ? if i insert different entity value then it just rewrite data from existing one rather than making new record..if maximum id of my table is 2 then next inserted data should be on 3rd.but it just started from 1st.
ruchiworlds