Working with hibernate and h2 database. I've set hibernate.hbm2ddl.auto to 'create', all works fine, table in db was created. If I comment this code it will work too. But if I need to change schema e.g. add new field I need to set it to 'update, but when I do it I get an error even if I din't change schema and code:
INFO: HHH000262: Table not found: Car
Exception in thread "main" java.lang.ExceptionInInitializerError
Caused by: org.hibernate.tool.schema.spi.SchemaManagementException: Unable to execute schema management to JDBC target [create table Car (id bigint not null, color varchar(255), name varchar(255), driver_id bigint, primary key (id))]
Caused by: org.h2.jdbc.JdbcSQLException: Table "CAR" already exists; SQL statement:
create table Car (id bigint not null, color varchar(255), name varchar(255), driver_id bigint, primary key (id)) [42101-188]
Why do I get an error when I change hbm2ddl.auto to 'update' and how to fix it? As I see it can't find table, but it there hibernate created it, and now can't see it, why so?
My code:
public class Service {
private final SessionFactory ourSessionFactory;
private final ServiceRegistry serviceRegistry;
public Service(Class... classes){
try {
Configuration configuration = new Configuration()
.addProperties(ConnectionProperties.getH2(true))
/*.addAnnotatedClass(Car.class)
.addAnnotatedClass(Driver.class)
.addAnnotatedClass(House.class)*/;
for (Class clas: classes) {
configuration.addAnnotatedClass(clas);
}
serviceRegistry = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties()).build();
ourSessionFactory = configuration.buildSessionFactory(serviceRegistry);
} catch (Throwable ex) {
throw new ExceptionInInitializerError(ex);
}
}
public Session getSession() throws HibernateException {
return ourSessionFactory.openSession();
}
}
public class CarService extends Service {
public CarService() {
super(Car.class, Driver.class);
}
public List<Car> getAllCars() {
final Session session = getSession();
List<Car> cars;
try {
session.beginTransaction();
cars = session.createQuery("from Car").list();
session.getTransaction().commit();
} finally {
session.close();
}
return cars;
}
public void addCar(Car car) {
final Session session = getSession();
try {
session.beginTransaction();
session.save(car);
session.getTransaction().commit();
} finally {
session.close();
}
}
}
@Entity
public class Car {
@Id
@GeneratedValue
private long id;
private String color;
private String name;
@OneToOne(cascade = javax.persistence.CascadeType.ALL)
private Driver driver;
//getters and setters
}