我使用H2在内存数据库,我不希望创建我的数据库副本的位置。只有当我使用createItem和输入位置列ID manualy它把它写在相同的位置。否则,即使国家城市GPS坐标相同的应用程序写入到其他位置与它的ID。
我试图了解,但它不工作
我得到了这些实体。
@Entity
@Table(name = "item_System_items")
public class Item {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String title;
private String description;
private BigDecimal price;
private Integer stock;
@ManyToOne
@JoinColumn(name = "location_id")
@Cascade(value={org.hibernate.annotations.CascadeType.ALL})
private Location location;
和
@Entity
@Table(name = "item_System_locations")
public class Location {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String country;
private String city;
private String street;
private String gpsCoordinates;
getter和setter方法有我只是没有张贴在这里
调节器
@RestController
@RequestMapping("/items")
public class ItemsController {
@Autowired
private ItemsService service;
@PostMapping
@ResponseStatus(value=HttpStatus.CREATED)
public int createItem(@RequestBody Item item) {
return service.createItem(item);
}
服务
@Service
@Transactional
public class ItemsService {
@Autowired
private ItemJPARepository repository;
public int createItem(Item item) {
return repository.save(item).getId();
}
我希望以后重新编码的应用程序不做出新的位置,如果列值是相同的。
谢谢大家!如果你真的帮助我,我会很高兴!
有没有在你的实体定义来告诉你想要的约束的ORM。
您可以在@UniqueConstraint
实体添加@Table
到Location
并指定列(S)都必须在一个独特的组合(例如链接的文档中给出):
@Table(
name="EMPLOYEE",
uniqueConstraints=
@UniqueConstraint(columnNames={"EMP_ID", "EMP_NAME"})
)
这将在数据库中添加一个检查,如果被ORM管理数据库架构,违反时会抛出异常。