6
votes

I am learning hibernate . I am bit confused with hbm2dll.auto update property . Change in model object data type is not changing data type of table in mysql.

Firstly I have created User Pojo with userId as data type int . Initially I have made hbm2dll property as CREATE .

@Entity(name="user")
public class User {
    @Id
    private int userid; 
    private String username;
    ....

}

For persisting data firstly I have created user object like below and saved using sessionFactory .

User user = new user();
     user.setUserid(1);
     user.setUsername("First User");

Because of above effort User table got created where userid data is int.

But later I changed the pojo’s userid data type to string .

Also I changed hbm2ddl property to update .

So after this change even user object is having string as userid , table userid data type is not changing to varchar . How to change the data type of table using hibernate .

3

3 Answers

2
votes

I believe update can not change the data type.

Imagine the field of type string will be change to Integer. What will happen to existing data?

So update (data type update) can not be guaranteed if the table is not empty.

2
votes

As per my understanding hibernate will not allow you to update field datatype directly, for this we have to take backup of the current field and then need to create new field and then copy backup data in new field.

And If I am wrong, please correct me too.

1
votes

If you don't want to loose old data, you can manually do the following:

  1. add new optional column with NEW data type
  2. update the new column with values of the old column (using convert)
  3. drop the old column
  4. rename the new column (not all dialects support this)
  5. mark the column as not-null (optional)