0

I am trying to add a unique constraint on a column but it works if I recreate database but doesn't work when I update already existing database.

Similar with adding unique to index. Is there a reason why hibernate doesn't update column if database already exists? I am using Dropwizard.

@Entity
@Table(name = EnrollmentStatusEntity.TABLE_NAME,
        indexes = {
            @Index(name = Student_RollNo,
                    columnList = rollNo,
                    unique = true)
        })
@Data
public class Student {
    public static final String TABLE_NAME = "Student";

    @Id
    @NonNull
    @Column(name = ID, unique = true, updatable = false, nullable = false)
    private String id;

    @NonNull
    @Column(name = COMPARTMENT_ID, unique=true, nullable = false, updatable = false)
    private String rollNo;
D86658
  • 11
  • 2
  • 1
    You would need to use `spring.jpa.hibernate.ddl-auto=update` (or similar property, that's what Spring Boot uses) to have Hibernate update the database schema. – Kayaman Nov 17 '20 at 19:14
  • Does this work for any schema changes in entities ? Does this work with dropwizard as well ? – D86658 Nov 17 '20 at 19:36
  • 1
    ddl-auto=update would drop and create a new schema does this mean all the data will be lost on recreation ? https://docs.jboss.org/hibernate/orm/4.3/manual/en-US/html_single/ – D86658 Nov 17 '20 at 19:52
  • Yeah could be. The annotations for constraints or indexes aren't very useful since you'll never know if they represent the true state of the database, and they're a poor tool for schema definition anyway. – Kayaman Nov 17 '20 at 20:26

2 Answers2

0

Try to add this on your existing Hibernate class settings.put(Environment.HBM2DDL_AUTO, "update");

it should work with this code but be careful when adding a table to the db if the table isnt NULL then it wont update the db (must be 0 on creating 1st time then change value inside the code or through the browser)

0

You can control the hibernate's automatic schema generation through your dropwizard project's configuration yaml file:

database:
  properties:
    hibernate.hbm2ddl.auto: update

This will update the schema automatically every time you run the application, if your db properties are otherwise correctly set in the configuration file.

This is usually not a good idea for production use.

Dropwizard Migrations uses Liquibase to track, version and deploy database changes. I would recommend using Dropwizard Migration and setting hibernate.hbm2ddl.auto: validate, that way you manage the database schema changes with Liquibase and validate with hibernate that the database schema matches the java entities.

Jenneth
  • 351
  • 1
  • 10