【问题标题】:Spring boot - Hibernate JPA not creating MySql DB tableSpring boot - Hibernate JPA 未创建 MySql DB 表
【发布时间】:2017-08-11 23:59:33
【问题描述】:

我知道这个问题可能是重复的,但这些解决方案都不适合我。

我希望自动创建表格。但是,当我将带有 JSON 格式的 USER 对象的 POST 请求发送到服务器时,出现以下异常。

例外:

    {
  "timestamp": 1490023621440,
  "status": 500,
  "error": "Internal Server Error",
  "exception": "org.springframework.jdbc.BadSqlGrammarException",
  "message": "PreparedStatementCallback; bad SQL grammar [INSERT INTO user(lastName, firstName, dob, phone, email, password) VALUES (?, ?, ?, ?, ?, ?)]; nested exception is java.sql.SQLSyntaxErrorException: Table 'master_slave.user' doesn't exist",
  "path": "/main"
}

application.properties

spring.datasource.url=jdbc:mysql://${writerendpoint}:${port}/${database.name}
spring.datasource.username=root
spring.datasource.password=root
#spring.datasource.driverClassName=com.mysql.jdbc.driver

writerendpoint=localhost
port=3306
database.name=master_slave

spring.session.store-type=none

# ===============================
# = JPA / HIBERNATE
# ===============================

# Specify the DBMS
spring.jpa.database = MYSQL

# Show or not log for each sql query
spring.jpa.show-sql = true

# Ddl auto must be set to "create" to ensure that Hibernate will run the
# import.sql file at application startup
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = create

# SQL dialect for genereting optimized queries
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect

spring.jpa.properties.hibernate.default_schema=master_slave

用户.java

@Entity
@Table(name="user")
public class User {

    @Id
    @Column
    @GeneratedValue(strategy=GenerationType.AUTO)
    private int userId;
    @NotEmpty
    @Column
    @Max(value=15)
    private String lastName;
    @NotEmpty
    @Column
    @Max(value=15)
    private String firstName;   
    @NotEmpty
    @Column
    private Date dob;
    @Column
    @Max(value=10)
    private String phone;
    @NotEmpty
    @Column
    @Email
    private String email;
    @NotEmpty
    @Column
    @Min(value=6)
    @Max(value=15)
    private String password;

and their getters and setters.

MainDaoImpl.java

@Repository
@Qualifier("mysql")
public class MainDaoImpl implements MainDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    /* (non-Javadoc)
     * @see com.app.masterSlave.dao.RegistrationDao#userRegistration(com.app.masterSlave.model.User)
     */
    @Override
    public void userRegistration(User user) {
        final String sql="INSERT INTO user(lastName, firstName, dob, phone, email, password) VALUES (?, ?, ?, ?, ?, ?)";
        final String lastName=user.getLastName();
        final String firstName=user.getFirstName();
        final Date dob=user.getDob();
        final String phone = user.getPhone();
        final String email = user.getEmail();
        final String password = user.getPassword();
//      BCryptPasswordEncoder encodedPassword = new BCryptPasswordEncoder();            
//      final String password = encodedPassword.encode(user.getPassword());

        int success = jdbcTemplate.update(sql, new Object[] {lastName, firstName, dob, phone, email, password});

        if(success==0) {
            System.out.println("There was an error while insertion.");

        }
        else {
            System.out.println("Row with email: " + email + " inserted successfully.");

        }

    }
}

提前致谢。

【问题讨论】:

  • 应用程序启动时是否发现异常?
  • 不,我在应用程序启动时没有看到任何错误。我在下面看到一种警告:Loading class com.mysql.jdbc.Driver'. This is deprecated. The new driver class is com.mysql.cj.jdbc.Driver'。驱动通过SPI自动注册,一般不需要手动加载驱动类。
  • <artifactId>mysql-connector-java</artifactId>你在pom中添加了吗?
  • 是的,我有。 mysqlmysql-connector-java6.0.5
  • @EnableAutoConfiguration 是否存在于您的主 ApplicationClass 中?

标签: mysql hibernate jpa spring-boot


【解决方案1】:

您正在为 JPA 配置休眠,但您通过 SQL 插入用户。

如果JPA和JDBC模板的配置不兼容,你会遇到问题,就像你发布的那样。为避免这种情况,您可以考虑仅在 JPA 中或仅在 JDBC 中执行所有数据库操作。

你正在使用的网址

spring.datasource.url=jdbc:mysql://${writerendpoint}:${port}/${database.name}

已经包含数据库名称“master_slave”。此外,您将 JPA 默认模式设置为相同的名称

spring.jpa.properties.hibernate.default_schema=master_slave

这可能只是多余的,或者是您的问题的原因。删除它并尝试一下。

查看数据库。哪些表是由 hibernate 创建的?它们在您期望的数据库中吗?

【讨论】:

  • 您好 Stefan,感谢您的回复。实际上,我最近才添加了第二个属性,而之前没有。当该属性甚至不存在时,我也面临同样的错误。对于数据库,我看不到在其中创建任何表。我想将 JdbcTemplate 用于 DB 操作,但也希望 hibernate 自己管理 DDL 部分。有什么想法我应该怎么做?
猜你喜欢
  • 2020-02-29
  • 2021-09-15
  • 2019-06-12
  • 1970-01-01
  • 2017-05-29
  • 2017-03-05
  • 2017-11-20
  • 2018-12-16
  • 2018-05-11
相关资源
最近更新 更多