Hibernate绑定在插入时返回null。

huangapple go评论78阅读模式
英文:

Hibernate binding returns null on insert

问题

我在这里寻求帮助,因为我已经在互联网上搜索了几个小时,但没有找到答案。也许这里的某个人会对我的问题有解决方案。

我刚开始使用 Spring Boot,所以请不要对我太苛刻,我可能在文档中遗漏了一些信息。
我试图使用一个类似这样的 JSON 文件向我的数据库添加数据。在“OneToMany”关系和相反的“ManyToOne”关系中,一切都正常工作(我遵循了这里的文档)。
我将 Cascade.ALL 设置为在实体之间进行传播。
正如你所看到的,Hibernate 会将绑定值设置为 null,就像它从未被插入过一样,尽管它似乎在前一步中已插入。
许多主题都涉及到这个问题,对于其中许多主题,它们已经通过设置 null = false 选项来解决,但在我这里不起作用。

信息:
一个联系人可以有多个电子邮件地址,而一个电子邮件地址只属于一个联系人。

我的代码:

Emails

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Entity
@Table(name = "Email")
public class Email implements Serializable {

    @Id
    @GeneratedValue
    @Column(name = "idEmail")
    private int id;

    @Column(name = "Email")
    @JsonProperty("mail")
    private String email;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "Contact_idContact")
    private Contact contact;
}

Contact

@Entity
@Table(name = "Contact")
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class Contact implements Serializable {

    @GeneratedValue
    @Id
    @Column(name = "idContact", nullable = false, unique = true)
    private int id;

    @Column(name = "Nom")
    private String nom;

    @Column(name = "Prenom")
    private String prenom;

    @Column(name = "Mobile")
    private String mobile;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = "contact")
    private Set<Email> emails = new HashSet<>();
}

我的 JSON 提交:

{
"contacts": [
    {
      "nom": "myName",
      "prenom": "MyFirstName",
      "mobile": "06666666666",
      "emails": [
        {
          "mail": "mail1@test.com"
        },
        {
          "mail": "mail2@test.com"
        }
      ],
    }
  ]
}

POST 方法

 @PostMapping("/add")
    public ResponseEntity<Void> addContact(@RequestBody Contact contact) {

        Contact contact1 = contactService.save(contact);
        URI location = ServletUriComponentsBuilder
                .fromCurrentRequest()
                .path("/{id}")
                .buildAndExpand(contact1.getId())
                .toUri();
        return ResponseEntity.created(location).build();
    }

错误:

2020-10-15 16:40:16.501 DEBUG 13608 --- [nio-9000-exec-2] org.hibernate.SQL                        : insert into Contact (Mobile, Nom, Prenom, idContact) values (?, ?, ?, ?)
2020-10-15 16:40:16.502 TRACE 13608 --- [nio-9000-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] - [06666666666]
2020-10-15 16:40:16.503 TRACE 13608 --- [nio-9000-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [2] as [VARCHAR] - [MyName]
2020-10-15 16:40:16.504 TRACE 13608 --- [nio-9000-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [3] as [VARCHAR] - [MyFirstName]
2020-10-15 16:40:16.505 TRACE 13608 --- [nio-9000-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [4] as [INTEGER] - [46]
2020-10-15 16:40:16.510 DEBUG 13608 --- [nio-9000-exec-2] org.hibernate.SQL                        : insert into Email (Contact_idContact, Email, idEmail) values (?, ?, ?)
2020-10-15 16:40:16.511 TRACE 13608 --- [nio-9000-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [INTEGER] - [null]
2020-10-15 16:40:16.512 TRACE 13608 --- [nio-9000-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [2] as [VARCHAR] - [mail1@test.com]
2020-10-15 16:40:16.512 TRACE 13608 --- [nio-9000-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [3] as [INTEGER] - [47]
2020-10-15 16:40:16.542  WARN 13608 --- [nio-9000-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1048, SQLState: 23000
2020-10-15 16:40:16.542 ERROR 13608 --- [nio-9000-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper   : Column 'Contact_idContact' cannot be null
2020-10-15 16:40:16.636 ERROR 13608 --- [nio-9000-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

在这种情况下,Contact_idContact 应该被插入为 46。

出了什么问题?

英文:

I'm here to get help because I've been searching the internet for a few hours without finding my answers. Maybe someone here will have a solution to my problem.

I'm new with spring boot, so don't be too mean to me, I probably missed some information in the documentation.
I'm trying to add data to my database with a json file that looks like this one.
Everything works correctly up to the OneToMany relationship and vice versa ManyToOne (I followed the doc here).
I put Cascade.ALL to propagate to entities.
As you can see, Hibernate makes a binding with a null value, as if it had never been inserted whereas it seems to be at the previous step.
A lot of topics deal with this problem, and for many of them they have been solved with the null = false option, but it doesn't work for me.

Information:
A contact can have multiple email addresses, and an email address belongs to only one contact.

My code :

Emails

@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
@Entity
@Table(name = &quot;Email&quot;)
public class Email implements Serializable {

    @Id
    @GeneratedValue
    @Column(name = &quot;idEmail&quot;)
    private int id;

    @Column(name = &quot;Email&quot;)
    @JsonProperty(&quot;mail&quot;)
    private String email;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = &quot;Contact_idContact&quot;)
    private Contact contact;
}

Contact

@Entity
@Table(name = &quot;Contact&quot;)
@NoArgsConstructor
@AllArgsConstructor
@Getter
@Setter
public class Contact implements Serializable {

    @GeneratedValue
    @Id
    @Column(name = &quot;idContact&quot;, nullable = false, unique = true)
    private int id;

    @Column(name = &quot;Nom&quot;)
    private String nom;

    @Column(name = &quot;Prenom&quot;)
    private String prenom;

    @Column(name = &quot;Mobile&quot;)
    private String mobile;

    @OneToMany(cascade = CascadeType.ALL, mappedBy = &quot;contact&quot;)
    private Set&lt;Email&gt; emails = new HashSet&lt;&gt;();
}

My json post :

{
&quot;contacts&quot;: [
    {
      &quot;nom&quot;: &quot;myName&quot;,
      &quot;prenom&quot;: &quot;MyFirstName&quot;,
      &quot;mobile&quot;: &quot;06666666666&quot;,
      &quot;emails&quot;: [
        {
          &quot;mail&quot;: &quot;mail1@test.com&quot;
        },
	      {
          &quot;mail&quot;: &quot;mail2@test.com&quot;
        }
      ],
    }
  ]
}

POST Method

 @PostMapping(&quot;/add&quot;)
    public ResponseEntity&lt;Void&gt; addContact(@RequestBody Contact contact) {

        Contact contact1 = contactService.save(contact);
        URI location = ServletUriComponentsBuilder
                .fromCurrentRequest()
                .path(&quot;/{id}&quot;)
                .buildAndExpand(contact1.getId())
                .toUri();
        return ResponseEntity.created(location).build();
    }

Error:

2020-10-15 16:40:16.501 DEBUG 13608 --- [nio-9000-exec-2] org.hibernate.SQL                        : insert into Contact (Mobile, Nom, Prenom, idContact) values (?, ?, ?, ?)
2020-10-15 16:40:16.502 TRACE 13608 --- [nio-9000-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [VARCHAR] - [06666666666]
2020-10-15 16:40:16.503 TRACE 13608 --- [nio-9000-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [2] as [VARCHAR] - [MyName]
2020-10-15 16:40:16.504 TRACE 13608 --- [nio-9000-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [3] as [VARCHAR] - [MyFirstName]
2020-10-15 16:40:16.505 TRACE 13608 --- [nio-9000-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [4] as [INTEGER] - [46]
2020-10-15 16:40:16.510 DEBUG 13608 --- [nio-9000-exec-2] org.hibernate.SQL                        : insert into Email (Contact_idContact, Email, idEmail) values (?, ?, ?)
2020-10-15 16:40:16.511 TRACE 13608 --- [nio-9000-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [1] as [INTEGER] - [null]
2020-10-15 16:40:16.512 TRACE 13608 --- [nio-9000-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [2] as [VARCHAR] - [mail1@test.com]
2020-10-15 16:40:16.512 TRACE 13608 --- [nio-9000-exec-2] o.h.type.descriptor.sql.BasicBinder      : binding parameter [3] as [INTEGER] - [47]
2020-10-15 16:40:16.542  WARN 13608 --- [nio-9000-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper   : SQL Error: 1048, SQLState: 23000
2020-10-15 16:40:16.542 ERROR 13608 --- [nio-9000-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper   : Column &#39;Contact_idContact&#39; cannot be null
2020-10-15 16:40:16.636 ERROR 13608 --- [nio-9000-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause

In this case, Contact_idContact should be 46 as inserted.

What's wrong with it?

答案1

得分: 0

我解决了我的问题。我在Email.java中忘记了一个CascadeType.ALL。

英文:

I resolved my problem. I forgot a CascadeType.ALL in Email.java.

huangapple
  • 本文由 发表于 2020年10月15日 22:52:18
  • 转载请务必保留本文链接:https://go.coder-hub.com/64374289.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定