Я пытаюсь создать небольшое веб-приложение, используя Spring, MySQL, Thymeleaf и Hibernate. Всякий раз, когда я пытаюсь выполнить вызов API для сбора данных формы и добавления их в мою базу данных, я получаю сообщение об ошибке java.sql.SQLSyntaxErrorException: Table 'db_example.bottlecaps' doesn't exist
Хотя я явно не создавал эту таблицу с помощью запроса, я использую синтаксис @Entity
и @Table
от import javax.persistence
, чтобы создать для меня таблицу. И даже когда я запускаю свое приложение, Hibernate печатает в журналах, что таблица создается:
2020-06-19 12:43:33.050 WARN 8576 --- [ restartedMain] org.thymeleaf.templatemode.TemplateMode : [THYMELEAF][restartedMain] Template Mode 'LEGACYHTML5' is deprecated. Using Template Mode 'HTML' instead.
2020-06-19 12:43:33.149 INFO 8576 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2020-06-19 12:43:33.193 INFO 8576 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2020-06-19 12:43:33.195 INFO 8576 --- [ restartedMain] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
Hibernate: create table bottlecaps (id binary(255) not null, brand varchar(255), image-link varchar(255), country varchar(255), description varchar(255), is_alcoholic bit, name varchar(255), year-found integer, year-made integer, primary key (id)) engine=InnoDB
2020-06-19 12:43:33.526 INFO 8576 --- [ task-1] j.LocalContainerEntityManagerFactoryBean : Initialized JPA EntityManagerFactory for persistence unit 'default'
2020-06-19 12:43:33.806 INFO 8576 --- [ restartedMain] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
Если мы продолжим немного дальше по журналам, вы увидите, где он пытается добавить мою информацию в таблица, когда я вызываю API, но затем выходит из строя.
Hibernate: select bottlecap0_.id as id1_0_0_, bottlecap0_.brand as brand2_0_0_, bottlecap0_.image-link as image3_0_0_, bottlecap0_.country as country4_0_0_, bottlecap0_.description as descript5_0_0_, bottlecap0_.is_alcoholic as is_alcoh6_0_0_, bottlecap0_.name as name7_0_0_, bottlecap0_.year-found as year8_0_0_, bottlecap0_.year-made as year9_0_0_ from bottlecaps bottlecap0_ where bottlecap0_.id=?
2020-06-19 12:44:12.971 ERROR 8576 --- [0.1-8080-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper : Table 'db_example.bottlecaps' doesn't exist
2020-06-19 12:44:12.980 DEBUG 8576 --- [0.1-8080-exec-2] o.s.web.servlet.DispatcherServlet : Failed to complete request: org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
2020-06-19 12:44:12.989 ERROR 8576 --- [0.1-8080-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
Вот мой файл application.properties. В аналогичном посте я видел, как люди просят об этом
spring.servlet.multipart.max-file-size=50MB
# ===============================
# TOMCAT
# ===============================
server.address=127.0.0.1
server.error.whitelabel.enabled=false
server.tomcat.accesslog.enabled=true
# ===============================
# = LOGGING
# ===============================
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR
# ===============================
# = DATA SOURCE
# ===============================
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/db_example
spring.datasource.username= user
spring.datasource.password= pass
spring.datasource.tomcat.max-wait=10000
spring.datasource.tomcat.max-active=5
spring.datasource.tomcat.test-on-borrow=true
spring.datasource.platform=mysql
# ===============================
# = JPA / HIBERNATE
# ===============================
spring.jpa.show-sql = true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.hibernate.naming-strategy=org.hibernate.cfg.DefaultNamingStrategy
# ===============================
# = Thymeleaf configurations
# ===============================
spring.thymeleaf.mode=LEGACYHTML5
spring.thymeleaf.cache=false
Я также укажу, где я создаю свой объект и таблицу, а также его контроллер
package com.example.form.domain;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotEmpty;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.UUID;
@Entity
@Table(name = "bottlecaps", schema ="db_example")
public class Bottlecap {
@Id
@Column(name = "id")
private UUID id;
@Column(name = "name")
private String name;
@Column(name="brand")
private String brand;
@Column(name="year-made")
private Integer yearMade;
@Column(name="country")
private String country;
@Column(name="image-link")
private String capImageLink; //S3 key
@Column(name="description")
private String description;
@Column(name="year-found")
private Integer yearFound;
@Column(name="isAlcoholic")
private Boolean isAlcoholic;
public Bottlecap() {
}
public Bottlecap(UUID id, String name, String brand, Integer yearMade,
String country, String capImageLink, String description,
Integer yearFound, Boolean isAlcoholic) {
this.id = id;
this.name = name;
this.brand = brand;
this.yearMade = yearMade;
this.country = country;
this.capImageLink = capImageLink;
this.description = description;
this.yearFound = yearFound;
this.isAlcoholic = isAlcoholic;
}
//Getters and Setters down here
}
package com.example.form.controllers;
import com.example.form.domain.Bottlecap;
import com.example.form.domain.User;
import com.example.form.repository.BottlecapRepository;
import com.example.form.service.BottlecapService;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import javax.validation.Valid;
import java.util.Map;
import java.util.UUID;
@Controller
public class BottlecapController {
private BottlecapService bottlecapService;
private BottlecapRepository bottlecapRepository;
public BottlecapController(BottlecapService bottlecapService, BottlecapRepository bottlecapRepository) {
this.bottlecapService = bottlecapService;
this.bottlecapRepository = bottlecapRepository;
}
// Return registration form template
@RequestMapping(value="/bottlecap-entry", method = RequestMethod.GET)
public ModelAndView showEntryPage(ModelAndView modelAndView, Bottlecap bottlecap){
modelAndView.addObject("bottlecap", bottlecap);
modelAndView.setViewName("entry");
return modelAndView;
}
@PostMapping("/bottlecap-entry")
private void entryForm(@Valid Bottlecap bottlecap, @RequestParam(value = "file")MultipartFile image){
bottlecap.setId(UUID.randomUUID());
bottlecapService.saveCap(bottlecap);
//bottlecapService.uploadEntryImage(bottlecap.getId(), image);
}
}
Это это мой первый проект, в котором я пытаюсь сделать что-то подобное, так что любые отзывы приветствуются! Спасибо.