当使用CreateItem方法与地点,地点创建即使在所有列有相同的值

问题描述 投票:0回答:1

我使用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();
    }

我希望以后重新编码的应用程序不做出新的位置,如果列值是相同的。

谢谢大家!如果你真的帮助我,我会很高兴!

java spring rest crud
1个回答
0
投票

有没有在你的实体定义来告诉你想要的约束的ORM。

您可以在@UniqueConstraint实体添加@TableLocation并指定列(S)都必须在一个独特的组合(例如链接的文档中给出):

@Table(
        name="EMPLOYEE", 
        uniqueConstraints=
            @UniqueConstraint(columnNames={"EMP_ID", "EMP_NAME"})
    )

这将在数​​据库中添加一个检查,如果被ORM管理数据库架构,违反时会抛出异常。

© www.soinside.com 2019 - 2024. All rights reserved.