问题描述
当我尝试使用Hibernate 4 - MySQL配置加载Spring引导应用程序时,出现配置堆栈跟踪错误。我无法弄清楚是什么导致这个外键约束问题。 非常感谢任何帮助!
**原因:java。 sql.SQLException:无法添加外键约束
在com.mysql.jdbc.SQLError.createSQLException(SQLError.java:963)
在com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3966 )
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3902)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2526)
at com。 mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2673)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)
at com.mysql.jdbc.ConnectionImpl.execSQL( ConnectionImpl.java:2503)
at com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:839)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:739)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:49)
... **
以下是我的三个数据库表:
@Entity
公共类主体实现{
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
私人long principal_id;
@Column(name =username,unique = true,nullable = false)
私有字符串名称;
@Column(unique = true,nullable = false)
private String email;
@Column(nullable = false)
私人字符串密码;
@Column(nullable = false)
私有布尔锁定;
@ManyToMany(fetch = FetchType.EAGER)
@JoinTable(joinColumns = {@JoinColumn(name =PRINCIPAL_ID,referencedColumnName =PRINCIPAL_ID)},inverseJoinColumns = {@JoinColumn name =ROLE_ID,referencedColumnName =ROLE_ID)})
private Set< Role>角色;
public Principal(){
super();
locked = false;
public Principal(final String nameToSet,final String passwordToSet,final Set< Role> rolesToSet){
super();
name = nameToSet;
password = passwordToSet;
roles = rolesToSet;
}
public Principal(final UserDto userDto){
super();
name = userDto.getName();
password = userDto.getPassword();
roles = userDto.getRoles();
}
@Override
public Long getId(){
return principal_id;
}
@Override
public void setId(final Long idToSet){
principal_id = idToSet;
}
@Override
public String getName(){
return name;
}
public void setName(final String nameToSet){
name = nameToSet;
}
public String getEmail(){
return email;
}
public void setEmail(final String emailToSet){
email = emailToSet;
}
public String getPassword(){
return password;
}
public void setPassword(final String passwordToSet){
password = passwordToSet;
}
public Set< Role> getRoles(){
返回角色;
}
public void setRoles(final Set< Role> rolesToSet){
roles = rolesToSet;
}
public Boolean getLocked(){
return locked;
}
public void setLocked(final Boolean lockedToSet){
locked = lockedToSet;
}
}
@Entity
公共类角色实现INameableEntity,INameableDto {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private long role_id;
@Column(unique = true,nullable = false)
@Size(min = 2,max = 30)
@NotNull
私有字符串名称;
public Role(){
super();
}
public Role(final String nameToSet){
super();
name = nameToSet;
}
// API
@Override
public Long getId(){
return role_id;
}
@Override
public void setId(final Long idToSet){
role_id = idToSet;
}
@Override
public String getName(){
return name;
}
public void setName(final String nameToSet){
name = nameToSet;
}
jdbc.driverClassName = com.mysql.jdbc.Driver
jdbc.url = jdbc:mysql :// localhost:3306 / qlc?& useSSL = false
jdbc.username = root
jdbc.password =密码
hibernate.dialect = org。 hibernate.dialect.MySQL5Dialect
hibernate.show_sql = true
hibernate.hbm2ddl.auto = update
jpa.generateDdl = true
<$ p $ {code> @Configuration
@EnableTransactionManagement
@ComponentScan({org.qlc.um.persistence})
@PropertySource({persistence-mysql.properties })
@EnableJpaRepositories(basePackages =org.qlc.um.persistence.dao)
public class UmPersistenceJpaConfig {
@Autowired
private Environment env;
public UmPersistenceJpaConfig(){
super();
$ beans
$ b $Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory(){
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String [] {org.qlc.um});
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
返回em;
@Bean
public DataSource dataSource(){
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty(jdbc.driverClassName));
dataSource.setUrl(env.getProperty(jdbc.url));
dataSource.setUsername(env.getProperty(jdbc.username));
dataSource.setPassword(env.getProperty(jdbc.password));
返回dataSource;
$Be
public JpaTransactionManager transactionManager(){
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory()。getObject());
返回transactionManager;
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation(){
return new PersistenceExceptionTranslationPostProcessor();
$ b $ //
final属性additionalProperties(){
final属性hibernateProperties = new Properties();
hibernateProperties.setProperty(hibernate.hbm2ddl.auto,env.getProperty(hibernate.hbm2ddl.auto,create-drop));
hibernateProperties.setProperty(hibernate.dialect,env.getProperty(hibernate.dialect));
// setProperty(hibernate.hbm2ddl.auto,hibernateHbm2ddlAuto);
// setProperty(hibernate.ejb.naming_strategy,org.hibernate.cfg.ImprovedNamingStrategy.class.getName());
返回hibernateProperties;
}
}
我的猜测是,因为你没有在实体的id中标记@column,所以它将获取你的getter的默认属性名称,它将是'id'。
委托人
@Id
@GeneratedValue(strategy = GenerationType.AUTO )
Column(name =principal_id)
private long principal_id;
角色
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Column(name =role_id)
private Long role_id;
I am getting a configuration stacktrace error when I try to load my spring boot application with a Hibernate 4 - MySQL configuration. I can't figure out what is causing this foreign key constraint problem. Any help greatly appreciated!
**Caused by: java.sql.SQLException: Cannot add foreign key constraint
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:963)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3966)
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:3902)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:2526)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:2673)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2545)
at com.mysql.jdbc.ConnectionImpl.execSQL(ConnectionImpl.java:2503)
at com.mysql.jdbc.StatementImpl.executeInternal(StatementImpl.java:839)
at com.mysql.jdbc.StatementImpl.execute(StatementImpl.java:739)
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:49)
...**
Here are my three database tables:
@Entity
public class Principal implements {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long principal_id;
@Column(name = "username", unique = true, nullable = false)
private String name;
@Column(unique = true, nullable = false)
private String email;
@Column(nullable = false)
private String password;
@Column(nullable = false)
private Boolean locked;
@ManyToMany( fetch = FetchType.EAGER)
@JoinTable(joinColumns = { @JoinColumn(name = "PRINCIPAL_ID", referencedColumnName = "PRINCIPAL_ID") }, inverseJoinColumns = { @JoinColumn(name = "ROLE_ID", referencedColumnName = "ROLE_ID") })
private Set<Role> roles;
public Principal() {
super();
locked = false;
}
public Principal(final String nameToSet, final String passwordToSet, final Set<Role> rolesToSet) {
super();
name = nameToSet;
password = passwordToSet;
roles = rolesToSet;
}
public Principal(final UserDto userDto) {
super();
name = userDto.getName();
password = userDto.getPassword();
roles = userDto.getRoles();
}
@Override
public Long getId() {
return principal_id;
}
@Override
public void setId(final Long idToSet) {
principal_id = idToSet;
}
@Override
public String getName() {
return name;
}
public void setName(final String nameToSet) {
name = nameToSet;
}
public String getEmail() {
return email;
}
public void setEmail(final String emailToSet) {
email = emailToSet;
}
public String getPassword() {
return password;
}
public void setPassword(final String passwordToSet) {
password = passwordToSet;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(final Set<Role> rolesToSet) {
roles = rolesToSet;
}
public Boolean getLocked() {
return locked;
}
public void setLocked(final Boolean lockedToSet) {
locked = lockedToSet;
}
}
@Entity
public class Role implements INameableEntity, INameableDto {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long role_id;
@Column(unique = true, nullable = false)
@Size(min = 2, max = 30)
@NotNull
private String name;
public Role() {
super();
}
public Role(final String nameToSet) {
super();
name = nameToSet;
}
// API
@Override
public Long getId() {
return role_id;
}
@Override
public void setId(final Long idToSet) {
role_id = idToSet;
}
@Override
public String getName() {
return name;
}
public void setName(final String nameToSet) {
name = nameToSet;
}
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/qlc?&useSSL=false
jdbc.username=root
jdbc.password=password
hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
jpa.generateDdl=true
@Configuration
@EnableTransactionManagement
@ComponentScan({ "org.qlc.um.persistence" })
@PropertySource({ "persistence-mysql.properties" })
@EnableJpaRepositories(basePackages = "org.qlc.um.persistence.dao")
public class UmPersistenceJpaConfig {
@Autowired
private Environment env;
public UmPersistenceJpaConfig() {
super();
}
// beans
@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
final LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
em.setDataSource(dataSource());
em.setPackagesToScan(new String[] { "org.qlc.um" });
final HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
em.setJpaVendorAdapter(vendorAdapter);
em.setJpaProperties(additionalProperties());
return em;
}
@Bean
public DataSource dataSource() {
final DriverManagerDataSource dataSource = new DriverManagerDataSource();
dataSource.setDriverClassName(env.getProperty("jdbc.driverClassName"));
dataSource.setUrl(env.getProperty("jdbc.url"));
dataSource.setUsername(env.getProperty("jdbc.username"));
dataSource.setPassword(env.getProperty("jdbc.password"));
return dataSource;
}
@Bean
public JpaTransactionManager transactionManager() {
final JpaTransactionManager transactionManager = new JpaTransactionManager();
transactionManager.setEntityManagerFactory(entityManagerFactory().getObject());
return transactionManager;
}
@Bean
public PersistenceExceptionTranslationPostProcessor exceptionTranslation() {
return new PersistenceExceptionTranslationPostProcessor();
}
//
final Properties additionalProperties() {
final Properties hibernateProperties = new Properties();
hibernateProperties.setProperty("hibernate.hbm2ddl.auto", env.getProperty("hibernate.hbm2ddl.auto", "create-drop"));
hibernateProperties.setProperty("hibernate.dialect", env.getProperty("hibernate.dialect"));
// setProperty("hibernate.hbm2ddl.auto", hibernateHbm2ddlAuto);
// setProperty("hibernate.ejb.naming_strategy", org.hibernate.cfg.ImprovedNamingStrategy.class.getName());
return hibernateProperties;
}
}
my guess, since you have not marked the @column in id of entity it is taking default property name of your getter which will be 'id'
try,Principal
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Column(name="principal_id")
private Long principal_id;
Role
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
Column(name="role_id")
private Long role_id;
这篇关于Hibernate 4 Annotation - MySQL配置错误:java.sql.SQLException:无法添加外键约束的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!