【问题标题】:JPA OneToMany Relationship - foreignkey is not setJPA OneToMany 关系 - 未设置外键
【发布时间】:2016-03-13 08:45:21
【问题描述】:

我使用 ajax post 向服务器发送数据

  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");
  });

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

  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

数据库架构

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='댓글'
;

我对 spring data jpa 有一些问题。 @OneToMany 关系似乎是错误的,但我不知道。

@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;

}

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

Posts entity = new Post();
Posts savedEntity = repository.save(entity);

请帮我解决 JPA 关系问题。

【问题讨论】:

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


    【解决方案1】:

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

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

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

    您可以使用Posts 保存Comments

    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);
    

    【讨论】:

    • 非常感谢@v.ladyev 的礼貌回答!! ~~.
    【解决方案2】:

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

    首先,我修复了未将外键设置为 Comments 对象的问题。 我必须将方法 [addComments(Comments co)] 添加到 Posts 类。 如果我有数组 Comments 对象,我必须添加它实现的对象方法以添加到集合中。没有什么可以补充的。

    @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 error的问题。 添加一些代码来修复它。

    @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 .. ;
    }
    

    【讨论】:

      猜你喜欢
      • 2010-10-23
      • 2013-01-13
      • 2017-11-13
      • 2014-08-19
      • 1970-01-01
      • 2020-05-17
      • 1970-01-01
      • 1970-01-01
      • 2017-01-23
      相关资源
      最近更新 更多