Question
I'm unable to get spring boot to automatically load my database schema when I start it up.
Here is my application.properties:
spring.datasource.url=jdbc:mysql://localhost:3306/test
spring.datasource.username=test
spring.datasource.password=
spring.datasource.driverClassName = com.mysql.jdbc.Driver
spring.jpa.database = MYSQL
spring.jpa.show-sql = true
spring.jpa.hibernate.ddl-auto = create
spring.jpa.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
spring.jpa.hibernate.naming_strategy = org.hibernate.cfg.ImprovedNamingStrategy
Here is my Application.java:
@EnableAutoConfiguration
@ComponentScan
public class Application {
public static void main(final String[] args){
SpringApplication.run(Application.class, args);
}
}
Here is a sample entity:
@Entity
@Table(name = "survey")
public class Survey implements Serializable {
private Long _id;
private String _name;
private List<Question> _questions;
/**
* @return survey's id.
*/
@Id
@GeneratedValue(strategy = IDENTITY)
@Column(name = "survey_id", unique = true, nullable = false)
public Long getId() {
return _id;
}
/**
* @return the survey name.
*/
@Column(name = "name")
public String getName() {
return _name;
}
/**
* @return a list of survey questions.
*/
@OneToMany(mappedBy = "survey")
@OrderBy("id")
public List<Question> getQuestions() {
return _questions;
}
/**
* @param id the id to set to.
*/
public void setId(Long id) {
_id = id;
}
/**
* @param name the name for the question.
*/
public void setName(final String name) {
_name = name;
}
/**
* @param questions list of questions to set.
*/
public void setQuestions(List<Question> questions) {
_questions = questions;
}
}
Any ideas what I'm doing wrong?
Answer
There are several possible causes:
-
Your entity classes are in the same or in a sub-package relative one where you have you class with
@EnableAutoConfiguration.
If not then your spring app does not see them and hence will not create anything in db -
Check your config, it seems that you are using some hibernate specific options, try to replace them with:
spring.jpa.database-platform=org.hibernate.dialect.MySQL5InnoDBDialect spring.jpa.hibernate.ddl-auto=update spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver spring.datasource.url=jdbc:mysql://localhost:3306/test spring.datasource.username=test spring.datasource.password=
**note that the manual loading of the driver class is unnecessary because it's automatically registered, so don't bother yourself with it
- Your
application.properties
must be insrc/main/resources
folder.
If you did not specify dialect correctly it might try to default to bundled
together with boot in-memory database and (as it was with me) I could see that
it tries to connect to local HSQL
(see console output) instance and fail at
updating the schema.