При использовании стратегии Hibernate GenerationType.Table
, нам нужно иметь таблицу, уже созданную в базе данных для генерации ключа, или Hibernate может создать ее самостоятельно, если данные не предоставлены?
Я искал это в Интернете и не мог найти удовлетворительный ответ.
В моем коде при использовании типа AUTO
он выбирает стратегию Table
, которая генерирует исключение, которое связано с отсутствием таблицы для генерации ключа в MySQL DB. Просто нужно подтвердить, если это ожидаемое поведение.
ERROR
DEBUG - select tbl.next_val from hibernate_sequences tbl where tbl.sequence_name=? for update
ERROR - HHH000351: Could not read or init a hi value
java.sql.SQLSyntaxErrorException: Table 'ifinances.hibernate_sequences' doesn't exist
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:955)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:1005)
at org.hibernate.id.enhanced.TableGenerator.executeQuery(TableGenerator.java:705)
at org.hibernate.id.enhanced.TableGenerator.access$400(TableGenerator.java:132)
at org.hibernate.id.enhanced.TableGenerator$1$1.execute(TableGenerator.java:589)
at org.hibernate.id.enhanced.TableGenerator$1$1.execute(TableGenerator.java:575)
at org.hibernate.jdbc.WorkExecutor.executeReturningWork(WorkExecutor.java:55)
at org.hibernate.jdbc.AbstractReturningWork.accept(AbstractReturningWork.java:34)
at org.hibernate.resource.transaction.backend.jdbc.internal.JdbcIsolationDelegate.delegateWork(JdbcIsolationDelegate.java:57)
at org.hibernate.id.enhanced.TableGenerator$1.getNextValue(TableGenerator.java:574)
at org.hibernate.id.enhanced.NoopOptimizer.generate(NoopOptimizer.java:40)
at org.hibernate.id.enhanced.TableGenerator.generate(TableGenerator.java:570)
at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:119)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:191)
at org.hibernate.event.internal.DefaultSaveEventListener.saveWithGeneratedOrRequestedId(DefaultSaveEventListener.java:38)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.entityIsTransient(DefaultSaveOrUpdateEventListener.java:176)
at org.hibernate.event.internal.DefaultSaveEventListener.performSaveOrUpdate(DefaultSaveEventListener.java:32)
at org.hibernate.event.internal.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:73)
at org.hibernate.internal.SessionImpl.fireSave(SessionImpl.java:712)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:704)
at org.hibernate.internal.SessionImpl.save(SessionImpl.java:699)
at com.infiniteskills.data.Application.main(Application.java:42)
ERROR - Table 'ifinances.hibernate_sequences' doesn't exist
Класс сущности
@Entity
@Table(name = "BANK")
public class Bank {
@Id
/*
* @GeneratedValue(strategy = GenerationType.AUTO, generator = "native")
*
* @GenericGenerator(name = "native", strategy = "native")
*/
@GeneratedValue(strategy = GenerationType.TABLE)
@Column(name = "BANK_ID")
private Long bankId;
@Column(name = "NAME")
private String name;
@Embedded
private Address address = new Address();
класс приложения
package com.infiniteskills.data;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.Calendar;
import java.util.Date;
import org.hibernate.Session;import org.hibernate.type.descriptor.java.LocalDateJavaDescriptor;
import com.infiniteskills.data.entities.Bank;
import com.infiniteskills.data.entities.TimeTest;
import com.infiniteskills.data.entities.User;
public class Application {
public static void main(String[] args) {
Session session = HibernateUtil.getSessionFactory().openSession();
try {
session.getTransaction().begin();
/*
* TimeTest test = new TimeTest(new Date()); session.save(test);
* session.getTransaction().commit();
*
* session.refresh(test);
*
* System.out.println(test);
*/
Bank bank = new Bank();
bank.setName("State Bank");
bank.setAddressLine1("Ranibagh");
bank.setAddressLine2("Haldwani");
bank.setCity("Nainital");
bank.setState("UK");
bank.setZipCode("63139");
bank.setCreatedBy("Vaibhav Pandey");
bank.setLastUpdatedBy("Vaibhav Pandey");
bank.setCreatedDate(LocalDateTime.now());
bank.setLastUpdatedDate(LocalDateTime.now());
bank.setInternational(false);
session.save(bank);
session.getTransaction().commit();