【问题标题】:OneToOne with hibernate JPAOneToOne 与休眠 JPA
【发布时间】:2021-06-25 18:45:05
【问题描述】:

我正在尝试关联两个表

用户和地址 一个用户只有一个地址,一个地址只属于一个用户。密钥按地址的 ID 列出 所以我首先创建我的地址,然后我创建一个用户并将其与地址 ID 链接 但我根本做不到,我有以下错误作为回报:

Error creating bean with name 'entityManagerFactory' defined in class path resource [org / springframework / boot / autoconfigure / orm / jpa / HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is java.lang.NullPointerException: Cannot invoke "org.hibernate.mapping.PersistentClass.getTable ()" because "classMapping" is null

我对 hibernate 完全陌生,但我需要这个项目用于大学,所以请原谅我对这个主题的无知

这是我的代码:

USER/USUARIO 类:

import org.hibernate.validator.constraints.br.CPF;

import javax.persistence.*;
import javax.validation.constraints.*;


public class Usuario{

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Integer id;

    @Column
    @NotNull
    @Size(min = 5,max = 30)
    @Pattern(regexp = "^[a-zA-Z\s]*$", message = "Nome inválido! Digite apenas letras e espaçamento") //Permite apenas letras e espaço
    private String nome;

    @NotNull
    @CPF
    private String cpf;

    @NotNull
    @Email
    private String email;

    @NotNull
    @Size(min = 5,max = 12)
    private String senha;

    private Integer telefone;

    @DecimalMin("0")
    @DecimalMax("5")
    private Double avaliacao;

    @NotNull
    @OneToOne(cascade = CascadeType.ALL,mappedBy = "id")
    private Endereco endereco;

    //Atributos para usuários autônomos

    private Boolean isAutonomo;

    private String categoriaAutonomo;

    private Double precoAutonomo;

//Getters and Setters

ADRESS/ENDERECO 类

import javax.persistence.*;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

@Entity
@Table(name = "endereco")
public class Endereco {

    @Id
    @OneToOne
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    @NotNull
    @Size(min = 8,max = 8)
    private String cep;

    @NotNull
    private String bairro;

    @NotNull
    private String logradouro;

    @NotNull
    private Integer numeroLogradouro;

    private String complemento;

    @NotNull
    @Size(min = 2,max = 2)
    private String uf;

    @NotNull
    private String cidade;

控制器

import br.com.bandtec.projetocaputeam.dominio.*;
import br.com.bandtec.projetocaputeam.repository.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/caputeam")
public class CaputeamController {

    @Autowired
    private UsuariosRepository usuariosRepository;

    @Autowired
    private EnderecoRepository enderecoRepository;

//--- USERS
    @GetMapping("/usuarios")
    public ResponseEntity getUsuarios(){
        List<Usuario> usuarios = usuariosRepository.findAll();
        return !usuarios.isEmpty() ? ResponseEntity.status(200).body(usuarios) :
                                     ResponseEntity.status(204).build();
    }

    @PostMapping("/cadastrar-usuario")
    public ResponseEntity cadastrarUsuario(@RequestBody @Valid Usuario novoUsuario){
        usuariosRepository.save(novoUsuario);
        return ResponseEntity.ok().build();
    }

//--- ADRESS
    @PostMapping("/cadastrar-endereco")
    public ResponseEntity cadastrarEndereco(@RequestBody @Valid Endereco novoEndereco){
        enderecoRepository.save(novoEndereco);
        return ResponseEntity.ok().build();
    }
}

应用

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ProjetoCaputeamApplication {

    public static void main(String[] args) {
        SpringApplication.run(ProjetoCaputeamApplication.class, args);
    }

}

这就是我的逻辑模型

编辑 我试图删除“映射者”部分并从地址中删除@OneToOne,但现在当我尝试发送地址的 POST 时它返回以下错误:

org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException: Referential integrity constraint violation: "FKMXNOON0IKGA83W1A203Y6OFPN: PUBLIC.ENDERECO FOREIGN KEY(ID) REFERENCES PUBLIC.USUARIO(ID) (1)"; SQL statement:
insert into endereco (bairro, cep, cidade, complemento, logradouro, numero_logradouro, uf, id) values (?, ?, ?, ?, ?, ?, ?, ?) [23506-200]

好像他没有输入任何地址字段

我像这样通过邮递员发送我的 POST:

{
    "bairro": "Vila Prmavera",
    "cep": "03388110",
    "cidade": "São Paulo",
    "complemento": "b1",
    "logradouro": "Rua das dores",
    "numeroLogradouro": 7,
    "uf": "SP"
}

【问题讨论】:

    标签: java spring hibernate jpa h2


    【解决方案1】:

    不要映射到 ID。 Map 表示实体映射而不是 id 映射。

    public class Endereco {
    
        @Id
        @GeneratedValue(strategy = GenerationType.AUTO)
        private Integer id;
    
        @OneToOne
        private Usuario usuario
    
         ....
       }
    

    或者,如果您不希望 Endereco 保留对 Usuario 的引用,只需将其删除即可。但是您不能将@OneToOne 放在 id 字段上。如果您只有一侧有@OneToOne,那么您还需要注释 @MapsId

    public class Usario {
    
            @NotNull
            @MapsId
            @OneToOne(cascade = CascadeType.ALL)
            private Endereco endereco;
    
     public class Endereco {
        
            @Id
            @GeneratedValue(strategy = GenerationType.AUTO)
            private Integer id
    
           }
    

    因为@OneToOne 试图与一个实体进行映射,这意味着数据库中的一个表。对于 id,数据库中没有任何实体或表。这就是它抱怨的原因

    【讨论】:

    • 我认为这是有道理的,但我怎样才能表明用户地址属性应该获取地址 ID?我试图删除映射的部分并从地址中删除 OneToOne,但现在它返回以下错误:org.h2.jdbc.JdbcSQLIntegrityConstraintViolationException:参照完整性约束违规:“FKMXNOON0IKGA83W1A203Y6OFPN:PUBLIC.ENDERECO FOREIGN KEY(ID) REFERENCES PUBLIC.USUARIO (ID) (1)"; SQL 语句:插入 endereco (bairro, cep, cidade, Complemento, logradouro, numero_logradouro, uf, id) 值 (?, ?, ?, ?, ?, ?, ?, ?) [23506-200]
    • 你有存储在文件中的 h2 数据库吗?
    • 我正在使用 h2 控制台,但我没有将其保存到本地文件
    • @BeatrizBarbosa 检查我更新的答案。如果你只有一侧OneToOne那么你还需要@MapsId
    • 它返回 NULL 不允许列“ENDERECO_ID”; SQL 语句:insert into endereco (bairro, cep, cidade, Complemento, logradouro, numero_logradouro, uf, id) values (?, ?, ?, ?, ?, ?, ?, ?) [23502-200] 好像我发了一个空帖子
    猜你喜欢
    • 2012-07-30
    • 1970-01-01
    • 2019-01-27
    • 1970-01-01
    • 2011-02-13
    • 2017-11-13
    • 2012-10-14
    • 2011-02-25
    • 2014-12-27
    相关资源
    最近更新 更多