mysql jpa 不要自动建表,如何让Hibernate在与JPA一起使用时自动在数据库中创建表?...

2023-11-18

I am new to JPA, And for now I am trying to understand standard examples, I was reading online and saw a few stackoverflow questions, What I found in all of them is the following statement will allow hibernate to create tables at run-time.

hibernate.hbm2ddl.auto=create

But Whenever I run my code without tables in mysql database, it throws the following error :

. ____ _ __ _ _

/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \

( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \

\\/ ___)| |_)| | | | | || (_| | ) ) ) )

' |____| .__|_| |_|_| |_\__, | / / / /

=========|_|==============|___/=/_/_/_/

:: Spring Boot :: (v1.1.4.RELEASE)

2014-07-24 09:44:25.365 INFO 8496 --- [ main] o.s.d.j.e.r.simple.SimpleConfiguration : Starting SimpleConfiguration on harmathu-WS with PID 8496 (C:\Songs\spring-data-jpa-examples\spring-data-jpa-example\target\classes started by harmathu in C:\Songs\spring-data-jpa-examples\spring-data-jpa-example)

2014-07-24 09:44:25.421 INFO 8496 --- [ main] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@429bd883: startup date [Thu Jul 24 09:44:25 IST 2014]; root of context hierarchy

2014-07-24 09:44:26.722 INFO 8496 --- [ main] j.LocalContainerEntityManagerFactoryBean : Building JPA container EntityManagerFactory for persistence unit 'default'

2014-07-24 09:44:26.747 INFO 8496 --- [ main] o.hibernate.jpa.internal.util.LogHelper : HHH000204: Processing PersistenceUnitInfo [

name: default

...]

2014-07-24 09:44:26.831 INFO 8496 --- [ main] org.hibernate.Version : HHH000412: Hibernate Core {4.3.5.Final}

2014-07-24 09:44:26.834 INFO 8496 --- [ main] org.hibernate.cfg.Environment : HHH000206: hibernate.properties not found

2014-07-24 09:44:26.836 INFO 8496 --- [ main] org.hibernate.cfg.Environment : HHH000021: Bytecode provider name : javassist

2014-07-24 09:44:27.172 INFO 8496 --- [ main] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {4.0.4.Final}

2014-07-24 09:44:27.390 INFO 8496 --- [ main] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5Dialect

2014-07-24 09:44:27.571 INFO 8496 --- [ main] o.h.h.i.ast.ASTQueryTranslatorFactory : HHH000397: Using ASTQueryTranslatorFactory

2014-07-24 09:44:28.392 WARN 8496 --- [ main] o.h.hql.internal.ast.HqlSqlWalker : [DEPRECATION] Encountered positional parameter near line 1, column 97. Positional parameter are considered deprecated; use named parameters or JPA-style positional parameters instead.

2014-07-24 09:44:28.567 INFO 8496 --- [ main] o.s.j.e.a.AnnotationMBeanExporter : Registering beans for JMX exposure on startup

2014-07-24 09:44:28.591 INFO 8496 --- [ main] o.s.d.j.e.r.simple.SimpleConfiguration : Started SimpleConfiguration in 3.611 seconds (JVM running for 4.607)

2014-07-24 09:44:28.658 WARN 8496 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 1146, SQLState: 42S02

2014-07-24 09:44:28.659 ERROR 8496 --- [ main] o.h.engine.jdbc.spi.SqlExceptionHelper : Table 'test_auditor.app_user' doesn't exist

Exception in thread "main" org.springframework.dao.InvalidDataAccessResourceUsageException: could not execute statement; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not execute statement

at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:172)

at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:155)

at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:417)

at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)

at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)

at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)

at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodIntercceptor.invoke(CrudMethodMetadataPostProcessor.java:111)

at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)

at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)

at com.sun.proxy.$Proxy56.save(Unknown Source)

at org.springframework.data.jpa.example.repository.simple.SimpleConfiguration.main(SimpleConfiguration.java:45)

Caused by: org.hibernate.exception.SQLGrammarException: could not execute statement

at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:80)

at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)

at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)

at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)

at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:190)

at org.hibernate.id.IdentityGenerator$GetGeneratedKeysDelegate.executeAndExtract(IdentityGenerator.java:96)

at org.hibernate.id.insert.AbstractReturningDelegate.performInsert(AbstractReturningDelegate.java:58)

at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3032)

at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3558)

at org.hibernate.action.internal.EntityIdentityInsertAction.execute(EntityIdentityInsertAction.java:98)

at org.hibernate.engine.spi.ActionQueue.execute(ActionQueue.java:490)

at org.hibernate.engine.spi.ActionQueue.addResolvedEntityInsertAction(ActionQueue.java:195)

at org.hibernate.engine.spi.ActionQueue.addInsertAction(ActionQueue.java:179)

at org.hibernate.engine.spi.ActionQueue.addAction(ActionQueue.java:214)

at org.hibernate.event.internal.AbstractSaveEventListener.addInsertAction(AbstractSaveEventListener.java:324)

at org.hibernate.event.internal.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:288)

at org.hibernate.event.internal.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:194)

at org.hibernate.event.internal.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:125)

at org.hibernate.jpa.event.internal.core.JpaPersistEventListener.saveWithGeneratedId(JpaPersistEventListener.java:84)

at org.hibernate.event.internal.DefaultPersistEventListener.entityIsTransient(DefaultPersistEventListener.java:206)

at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:149)

at org.hibernate.event.internal.DefaultPersistEventListener.onPersist(DefaultPersistEventListener.java:75)

at org.hibernate.internal.SessionImpl.firePersist(SessionImpl.java:811)

at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:784)

at org.hibernate.internal.SessionImpl.persist(SessionImpl.java:789)

at org.hibernate.jpa.spi.AbstractEntityManagerImpl.persist(AbstractEntityManagerImpl.java:1181)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

at java.lang.reflect.Method.invoke(Unknown Source)

at org.springframework.orm.jpa.SharedEntityManagerCreator$SharedEntityManagerInvocationHandler.invoke(SharedEntityManagerCreator.java:289)

at com.sun.proxy.$Proxy49.persist(Unknown Source)

at org.springframework.data.jpa.repository.support.SimpleJpaRepository.save(SimpleJpaRepository.java:389)

at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)

at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)

at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)

at java.lang.reflect.Method.invoke(Unknown Source)

at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.executeMethodOn(RepositoryFactorySupport.java:405)

at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:390)

at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:344)

at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:98)

at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:262)

at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:95)

at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)

at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)

... 8 more

Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'test_auditor.app_user' doesn't exist

at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)

at sun.reflect.NativeConstructorAccessorImpl.newInstance(Unknown Source)

at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(Unknown Source)

at java.lang.reflect.Constructor.newInstance(Unknown Source)

at com.mysql.jdbc.Util.handleNewInstance(Util.java:408)

at com.mysql.jdbc.Util.getInstance(Util.java:383)

at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1062)

at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4226)

at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:4158)

at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2615)

at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2776)

at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2840)

at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:2082)

at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2334)

at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2262)

at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:2246)

at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:187)

... 49 more

2014-07-24 09:44:28.674 INFO 8496 --- [ Thread-1] s.c.a.AnnotationConfigApplicationContext : Closing org.springframework.context.annotation.AnnotationConfigApplicationContext@429bd883: startup date [Thu Jul 24 09:44:25 IST 2014]; root of context hierarchy

2014-07-24 09:44:28.676 INFO 8496 --- [ Thread-1] o.s.j.e.a.AnnotationMBeanExporter : Unregistering JMX-exposed beans on shutdown

2014-07-24 09:44:28.678 INFO 8496 --- [ Thread-1] j.LocalContainerEntityManagerFactoryBean : Closing JPA EntityManagerFactory for persistence unit 'default'

I have application.properties as this :

################### DataSource Configuration ##########################

spring.datasource.driverClassName=com.mysql.jdbc.Driver

spring.datasource.url=jdbc:mysql://localhost:3306/test_auditor

spring.datasource.username=root

spring.datasource.password=

################### Hibernate Configuration ##########################

hibernate.dialect=org.hibernate.dialect.MySQLDialect

hibernate.show_sql=true

hibernate.hbm2ddl.auto=create

Users.java :

package org.springframework.data.jpa.example.repository.simple;

import javax.persistence.Column;

import javax.persistence.Entity;

import javax.persistence.NamedQuery;

import javax.persistence.Table;

import org.springframework.data.jpa.domain.AbstractPersistable;

/**

* Sample user class.

*

* @author Oliver Gierke

* @author Thomas Darimont

*/

@Entity

@Table (name="app_User")

@NamedQuery(name = "User.findByTheUsersName", query = "SELECT u FROM User u where u.username = ?")

public class User extends AbstractPersistable {

private static final long serialVersionUID = -2952735933715107252L;

@Column(name="username", unique = true) private String username;

@Column (name="firstname")

private String firstname;

@Column (name="lastname")

private String lastname;

public User() {

this(null);

}

/**

* Creates a new user instance.

*/

public User(Long id) {

this.setId(id);

}

public User(String username, String firstname, String lastname) {

this.firstname = firstname;

this.lastname = lastname;

this.username = username;

}

/**

* Returns the username.

*

* @return

*/

public String getUsername() {

return username;

}

/**

* @param username the username to set

*/

public void setUsername(String username) {

this.username = username;

}

/**

* @return the firstname

*/

public String getFirstname() {

return firstname;

}

/**

* @param firstname the firstname to set

*/

public void setFirstname(String firstname) {

this.firstname = firstname;

}

/**

* @return the lastname

*/

public String getLastname() {

return lastname;

}

/**

* @param lastname the lastname to set

*/

public void setLastname(String lastname) {

this.lastname = lastname;

}

@Override

public String toString() {

return String.format(

"User[id=%d, username='%s', firstName='%s', lastName='%s']",

super.getId(), this.username, this.firstname, this.lastname);

}

}

Simple Configuration.java :

package org.springframework.data.jpa.example.repository.simple;

import java.util.List;

import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;

import org.springframework.context.ConfigurableApplicationContext;

import org.springframework.context.annotation.Configuration;

import org.springframework.context.annotation.PropertySource;

import org.springframework.data.jpa.repository.config.EnableJpaRepositories;

/**

* @author Oliver Gierke

*/

@Configuration

@PropertySource(value = { "classpath:application.properties" })

@EnableJpaRepositories

@EnableAutoConfiguration

class SimpleConfiguration {

public static void main(String[] args) {

ConfigurableApplicationContext context = SpringApplication.run(

SimpleConfiguration.class);

SimpleUserRepository repository = context

.getBean(SimpleUserRepository.class);

repository.save(new User("harmathu", "Harsh", "Mathur"));

repository.save(new User("vibmathu", "Vibhor", "Mathur"));

repository.save(new User("jackbau", "Jack", "Bauer"));

repository.save(new User("chobr", "Chloe", "O'Brian"));

repository.save(new User("kimbau", "Kim", "Bauer"));

repository.save(new User("davipa", "David", "Palmer"));

repository.save(new User("midess", "Michelle", "Dessler"));

Iterable users = repository.findAll();

System.out.println("Users found with findAll():");

System.out.println("-------------------------------");

for (User user : users) {

System.out.println(user);

}

System.out.println();

User user = repository.findOne(1L);

System.out.println("User found with findOne(1L):");

System.out.println("--------------------------------");

System.out.println(user);

System.out.println();

User bauers = repository.findByTheUsersName("chobr");

System.out.println("User found with findByLastName('Bauer'):");

System.out.println("--------------------------------------------");

System.out.println(bauers);

context.close();

}

}

解决方案

I think this is a Spring Boot issue and not a Spring Data JPA issue.

Try changing your properties from:

hibernate.dialect=org.hibernate.dialect.MySQLDialect

hibernate.show_sql=true

hibernate.hbm2ddl.auto=create

to:

spring.jpa.database=MYSQL

spring.jpa.show-sql=true

spring.jpa.hibernate.ddl-auto=create

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

mysql jpa 不要自动建表,如何让Hibernate在与JPA一起使用时自动在数据库中创建表?... 的相关文章

随机推荐

  • 猿如意

    目录 一 什么是猿如意 二 借助猿如意安装Visual Studio Code 1 安装猿如意 2 安装Visual Studio Code 三 总结 一 什么是猿如意 猿如意是CSDN推出来的一款面向开发者的工具 他能够帮助开发者 找到自
  • GEE学习笔记 六十七:【GEE之Python版教程一】GEE学习背景介绍

    相信很多人都对GEE已经比较熟悉了 只是不熟悉GEE的Python的API而已 这里只是做一个简单的总结概括一下GEE相关内容 1 GEE学习基本要求 目前市面上无论出现什么新的技术 总会出现一种课程或者资料 xxx天零基础精通xxx 其实
  • 系统分析与设计——lesson16

    使用 ECB 实现 make reservation 用例的详细设计 包含用例简介 顺序图 类图 用例简介 make reservation这个用例包括 根据location和入住时间查询旅馆 可按照某种属性排序显示旅馆 选择房间 填写入住
  • struts验证框架

    关于validation xml 在validator xml中使用了validation rules xml的验证规则注意一定要加其已经定义好的出错消息考到你的资源包里去 否则出错的时候 显示错误对话框里面却什么错误消息都没有 不允许发生
  • MySQL自动重新连接

    最近部署一个系统 后台用线程池来处理请求 而每个线程有一个mysql连接 当系统运行一阶段后 有些请求会出现操作 Internal error 而操作一次可能又会成功 经过多方调试 发现是MySQL连接超时 如果使用了长连接而长期没有对数据
  • Qt程序Release版出现 类似 QEventLoop: Cannot be used without QApplication 问题的终极解决方案

    Qt程序Release版出现 类似 QEventLoop Cannot be used without QApplication 问题的终极解决方案 参考文章 1 Qt程序Release版出现 类似 QEventLoop Cannot be
  • 初学者学习安装Vmware正版软件

    目录 一 获取下载安装 二 安装图文步骤 三 可能出现问题 2分钟无脑 快速安装Vmware 一 获取下载安装 首先说明 官网下载需要登入账号 最新版可以下载试用版 不需要账号 下述为官网的下载路径图示 仅供参考 注意 目前下载都需要账号了
  • Linux系统Could not connect to '192.168.128.XXX' (port 22): Connection failed.

    网上查找了方法 都是 查看防火墙 service iptables status 关闭防火墙 service iptables stop 打开防火墙 service iptables start 打开sshd service sshd st
  • zigbee串口打印无法显示或乱码解决方法

    zigbee串口打印问题 在终端节点向协调器发数据时 在数据流中伴有该节点的网络地址 而有时通过PC端无法打印出来 1 可能是串口软件的问题 用过好几个串口软件 有时会出现停止 或乱码行为 在经过多次换用软件 发现 SecureCRT 这个
  • uni-app watch事件监听三种用法

    1 普通监听 无法监听到第一次绑定的变化
  • stm32----用状态机判断单双击

    一 什么是状态机 状态机 State Machine 是一种用于描述系统状态和状态之间转换关系的数学模型 说白了就是做出某个动作之后变成什么样的状态 比如stm32中的按键控制开关灯 假设灯一开始是关的 当我们按下按键之后 灯亮了 这相当于
  • REST API 设计最佳实践:如何正确使用 HTTP 状态码?

    总的来说 HTTP协议出现以来Web服务也就存在了 但是 自从云计算出现后 才成为实现客户端与服务和数据交互的普遍方法 作为一名开发者 我很幸运能够在工作中使用一些仍然存在的SOAP服务 但是 我主要接触的是REST 这是一种基于资源的AP
  • dev express for asp.net 如何更换主题

    1 如下图点击菜单 2 选择主题然后按 Update Project
  • Python——协程(Coroutine),异步IO

    目录 生成器 Generator yield表达式的使用 生产者和消费者模型 编辑 yield from表达式 协程 Coroutine asyncio coroutine async await 总结 由于GIL的存在 导致Python多
  • Java FileReader

    Java FileReader Java FileReader Java FileReader class is part of java io package Java FileReader类是java io软件包的一部分 The Fil
  • Android自动化测试,5个必备的测试框架

    Appium Appium是一个开源的移动测试工具 支持iOS和Android 它可以用来测试任何类型的移动应用 原生 网络和混合 作为一个跨平台的工具 你可以在不同的平台上运行相同的测试 为了实现跨平台的功能 Appium使用了供应商提供
  • python 抖音采集_python爬取抖音视频的实例详解

    import requests import json import re import os from pprint import pprint as pp import queue class DouYin header accept
  • 全书简介和作者寄语

    巨硬的NumPy 巨硬的NumPy 教程包括两部分 从小白到入门 和 从入门到熟练 从小白到入门 旨在帮助没有基础的同学快速掌握 numpy 的常用功能 保证日常绝大多数场景的使用 从入门到熟练 目的是帮助有进一步需要的同学对 numpy
  • (六)Kubernetes - 手动部署(二进制方式安装)

    Kubernetes 手动部署 5 1 部署Nginx Keepalived高可用负载均衡器 1 1 安装软件包 Master1 Master2 1 2 Nginx配置文件 主备相同 1 3 keepalived配置文件 Master1 1
  • mysql jpa 不要自动建表,如何让Hibernate在与JPA一起使用时自动在数据库中创建表?...

    I am new to JPA And for now I am trying to understand standard examples I was reading online and saw a few stackoverflow