Hibernate hbm2ddl = update,errors - 找不到表,Table已经存在

时间:2015-09-14 13:36:57

标签: java hibernate h2

使用hibernate和h2数据库。 我已经将hibernate.hbm2ddl.auto设置为' create',一切正常,db中的表已创建。 如果我评论这段代码,它也会起作用。但是,如果我需要更改架构,例如添加新字段我需要将其设置为“更新”,但是当我这样做时,即使我不改变架构和代码,我也会收到错误:

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]

当我将hbm2ddl.auto更改为“更新”时,为什么会出现错误?以及如何解决它? 我认为它无法找到表格,但是hibernate创建了它,现在无法看到它,为什么会这样呢?

我的代码:

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
}

0 个答案:

没有答案