jpa异常

异常信息

Error executing DDL "alter table blog_comment add constraint FK5pu6xb8447el9dfjw4ftmpk0i foreign key (articleId) references blog_article (articleId)" via JDBC Statement

实体类

package com.blog.entity;

import java.util.Date;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;


/*
 * 文章评论
 */
@Entity
@Table(name="blog_comment")
public class Comment {
	
	private Long commentid;
	private Article article;//文章
	private Date createTime;//评论时间
	private User user;//评论者
	private String content;//评论内容
	private Comment target;//针对的目标
	
	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	public Long getCommentid() {
		return commentid;
	}
	@ManyToOne
	@JoinColumn(name="articleId")
	public Article getArticle() {
		return article;
	}
	@ManyToOne
	@JoinColumn(name="userId")
	public User getUser() {
		return user;
	}
	@ManyToOne
	@JoinColumn(name="targetId")
	public Comment getTarget() {
		return target;
	}
	public void setCommentid(Long commentid) {
		this.commentid = commentid;
	}
		
	public void setArticle(Article article) {
		this.article = article;
	}
	
	public Date getCreateTime() {
		return createTime;
	}
	
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
	
	public void setUser(User user) {
		this.user = user;
	}
	@Column(columnDefinition="TEXT")
	public String getContent() {
		return content;
	}
	
	public void setContent(String content) {
		this.content = content;
	}

	
	public void setTarget(Comment target) {
		this.target = target;
	}

	
}

Springboot 建了个实体,其中两个字段是关联外键,User和Article现在提示创建失败。什么原因呢?
Article实体也有关联的外键,相同的方法就创建成功了。。

兄弟啊,你这学习一下 markdown 吧,求你了。

现在就去看。。

看这个应该是启动的时候,根据你定义的实体去执行 表结构修改语句 报的异常

是不是把user表和article表,也就是出问题的表,一块删了,重新建问题可能就解决了?

一般来说,不会去建立数据库的主外键关系。你非要创建的话,那你就试试看,把受影响的表都删除了。重新启动。

你可以把你的异常信息复制全乎点,看看。

2019-12-12 17:11:41.877 WARN 10696 — [ restartedMain] o.h.t.s.i.ExceptionHandlerLoggedImpl : GenerationTarget encountered exception accepting command : Error executing DDL “alter table blog_comment add constraint FK3tcobnr2i19hw4g4ce16mj4dw foreign key (userId) references blog_user (userid)” via JDBC Statement

Caused by: java.sql.SQLException: Cannot add foreign key constraint

导致这种异常的原因有很多

  1. 外键字段不能为该表的主键
  2. 外键字段参考字段必须为参考表的主键
  3. 两个字段必须具有相同的数据类型和长度
  4. 两个字段必须具有相同的约束
  5. 两个字段所在表的引擎都为InnoDB
  6. 两个字段的字符集必须相同
  7. 两个字段的核对必须相同
  8. 创建关系的时候,表里面不能有数据

现在都没人用数据库的主外键约束了,都是靠程序去维护关系的。你不如把jpa的那个ddl执行关掉。

spring.jpa.hibernate.ddl-auto=none
我把update 设成none,不知道是关了,还是什么别的原因,没有提示异常了。
但数据结构里显示有外键。

那是你之前就建立好的关系,它又不会去删除你创建好的表。