При создании базы данных через Hibernate - ошибка org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement

445
06 октября 2017, 15:00

Вечер в Хату.

Пытаюсь создать таблицы в базе данных при помощи Hibernate.

Вот мой Config

<session-factory>
    <property name="connection.driver_class">com.mysql.jdbc.Driver</property>
    <property name="connection.url">jdbc:mysql://localhost:3306/lapkiDB</property>
    <property name="connection.username">root</property>
    <property name="connection.password">1769</property>
    <property name="dialect">org.hibernate.dialect.MySQL55Dialect</property>
    <property name="show_sql">true</property>
    <property name="format_sql">true</property>
    <property name="use_sql_comments">false</property>

    <property name="hbm2ddl.auto">update</property>


    <mapping class="entities.Animal"/>
    <mapping class="entities.Shelter"/>
    <mapping class="entities.AnimalBreed"/>
    <mapping class="entities.Type"/>
    <mapping class="entities.MetroStation"/>
    <mapping class="entities.City"/>

</session-factory>

Вот как выглядит база данных

Вот мои таблицы

Animals

@Entity
@Table(name = "animals")
public class Animal {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int animal_id;
@Column(name = "name")
private String name;
@ManyToOne(fetch =  FetchType.LAZY)
@JoinColumn(name = "type_id")
private Type type;
@Column(name = "sex")
private char sex;
@ManyToOne(fetch =  FetchType.LAZY)
@JoinColumn(name = "animalBreed_id")
private AnimalBreed animalBreed;
@Column(name = "age")
private int age;
@Column(name = "description")
private String description;
@Column(name = "photos") // узнать про хранение фото
private String photos;
@ManyToOne(fetch =  FetchType.LAZY)
@JoinColumn(name = "shelter_id")
private Shelter shelter;
public Animal() {
}
public Animal(String name, Type type, char sex, AnimalBreed animalBreed, int age, String description, String photos, Shelter shelter) {
    this.name = name;
    this.type = type;
    this.sex = sex;
    this.animalBreed = animalBreed;
    this.age = age;
    this.description = description;
    this.photos = photos;
    this.shelter = shelter;
}
public int getAnimal_id() {
    return animal_id;
}
public void setAnimal_id(int animal_id) {
    this.animal_id = animal_id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}
public Type getType() {
    return type;
}
public void setType(Type type) {
    this.type = type;
}
public char getSex() {
    return sex;
}
public void setSex(char sex) {
    this.sex = sex;
}
public AnimalBreed getAnimalBreed() {
    return animalBreed;
}
public void setAnimalBreed(AnimalBreed animalBreed) {
    this.animalBreed = animalBreed;
}
public int getAge() {
    return age;
}
public void setAge(int age) {
    this.age = age;
}
public String getDescription() {
    return description;
}
public void setDescription(String description) {
    this.description = description;
}
public String getPhotos() {
    return photos;
}
public void setPhotos(String photos) {
    this.photos = photos;
}
public Shelter getShelter() {
    return shelter;
}
public void setShelter(Shelter shelter) {
    this.shelter = shelter;
}
@Override
public String toString() {
    return "Animal{" +
            "animal_id=" + animal_id +
            ", name='" + name + '\'' +
            ", type=" + type +
            ", sex=" + sex +
            ", animalBreed=" + animalBreed +
            ", age=" + age +
            ", description='" + description + '\'' +
            ", photos='" + photos + '\'' +
            ", shelter=" + shelter +
            '}';
}

}

Shelter

@Entity
@Table(name = "shelters")
public class Shelter {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int shelter_id;
@Column(name = "name")
private String shelterName; // +
@ManyToOne(fetch =  FetchType.LAZY)
@JoinColumn(name = "city_id")
private City city; // +
@Column(name = "adress")
private String adress; // +
@ManyToOne(fetch =  FetchType.LAZY)
@JoinColumn(name = "metroStation_id")
private MetroStation metroStation; // +
@Column(name = "phones")
private String phones; // +
@Column(name = "webSite")
private String webSite; // +
@OneToMany(fetch = FetchType.LAZY, mappedBy = "shelter")
private Set<Animal> animals; // +
public Shelter() {
}
public Shelter(String shelterName, City city, String adress, MetroStation metroStation, String phones, String webSite) {
    this.shelterName = shelterName;
    this.city = city;
    this.adress = adress;
    this.metroStation = metroStation;
    this.phones = phones;
    this.webSite = webSite;
}
public int getShelter_id() {
    return shelter_id;
}
public void setShelter_id(int shelter_id) {
    this.shelter_id = shelter_id;
}
public String getShelterName() {
    return shelterName;
}
public void setShelterName(String shelterName) {
    this.shelterName = shelterName;
}
public City getCity() {
    return city;
}
public void setCity(City city) {
    this.city = city;
}
public String getAdress() {
    return adress;
}
public void setAdress(String adress) {
    this.adress = adress;
}
public MetroStation getMetroStation() {
    return metroStation;
}
public void setMetroStation(MetroStation metroStation) {
    this.metroStation = metroStation;
}
public String getPhones() {
    return phones;
}
public void setPhones(String phones) {
    this.phones = phones;
}
public String getWebSite() {
    return webSite;
}
public void setWebSite(String webSite) {
    this.webSite = webSite;
}
public Set<Animal> getAnimals() {
    return animals;
}
public void setAnimals(Set<Animal> animals) {
    this.animals = animals;
}
@Override
public String toString() {
    return "Shelter{" +
            "shelter_id=" + shelter_id +
            ", shelterName='" + shelterName + '\'' +
            ", city=" + city +
            ", adress='" + adress + '\'' +
            ", metroStation=" + metroStation +
            ", phones='" + phones + '\'' +
            ", webSite='" + webSite + '\'' +
            '}';
}

}

Type

@Entity
@Table(name = "types")
public class Type {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int type_id;
@Column(name = "type")
private String type;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "type")
private Set<AnimalBreed> animalBreeds;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "type")
private Set<Animal> animals;
public Type() {
}
public Type(String type) {
    this.type = type;
}
public int getType_id() {
    return type_id;
}
public void setType_id(int type_id) {
    this.type_id = type_id;
}
public String getType() {
    return type;
}
public void setType(String type) {
    this.type = type;
}
public Set<AnimalBreed> getAnimalBreeds() {
    return animalBreeds;
}
public void setAnimalBreeds(Set<AnimalBreed> animalBreeds) {
    this.animalBreeds = animalBreeds;
}
public Set<Animal> getAnimals() {
    return animals;
}
public void setAnimals(Set<Animal> animals) {
    this.animals = animals;
}
@Override
public String toString() {
    return "Type{" +
            "type_id=" + type_id +
            ", type='" + type + '\'' +
            '}';
}

}

AnimalBreed

@Entity
@Table(name = "AnimalBreed")
public class AnimalBreed {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int animalBreed_id;
@ManyToOne(fetch =  FetchType.LAZY)
@JoinColumn(name = "type_id")
private Type type;
@Column(name = "AnimalBreedName") // внеш
private String animalBreedName;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "animalBreed")
private Set<Animal> animals;
public AnimalBreed() {
}
public AnimalBreed(Type type, String animalBreedName) {
    this.type = type;
    this.animalBreedName = animalBreedName;
}
public int getAnimalBreed_id() {
    return animalBreed_id;
}
public void setAnimalBreed_id(int animalBreed_id) {
    this.animalBreed_id = animalBreed_id;
}
public Type getType() {
    return type;
}
public void setType(Type type) {
    this.type = type;
}
public String getAnimalBreedName() {
    return animalBreedName;
}
public void setAnimalBreedName(String animalBreedName) {
    this.animalBreedName = animalBreedName;
}
public Set<Animal> getAnimals() {
    return animals;
}
public void setAnimals(Set<Animal> animals) {
    this.animals = animals;
}
@Override
public String toString() {
    return "AnimalBreed{" +
            "animalBreed_id=" + animalBreed_id +
            ", type=" + type +
            ", animalBreedName='" + animalBreedName + '\'' +
            '}';
}

}

City

@Entity
@Table(name = "City")
public class City {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int city_id;
@Column(name = "cityName")
private String cityName;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "city")
private Set<MetroStation> metroStations;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "city")
private Set<Shelter> shelters;
public City() {
}
public City(String cityName) {
    this.cityName = cityName;
}
public int getCity_id() {
    return city_id;
}
public void setCity_id(int city_id) {
    this.city_id = city_id;
}
public String getCityName() {
    return cityName;
}
public void setCityName(String cityName) {
    this.cityName = cityName;
}
public Set<MetroStation> getMetroStations() {
    return metroStations;
}
public void setMetroStations(Set<MetroStation> metroStations) {
    this.metroStations = metroStations;
}
public Set<Shelter> getShelters() {
    return shelters;
}
public void setShelters(Set<Shelter> shelters) {
    this.shelters = shelters;
}
@Override
public String toString() {
    return "City{" +
            "city_id=" + city_id +
            ", cityName='" + cityName + '\'' +
            '}';
}

}

MetroStation

   @Entity
   @Table(name = "MetroStation")
   public class MetroStation {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private int metroStation_id;
@Column(name = "metroStationName")
private String metroStationName;
@ManyToOne(fetch =  FetchType.LAZY)
@JoinColumn(name = "city_id")
private City city;
@OneToMany(fetch = FetchType.LAZY, mappedBy = "metroStation")
private Set<Shelter> shelters;
public MetroStation() {
}
public MetroStation(String metroStationName, City city) {
    this.metroStationName = metroStationName;
    this.city = city;
}
public int getMetroStation_id() {
    return metroStation_id;
}
public void setMetroStation_id(int metroStation_id) {
    this.metroStation_id = metroStation_id;
}
public String getMetroStationName() {
    return metroStationName;
}
public void setMetroStationName(String metroStationName) {
    this.metroStationName = metroStationName;
}
public City getCity() {
    return city;
}
public void setCity(City city) {
    this.city = city;
}
public Set<Shelter> getShelters() {
    return shelters;
}
public void setShelters(Set<Shelter> shelters) {
    this.shelters = shelters;
}
@Override
public String toString() {
    return "MetroStation{" +
            "metroStation_id=" + metroStation_id +
            ", metroStationName='" + metroStationName + '\'' +
            ", city=" + city +
            '}';
}

}

Ошибка

Hibernate:  
     
    alter table MetroStation  
       add constraint FKq63mhpntc9ssuq6hn4a7vpojp  
       foreign key (city_id)  
       references City (city_id) 
Hibernate:  
     
    alter table shelters  
       add constraint FK4jueheylpjcufj9kslth9e41h  
       foreign key (city_id)  
       references City (city_id) 
Hibernate:  
     
    alter table shelters  
       add constraint FKqefjxxtdws00q0gfpulnprrcn  
       foreign key (metroStation_id)  
       references MetroStation (metroStation_id) 
окт 05, 2017 1:01:59 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException 
WARN: GenerationTarget encountered exception accepting command : Error executing DDL via JDBC Statement 
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement 
	at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) 
	at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:559) 
	at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:504) 
	at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applyForeignKeys(AbstractSchemaMigrator.java:433) 
	at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:249) 
	at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:114) 
	at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:183) 
	at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72) 
	at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:313) 
	at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:452) 
	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710) 
	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726) 
	at Start.main(Start.java:9) 
Caused by: java.sql.SQLException: Cannot add foreign key constraint 
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957) 
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878) 
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814) 
	at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478) 
	at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625) 
	at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2547) 
	at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2505) 
	at com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:840) 
	at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:740) 
	at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) 
	... 12 more 
 
окт 05, 2017 1:01:59 PM org.hibernate.tool.schema.internal.ExceptionHandlerLoggedImpl handleException 
WARN: GenerationTarget encountered exception accepting command : Error executing DDL via JDBC Statement 
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL via JDBC Statement 
	at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) 
	at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:559) 
	at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:504) 
	at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applyForeignKeys(AbstractSchemaMigrator.java:433) 
	at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:249) 
	at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:114) 
	at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:183) 
	at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72) 
	at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:313) 
	at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:452) 
	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:710) 
	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:726) 
	at Start.main(Start.java:9) 
Caused by: java.sql.SQLException: Cannot add foreign key constraint 
	at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957) 
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3878) 
	at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3814) 
	at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2478) 
	at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2625) 
	at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2547) 
	at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2505) 
	at com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:840) 
	at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:740) 
	at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) 
	... 12 more 
 
окт 05, 2017 1:02:00 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl stop 
INFO: HHH10001008: Cleaning up connection pool [jdbc:mysql://localhost:3306/lapkiDB]

Собственно с Hibernate работаю впервые, однако подобную таблицу уже удавалось создать. Тут перепроверил связи и тд, и то ли в глаза долблюсь то ли еще чего. Зарубежный StackOverflow предлагает пересесть на Eclipse, но мне не очень нравится данное решение. Заранее большое спасибо за помощь)

P.S изначально стоял просто MySqlDialect было 9 ошибок такого типа, изменил на 55, осталось всего 2.

Answer 1

Проблема решилась. Изменили @Column(name = "cityName") private String cityName; на @Column(name = "city") private String city; и @Column(name = "metroStationName") private String metroStationName; на @Column(name = "metroStation") private String metroStation; Спасибо

READ ALSO
Почему появляется сообщение &ldquo; Annotations are not supported at this language level&rdquo;?

Почему появляется сообщение “ Annotations are not supported at this language level”?

О каком уровне языка идет речь в сообщении?

277
Парсинг даты и времени

Парсинг даты и времени

Никак не получается составить шаблон для парсинга даты и времени в таком виде:

274
Преобразование SQL запросов в JAVA Class

Преобразование SQL запросов в JAVA Class

Стоит задача преобразовать некоторые sql запросы в конкретные Java файлыДопустим у меня есть запрос на создание таблицы:

235