У меня есть небольшое приложение, и я хочу, чтобы hibernate создавал таблицы, если не существует. У меня есть все необходимые аннотации (я думаю), и mi hibernate.cfg. xml завершен, но когда я запускаю тест, чтобы проверить, верен ли метод dao, hibernate покажет мне исключение, говорящее, что отношения не существуют. Когда я проверяю базу данных, таблиц нет.
Я хочу знать, является ли способ сделать Hibernate для автоматического создания таблиц или мне нужно добавить какой-то новый код или свойства в мой код.
hibernate.cfg. xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<!-- SQL Dialect -->
<property name="dialect">org.hibernate.dialect.PostgreSQLDialect</property>
<!-- Connection Settings -->
<property name="connection.driver_class">org.postgresql.Driver</property>
<property name="connection.url">jdbc:postgresql://localhost:5432/tour_bi</property>
<property name="connection.username">xxx</property>
<property name="connection.password">xxx</property>
<property name="current_session_context_class">thread</property>
<!-- SQL to stdout -->
<property name="show_sql">true</property>
<!-- Update database on startup -->
<property name="hbm2dll.auto">create</property>
<!-- Annotated entity classes -->
<mapping class="domain.Car_Type"/>
<mapping class="domain.Car"/>
<mapping class="domain.Client"/>
<mapping class="domain.Country"/>
<mapping class="domain.Guide"/>
<mapping class="domain.Imagen"/>
<mapping class="domain.Languaje"/>
<mapping class="domain.Province"/>
<mapping class="domain.Stop"/>
<mapping class="domain.System"/>
<mapping class="domain.Tour_Type"/>
<mapping class="domain.System"/>
<mapping class="domain.Tour"/>
</session-factory>
</hibernate-configuration>
База данных существует в publi c schema
, это мой тестовый класс
public class TestDB {
@Test
public void crudTest() {
Configuration configuration= new Configuration();
configuration.configure();
SessionFactory factory=configuration.buildSessionFactory();
Session session=factory.openSession();
createCarTYpe(session);
createCar(session);
readCar(session);
updateCar(session);
readCar(session);
deleteCar(session);
readCar(session);
session.close();
}
private void deleteCar(Session session) {
// TODO Auto-generated method stub
System.out.println("Eliminando Auto");
Car car=(Car)session.get(Car.class,1);
session.beginTransaction();
session.delete(car);
session.getTransaction().commit();
}
private void updateCar(Session session) {
// TODO Auto-generated method stub
System.out.println("Actualizando Auto");
Car car=(Car)session.get(Car.class,1);
car.setCant_people(10);
session.beginTransaction();
session.saveOrUpdate(car);
session.getTransaction().commit();
}
private void createCar(Session session) {
// TODO Auto-generated method stub
System.out.println("Creando Autos");
Car carA=new Car();
carA.setCant_people(5);
carA.setCar_type(Car_TypeDAO.getCarType(0));
carA.setTours(new ArrayList<Tour>());
Car carB=new Car();
carB.setCant_people(5);
carB.setCar_type(Car_TypeDAO.getCarType(0));
carB.setTours(new ArrayList<Tour>());
session.beginTransaction();
session.save(carA);
session.save(carB);
session.getTransaction().commit();
}
private void readCar(Session session) {
// TODO Auto-generated method stub
Query q=session.createQuery("select car from car");
ArrayList<Car> cars = (ArrayList<Car>) q.list();
System.out.println("Leyendo Autos");
for(Car c:cars) {
System.out.println(c.toString());
}
}
private void createCarTYpe(Session session) {
// TODO Auto-generated method stub
System.out.println("Creando Autos");
Car_Type carA=new Car_Type();
carA.setActive(true);
carA.setType("Deportivo");
session.beginTransaction();
session.save(carA);
session.getTransaction().commit();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
}
}
и это одна из моих моделей
@Entity
@Table(name="car_type")
public class Car_Type {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name="_id", unique = true)
private long _id;
@Column(name="active")
private boolean active;
@Column(name="type")
private String type;
@OneToOne(mappedBy = "car_type")
private Car car;
public Car_Type(boolean active, String type,Car car) {
super();
this.active = active;
this.type = type;
this.car=car;
}
public Car_Type() {
super();
// TODO Auto-generated constructor stub
}
public long get_id() {
return _id;
}
public void set_id(long _id) {
this._id = _id;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Car getCar() {
return car;
}
public void setCar(Car car) {
this.car = car;
}
@Override
public String toString() {
return "Car_Type [active=" + active + ", type=" + type + "]";
}
}
это лог в консоли
log4j:WARN Please initialize the log4j system properly.
06:06:29.838 [main] INFO org.hibernate.annotations.common.Version - Hibernate Commons Annotations 3.2.0.Final
06:06:31.101 [main] INFO org.hibernate.validator.util.Version - Hibernate Validator 4.0.2.GA
06:06:31.105 [main] DEBUG org.hibernate.validator.engine.ResourceBundleMessageInterpolator - ValidationMessages not found. Delegating to org.hibernate.validator.ValidationMessages
06:06:31.110 [main] DEBUG org.hibernate.validator.engine.resolver.DefaultTraversableResolver - Found javax.persistence.PersistenceUtil on classpath.
06:06:31.112 [main] INFO org.hibernate.validator.engine.resolver.DefaultTraversableResolver - Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
06:06:31.116 [main] DEBUG org.hibernate.validator.xml.ValidationXmlParser - No META-INF/validation.xml found. Using annotation based configuration only
06:06:31.196 [main] DEBUG org.hibernate.validator.engine.ResourceBundleMessageInterpolator - ValidationMessages not found. Delegating to org.hibernate.validator.ValidationMessages
06:06:31.196 [main] DEBUG org.hibernate.validator.engine.resolver.DefaultTraversableResolver - Found javax.persistence.PersistenceUtil on classpath.
06:06:31.197 [main] INFO org.hibernate.validator.engine.resolver.DefaultTraversableResolver - Instantiated an instance of org.hibernate.validator.engine.resolver.JPATraversableResolver.
06:06:31.203 [main] DEBUG org.hibernate.validator.xml.ValidationXmlParser - No META- INF/validation.xml found. Using annotation based configuration only
Creando Autos
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into car_type (active, type, _id) values (?, ?, ?)
нет ничего, что говорило бы о том, что hibernate создает какие-либо таблицы, идет речь о создании объектов и в моем Журнал испытаний:
org.hibernate.exception.SQLGrammarException: ERROR: no existe la relación «car_type»
Position: 13
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:122)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:47)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:125)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:110)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:129)
at org.hibernate.engine.jdbc.internal.proxy.AbstractProxyHandler.invoke(AbstractProxyHandler.java:81)
at com.sun.proxy.$Proxy18.executeUpdate(Unknown Source)
at org.hibernate.engine.jdbc.batch.internal.NonBatchingBatch.addToBatch(NonBatchingBatch.java:56)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2849)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3290)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:80)
at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:272)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:264)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:186)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:326)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:52)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1081)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:315)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:175)
at test.TestDB.createCarTYpe(TestDB.java:98)
at test.TestDB.crudTest(TestDB.java:28)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:59)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:56)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:305)
at org.junit.runners.BlockJUnit4ClassRunner$1.evaluate(BlockJUnit4ClassRunner.java:100)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:365)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:103)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:63)
at org.junit.runners.ParentRunner$4.run(ParentRunner.java:330)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:78)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:328)
at org.junit.runners.ParentRunner.access$100(ParentRunner.java:65)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:292)
at org.junit.runners.ParentRunner$3.evaluate(ParentRunner.java:305)
at org.junit.runners.ParentRunner.run(ParentRunner.java:412)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:89)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:41)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:541)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:763)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:463)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:209)
Caused by: org.postgresql.util.PSQLException: ERROR: no existe la relación «car_type»
Position: 13
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2505)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2241)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:310)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:447)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:368)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:158)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:124)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.hibernate.engine.jdbc.internal.proxy.AbstractStatementProxyHandler.continueInvocation(AbstractStatementProxyHandler.java:122)
... 43 more
Я использую tomcat server 9. Нужно ли мне обновлять web. xml на моем tomcat?
это моя база данных