JPA OneToMany关系 - 未设置foreignkey

时间:2016-03-13 08:45:22

标签: hibernate orm spring-data-jpa many-to-one hibernate-onetomany

我使用ajax post

将数据发送到服务器
#if I2CDEV_IMPLEMENTATION == I2CDEV_ARDUINO_WIRE
    Wire.begin();
    TWBR = 24; // 400kHz I2C clock (200kHz if CPU is 8MHz). Comment this line if having compilation difficulties with TWBR.
#elif I2CDEV_IMPLEMENTATION == I2CDEV_BUILTIN_FASTWIRE
    Fastwire::setup(400, true);
#endif
Serial.begin(115200);
while (!Serial) // wait for Leonardo enumeration, others continue immediately
   ;
mpu.initialize();
Serial.println(mpu.testConnection() ? F("") : F("MPU6050 connection failed"));

mpu.setI2CMasterModeEnabled(false);
mpu.setI2CBypassEnabled(true) ;
mpu.setSleepEnabled(false);

RTC.begin();
DateTime now = RTC.now();
DateTime nowSetup = RTC.now();
double startTime = nowSetup.unixtime();
if (! RTC.isrunning()) {
   Serial.println("RTC is NOT running!");
}  

我遇到了服务器错误。 foreignKey未设置为Comments表。

  var obj = {
    'sub': 'this is a test.'
    ,'userName': 'dbdyd'
    ,'saveDate': new Date()
    ,'comments': [
       {'comment':'1a', 'saveDate2': new Date(), 'seq2': null}
       ,{'comment':'2b', 'saveDate2': new Date(), 'seq2': null}
    ]
  };


  $.ajax({
    url: '/cp/RestApi/Posts',
    type: 'POST',
    dataType: 'json',
    contentType: 'application/json',
    data: JSON.stringify(obj)
  })
  .done(function() {
    console.log("success");
  })
  .fail(function() {
    console.log("error");
  });

数据库架构

  INFO: Starting Coyote HTTP/1.1 on http-8080
  Posts [seq=null, sub=this is a test., userName=dbdyd, saveDate=Sun Mar 13 09:05:46 KST 2016
, comments=[Comments [seq2=null, comment=2b, saveDate2=Sun Mar 13 09:05:46 KST 2016, posts=null], Comments [seq2=null, comment=1a, saveDate2=Sun Mar 13 09:05:46 KST 2016, posts=null]]]
Hibernate: insert into onnuricp.posts (save_date, sub, user_name) values (?, ?, ?)
Hibernate: insert into onnuricp.comments (comment, seq, save_date2) values (?, ?, ?)
09:05:47.315 [http-8080-1] ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Column 'seq' cannot be null
Mar 13, 2016 9:05:47 AM org.apache.catalina.core.StandardWrapperValve invoke

我对弹簧数据jpa有些问题。 @OneToMany关系似乎错了,但我不知道。

Create Table: CREATE TABLE `posts` (
  `seq` int(11) NOT NULL AUTO_INCREMENT COMMENT '게시판번호',
  `sub` varchar(255) DEFAULT NULL COMMENT '제목',
  `user_name` varchar(50) DEFAULT NULL COMMENT '작성자',
  `save_date` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '입력일자',
  PRIMARY KEY (`seq`)
) ENGINE=InnoDB AUTO_INCREMENT=84 DEFAULT CHARSET=utf8 COMMENT='게시판'



CREATE TABLE `comments` (
  `seq2` int(11) NOT NULL AUTO_INCREMENT COMMENT '댓글번호',
  `comment` varchar(255) NOT NULL COMMENT '내용',
  `save_date2` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '작성일자',
  `seq` int(11) NOT NULL COMMENT '게시판번호',
  PRIMARY KEY (`seq2`),
  KEY `FK_posts_TO_comments` (`seq`),
  CONSTRAINT `FK_posts_TO_comments` FOREIGN KEY (`seq`) REFERENCES `posts` (`seq`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COMMENT='댓글'
;

保存对象(帖子和评论)。 和服务实现这样。

@Entity
@Table(name = "posts")
public class Posts {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Basic(optional = false)
  @Column(name = "seq")
  private Integer seq;

  @Column(name = "sub", nullable = true)
  private String sub;

  @Column(name = "user_name")
  private String userName;

  @Column(name = "save_date", nullable = false)
  @Temporal(TemporalType.TIMESTAMP)
  private Date saveDate;

  @OneToMany( mappedBy = "posts", cascade = CascadeType.ALL)
  private Set<Comments> comments;

}



@Entity
@Table(name = "comments")
public class Comments implements Serializable {

  @Id
  @GeneratedValue(strategy = GenerationType.IDENTITY)
  @Basic(optional = false)
  @Column(name = "seq2")
  private Integer seq2;

  @Column(name = "comment", nullable = false)
  private String comment;

  @Column(name = "save_date2", nullable = false)
  @Temporal(TemporalType.TIMESTAMP)
  private Date saveDate2;

  @ManyToOne(optional = false)
  @JoinColumn(name = "seq", referencedColumnName="seq", nullable = false)
  private Posts posts;

}

请帮我解决JPA关系。

2 个答案:

答案 0 :(得分:0)

您的@OneToMany映射看起来是正确的。但您不需要指定referencedColumnName = "seq"只需使用

@ManyToOne(optional = false)
@JoinColumn(name = "seq", nullable = false)
private Posts posts;

请勿对CommentsPosts使用复数形式。只需CommentPost

您可以使用Comments

保存Posts
Posts post = new Posts();
post.setComments(new HashSet<Comments>());

Comments comment = new Comments();
comment.setPosts(post);
post.getComments().add(comment);

save(post);

如果数据库中已有post。您可以通过这种方式添加comment

Comments comment = new Comments();
comment.setPosts(post);

save(comment);

答案 1 :(得分:0)

我解决了这个问题并遇到了另一个问题。 所以,我在这篇文章中添加了一些解决方案。

首先,我修复了外键未设置为Comments对象的问题。 我必须在Posts类中添加方法[ addComments(评论合作)]。 如果我有数组注释对象,我必须添加它实现的对象方法添加到集合。没有什么可以添加其他东西。

@Entity
@Table(name = "posts", catalog = "onnuricp")
public class Posts {

  @OneToMany( mappedBy = "posts", cascade = CascadeType.ALL)
  private Set<Comments> comments;

  public Posts() {
    comments = new HashSet<Comments>();
  }

  public void addComments(Comments co) {
    co.setPosts(this);
    comments.add(co);
  }

}

其次,我遇到了关于 Jackson databind错误的问题。 添加一些代码来修复它。

@JsonIdentityInfo(
  generator = ObjectIdGenerators.PropertyGenerator.class, property = "seq2")

public class CommentsDto implements Serializable {

  getter .. ;
  setter .. ;

}


@JsonIdentityInfo(
  generator = ObjectIdGenerators.PropertyGenerator.class, property = "seq")

public class PostsDto implements Serializable {

  getter .. ;
  setter .. ;
}
相关问题