在使用Spring Boot API向manyToOne关系发送寄存器时出错



我在我的实体中使用@oneToMany - @manyToOne关系,但是一旦我需要保存注册到@manyToOne侧实体,我得到一个500 http代码错误。我一直在寻找没有结果的错误,因为我认为一切都是好的代码。

我的POST请求"Factura"

{
"monto": 1002,
"persona":
{
"id": 1,
"nombre": "Test",
"apellidoPaterno": "Testing",
"apellidoMaterno": "Testing",
"identificacion": "abc"
}
}

响应码:

{
"timestamp": "2022-06-20T18:46:44.318+00:00",
"status": 500,
"error": "Internal Server Error",
"path": "/factura"
}

和VSC控制台的错误。

nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: 
detached entity passed to persist: com.test.gt.clientefactura.models.Persona;

父实体(@oneToMany - Persona)。

@Entity
@Table(name = "persona")
public class Persona {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true, nullable = false, name = "persona_id")
private Long id;

@Column(nullable = false)
private String nombre;    
@Column(nullable = false)
private String apellidoPaterno;    

private String apellidoMaterno;    
@Column(unique = true, nullable = false)
private String identificacion;
@OneToMany(
fetch = FetchType.LAZY,
mappedBy = "fkPersonaId",
cascade = CascadeType.ALL,
orphanRemoval = true
)
private Set<Factura> facturas = new HashSet<>();
. . .
getters and setters

子实体(@manyToOne - Factura)。

@Entity
@Table(name = "factura")
public class Factura {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(unique = true, nullable = false)
private Long id;
@CreationTimestamp
@Temporal(TemporalType.TIMESTAMP)
private Date fecha;
private float monto;
@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name = "fkPersonaId", referencedColumnName = "persona_id")
private Persona fkPersonaId;
. . .
getters and setters

存储库:

@Repository
public interface PersonaRepository extends CrudRepository<Persona, Long>{
public Optional<Persona> findByIdentificacion(String identificacion);
public long deleteByIdentificacion(String identificacion);
}
@Repository
public interface FacturaRepository extends CrudRepository<Factura, Long>{
public abstract ArrayList<Factura> findAllByFkPersonaId(Long personaId);
}

抛出错误(Factura)的实体的服务类。

@Service
public class Ventas {
@Autowired
FacturaRepository facturaRepository;
public ArrayList<Factura> listFacturas() {
return (ArrayList<Factura>) facturaRepository.findAll();
}
@Transactional
public Factura storeFactura(Factura factura) {
return facturaRepository.save(factura);
}
. . .

控制器代码:

@RestController 
@RequestMapping("/factura")
public class FacturaRestService {
@Autowired
private Ventas facturaService;
@GetMapping
public ArrayList<Factura> findFacturas() {
return facturaService.listFacturas();
}
@PostMapping
public Factura addFactura(@RequestBody Factura factura) {
return facturaService.storeFactura(factura);
}
. . .

如何按我想要的方式保存寄存器?我很感激你的帮助。

如果使用hibernate,可以使用merge而不是save。但如果没有这个选项,下面的链接可能会帮助你

PersistentObjectException: JPA和Hibernate抛出的传递给持久化的分离实体

PS:我可以在你的问题下面添加评论,因为声誉点,所以把它作为答案发布

相关内容

  • 没有找到相关文章

最新更新