gpt4 book ai didi

java - Hibernate @OneToOne 和 ConstraintViolationException 关系的一侧

转载 作者:太空宇宙 更新时间:2023-11-04 10:23:11 25 4
gpt4 key购买 nike

我只是在实体字段上测试 hibernate @OneToOne 关系和验证。这是我的一方面关系:

@Table(name = "devices")
@Entity
public class Device extends BaseEntity {

@ManyToOne
@JoinColumn(name = "device_type_id")
private DeviceTypeEntity deviceType;

@NotBlank
private String name;

@NotBlank
private String serial;

@OneToOne(mappedBy = "device",cascade = CascadeType.ALL, fetch=FetchType.EAGER)
@NotNull
private Connection connection;

@OneToMany(cascade = CascadeType.ALL,fetch=FetchType.LAZY)
@JoinColumn(name="device_id")
private List<DeviceStatus> deviceStatuses = new ArrayList<DeviceStatus>();

// getters and setters

}

关系的另一面

@Table(name = "connections")
@Entity
public class Connection extends BaseEntity {

private static final long serialVersionUID = 1L;

@Column(name="connection_id", nullable = false)
@NotBlank
private String connectionId;

private String hostname;

@NotBlank
private String ip;

@Column(name="remote_port",nullable = false)
private Integer remotePort;

@Column(name="connection_time",nullable = false)
@Type(type = "com.app.hos.persistance.custom.DateTimeUserType")
private DateTime connectionTime;

@Column(name="end_connection_time")
@Type(type = "com.app.hos.persistance.custom.DateTimeUserType")
private DateTime endConnectionTime;

@JsonIgnore
@OneToOne(fetch=FetchType.EAGER)
@JoinColumn(name="device_id")
@NotNull
private Device device;


// setters and getters
}

如果我将 Connection 类中的“connectionId”字段设置为 null 并使用该“Connection”保存“Device”对象,即

  connection.setDevice(device);
device.setConnection(connection);
deviceRepository.save(device);

我期待 ConstraintViolationException,这对我来说没问题。但我注意到数据库中插入了一个设备实体。为什么?我希望如果发生异常,事务将回滚,并且数据库中根本没有实体(没有连接,也没有设备插入数据库)。

最佳答案

尽管其他答案中的建议从应用程序的角度解决了问题,但我相信这里存在一个更大的问题。当您在应用程序级别定义约束时,您这样做主要是因为您希望尽快检测到问题和违规行为。在本例中,您希望在应用程序级别检测 not null 约束。但事实是,当未检查此约束时,您的应用程序会在不应该写入数据的情况下将数据写入数据库,这意味着您缺少数据库级别的约束。这很重要,应该优先处理。

关于java - Hibernate @OneToOne 和 ConstraintViolationException 关系的一侧,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50862058/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com