46

I'm trying to start spring boot project with MySQL database, but I have some problem with database. I try to start my application that, and server is running but hibernate don't create Tables etc.

This is my code:

User Entity

 @Entity
   public class User {
      @Id
      @GeneratedValue(strategy = IDENTITY)
      private Long id;

      private String firstName;
      private String lastName;

      private String email;

      private String password;
      private String description;
      private String profile_photo;

      private LocalDate create;
      private LocalDate update;

      @OneToMany(mappedBy = "eventOwner")
      private List<Event> ownedEvents;

           public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public String getFirstName() {
    return firstName;
}

public void setFirstName(String firstName) {
    this.firstName = firstName;
}

public String getLastName() {
    return lastName;
}

public void setLastName(String lastName) {
    this.lastName = lastName;
}

public String getEmail() {
    return email;
}

public void setEmail(String email) {
    this.email = email;
}

public String getPassword() {
    return password;
}

public void setPassword(String password) {
    this.password = password;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getProfile_photo() {
    return profile_photo;
}

public void setProfile_photo(String profile_photo) {
    this.profile_photo = profile_photo;
}

public LocalDate getCreate() {
    return create;
}

public void setCreate(LocalDate create) {
    this.create = create;
}

public LocalDate getUpdate() {
    return update;
}

public void setUpdate(LocalDate update) {
    this.update = update;
}

public List<Event> getOwnedEvents() {
    return ownedEvents;
}

public void setOwnedEvents(List<Event> ownedEvents) {
    this.ownedEvents = ownedEvents;
}}

Event Entity

   @Entity
   @Table(name = "events")
   public class Event {

@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;

private Double longitude;
private Double latitude;

private String description;
private String header;

private LocalDate startData;
private LocalDate endData;
private LocalDate creat;
private LocalDate update;
private Filters filters;

@ManyToOne
@JoinColumn(name = "owner_id")
private User eventOwner;

public Long getId() {
    return id;
}

public void setId(Long id) {
    this.id = id;
}

public Double getLongitude() {
    return longitude;
}

public void setLongitude(Double longitude) {
    this.longitude = longitude;
}

public Double getLatitude() {
    return latitude;
}

public void setLatitude(Double latitude) {
    this.latitude = latitude;
}

public String getDescription() {
    return description;
}

public void setDescription(String description) {
    this.description = description;
}

public String getHeader() {
    return header;
}

public void setHeader(String header) {
    this.header = header;
}

public LocalDate getStartData() {
    return startData;
}

public void setStartData(LocalDate startData) {
    this.startData = startData;
}

public LocalDate getEndData() {
    return endData;
}

public void setEndData(LocalDate endData) {
    this.endData = endData;
}

public LocalDate getCreat() {
    return creat;
}

public void setCreat(LocalDate creat) {
    this.creat = creat;
}

public LocalDate getUpdate() {
    return update;
}

public void setUpdate(LocalDate update) {
    this.update = update;
}

public Filters getFilters() {
    return filters;
}

public void setFilters(Filters filters) {
    this.filters = filters;
}

public User getEventOwner() {
    return eventOwner;
}

public void setEventOwner(User eventOwner) {
    this.eventOwner = eventOwner;
}

}

And this is my properties:

spring.datasource.url= jdbc:mysql://localhost:3306/some_database? 
requireSSL=false&useSSL=false
spring.datasource.username= user
spring.datasource.password= passw 
logging.level.org.hibernate.SQL= DEBUG
spring.jpa.hibernate.ddl-auto = create-drop
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL55Dialect

This is error I get

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing 
DDL "alter table events drop foreign key FKg0mkvgsqn8584qoql6a2rxheq" via 
JDBC Statement

and

org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing 
DDL "create table events (id bigint not null auto_increment, creat date, 
description varchar(255), end_data date, event_type integer, max_age 
integer not null, min_age integer not null, open_to_changes bit not null, 
pets_allowed bit not null, price_range integer, smoking_allowed bit not 
null, header varchar(255), latitude double precision, longitude double 
precision, start_data date, update date, owner_id bigint, primary key (id)) 
engine=InnoDB" via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlString(SchemaCreatorImpl.java:440) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.applySqlStrings(SchemaCreatorImpl.java:424) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.createFromMetadata(SchemaCreatorImpl.java:315) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.performCreation(SchemaCreatorImpl.java:166) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:135) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.tool.schema.internal.SchemaCreatorImpl.doCreation(SchemaCreatorImpl.java:121) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:155) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:72) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:310) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:467) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:939) [hibernate-core-5.3.7.Final.jar:5.3.7.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57) [spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) [spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:390) [spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:377) [spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) [spring-orm-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1804) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1741) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:576) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:498) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) [spring-beans-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1083) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:853) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:546) ~[spring-context-5.1.4.RELEASE.jar:5.1.4.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:142) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) ~[spring-boot-2.1.2.RELEASE.jar:2.1.2.RELEASE]

Anyone know how to fix that?

FilipW
  • 634
  • 1
  • 6
  • 10

23 Answers23

86

Change spring.jpa.hibernate.ddl-auto = create-drop to update. It is dropping the database at start so wont find the required events table to alter anything.

Vivek Patel
  • 969
  • 5
  • 4
68

In my case the problem why i got this exception was, that some tables had names which are reserved for postgreSQL. eg. "Like" or "User". Changed name with:

@Table(name="likes") 

and it worked fine. Perhaps someone has the same problem.

SupaMario
  • 998
  • 9
  • 14
  • 2
    Had the same issue - that fixed it perfectly thanks! – Come.T Oct 22 '20 at 08:02
  • 2
    Thanks! that did solve my issue as well. Oh the trouble of trying to interpret what the ORM wants to do. Things always seem to be "lost in translation" – Amir Apr 03 '21 at 14:15
  • Is this annotation coming from `Hibernate` or from `Javax.Persistence`? I assume `Javax.Persistence`, as all others come from there, as well. – Akito Jun 13 '21 at 17:02
  • Had the same problem using MariaDB, fixed with this too – Juan Diego Lozano Nov 17 '22 at 18:06
9

It seems that it is an error related to reserved PostgreSQL words. Similar to the top answer (SupaMario's), the error went away after changing one of my column names from

@Column(name = "name", nullable = false)

to

@Column(name = "employee_name", nullable = false)
kyle_aoki
  • 247
  • 5
  • 6
  • @JoinColumn(name = "from") private Employee from; I had the same problem, "form" was a reserved keyword, after modifying to @JoinColumn(name = "cr_from") it worked fine. – Sayed Hussainullah Sadat Apr 17 '23 at 05:55
8

In my case the problem why i got this exception was, that some tables had names which are reserved for mySQL. eg. "order" Changed name with:

@Column(name="orders") 

or

for example

@ManyToOne(cascade = {CascadeType.ALL})
@JoinColumn(name = "fk_order",nullable = false)
private Order order;

worked for me.

davidrichardo
  • 81
  • 1
  • 1
3

Owner is a reserved word for MySQL. Either change it or use annotation to use some different name for forgeinkey instead of default

Reference: https://dev.mysql.com/doc/refman/8.0/en/keywords.html#keywords-8-0-detailed-O

Forcing JPA to use custom name

@ManyToOne
@MapsId("ownerId")
@JoinColumn(
        name = "owner_id",
        foreignKey = @ForeignKey(
                name = "fkey_own_id"
                )
        ) 
TRO
  • 31
  • 1
2

Just specify the dialect in your application.properties. For example, for MySQL 8:

hibernate.dialect=org.hibernate.dialect.MySQL8Dialect
ACV
  • 9,964
  • 5
  • 76
  • 81
1

Change The dialect of hibernate.cfg.xml Dialect :- org.hibernate.dialect.MySQL5InnoDBDialect OR org.hibernate.dialect.MySQL55Dialect OR org.hibernate.dialect.MySQL55InnoDBDialect OR org.hibernate.dialect.MySQL57InnoDBDialect

1

Change Line code in properties file:

form:

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL55Dialect

To:

spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect

Because MySQL55Dialect not creating FK . and MySQL5InnoDBDialect creating FK

1

I encountered that problem too with the MySQL running on Docker and here's solution which worked for me.

  1. Delete .data directory if you have one in your project directory.
  2. Turn off running Docker container.
  3. Delete existing Docker container.
  4. Create new Docker container by simply typing in docker-compose up -d in the directory where docker-compose.yml file is located.
  5. Rerun Spring Boot app.

After hours of trying to find solution this solved all my problems with the errors thrown by the Hibernate in the Spring Boot app.

(PS. I have in the application.properties file this line: spring.jpa.hibernate.ddl-auto=update - it might play some factor too)

YgLK
  • 23
  • 2
  • 7
0

Hmm I also encountered this issue but either of those solutions could not solve my issue. I am using MySQL database packaging with XAMPP. What I tried out to solve but failed

  • I deleted my Database located in "xampp\mysql\data"
  • I renamed my conflicted tables
  • Although I kept this "spring.jpa.hibernate.ddl-auto=update" setting in at start.

So what I did to solve this issue. Might be yours

  • I completely uninstalled the XAMPP package and Installed it again.
  • I created new database name
  • RUN the application

Friends it actually my circumstances, might be help your issue like me. If you have any question please post comment. Thanks

Subarata Talukder
  • 5,407
  • 2
  • 34
  • 50
0

Ran into similar issue and found SupaMario's answer here.

In my case I had a table named orders but MySql threw the error as it seems to be a reserve table / keyword.

I changed it to customer_order and it all worked fine.

Ahmed Ashour
  • 5,179
  • 10
  • 35
  • 56
0

if you see this problem, please double check your class properties for reserved keywords like key(in my case).

I changed the key to mkey and everything goes fine.

Setmax
  • 946
  • 6
  • 10
0

For anyone working with PostgreSQL and has the same problem even though your table names are not key words, place the line below in your application.properties. It worked for me.

spring.jpa.properties.hibernate.jdbc.lob.non_contextual_creation=true
Willy
  • 1
  • 1
0

In my case I had the error when I did this in a specific entity property

@Column(name ="condition", nullable = false)

I changed this to

@Column(name ="condition_of_house", nullable = false)

And it worked well

RubioRic
  • 2,442
  • 4
  • 28
  • 35
0

In my case, the error occurred because mysql user does not have REFERENCES privilege.

To solve this;

  1. Log into mysql with root user
  2. Grant all privileges for 'your_user'@'localhost'

or you just need to grant REFERENCES privileges to 'your_user'@'localhost'

See the documentation: https://dev.mysql.com/doc/refman/8.0/en/grant.html

0

Add this setting properties line code in application.yml or properties.properties file:

spring.jpa.hibernate.ddl-auto=update
harun ugur
  • 1,718
  • 18
  • 18
0

After checking my hibernate.dialect in application.properties, and changing my table's names (to make them less likely to interfere with reserved MSQL keywords), I was still having this error with create-and-drop, when Hibernate does its ALTER TABLE to add foreign keys.

Wanting to solve this I decided to look at MySQL logs in MySQL Workbench.

But then I was facing another issue: I couldn't access server logs (some errors regarding PATH variable, but PATH variable was ok). See here for how to solve that.

The real issue came from character encoding working on a European environment (France).

Issue was fixed by activating "Beta: Use UTF-8 for worldwide language support", under Control Panel > Region > Administrative > Change system locale.

After reboot, I could access my MySQL logs and guess what? I was no longer having errors with Hibernate either.

TriS
  • 3,668
  • 3
  • 11
  • 25
0

I was getting this error because I was using: private "Long" id; rather than: private "int" id; Hibernate was adding "BIGINT" in the DB and then didn't recognise it.

I changed my entity id's to "int" and that solved my problem. Hope this helps.

RG Fick
  • 11
  • 2
0

Adding space between column name also leads to this error.

eg.

 @Column(name = "PRODUCT ID")

change this to:

 @Column(name = "PRODUCT_ID")
0

Odd solution that eventually worked for me: After trying some of the suggested options for spring.jpa.hibernate.ddl-auto, which did not work, I ran it once with none and then with create and it worked.

I can't really explain it but it's quick to try, and it worked for me. I was using a h2 database.

halfer
  • 19,824
  • 17
  • 99
  • 186
Benjamin Basmaci
  • 2,247
  • 2
  • 25
  • 46
0

Check your main method.to find any error regarding return methods you called

MLone
  • 1
  • 1
  • I think you need to familiarize yourself with how this website works. Have you taken the [tour]? Have you visited the [help]? I believe that your "answer" is a suggestion on how to find the cause of the error and not a solution. As such it is more of a comment than an answer and you should not post comments as answers. Yes, you don't have enough reputation to post comments - so build up your reputation. – Abra Aug 26 '23 at 07:03
-1

Ok, had the same issue. Adding prefixes fixed the problem for me:

from:

`
@Entity
@Table(name = "result_man")
@Proxy(lazy = false)
public class ResultManEntity {
@Id
@GeneratedValue
@Column(name = "id", unique = true, length = 128)
private long id;
private String key;
private int score;
private int index;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "result_id")
private ResultEntity result;
}`

to:

`@Entity
@Table(name = "result_man")
@Proxy(lazy = false)
public class ResultManEntity {
@Id
@GeneratedValue
@Column(name = "id", unique = true, length = 128)
private long id;
private String _key;
private int _score;
private int _index;
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "result_id")
private ResultEntity result;`
-4

In my case, deleting tables from the database helped. BUT, ATTENTION, THIS WAS A TRAINING PROJECT :)