简体   繁体   English

Spring Boot中没有外键的REST API返回项

[英]Rest api return item without foreign key in Spring Boot

enter image description here 在此处输入图片说明

I created rest api with Spring-boot that return all data from database(MySql). 我用Spring-boot创建了REST API,该API从数据库(MySql)返回所有数据。 In sql many to one relationship Category-Item 在sql中多对一关系Category-Item

In controller i want to get all item with foreign key 在控制器中,我想使用外键获取所有项目

Entities 实体

@Entity
@Table(name = "categories")
public class Category implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String category_name;


    @OneToMany(cascade = CascadeType.ALL)
    private Set<Maqal> maqals;

    public Category() {

    }

    public Category(String category_name) {
        this.category_name = category_name;
    }
}
@Entity
@Table(name = "maqals")
public class Maqal implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private int id;
    private String context;

    @ManyToOne(optional = false)
    @JoinColumn(name = "category_id", unique = true)
    private Category category;


    public Maqal() {
    }

    public Maqal(String context) {
        this.context = context;
    }
}

Controller 控制者

    @RequestMapping("/allData")
    public Iterable<Maqal> getAllData() {
        return maqalsDao.findAll();
    }

But /allData return without foreign key. 但是/ allData返回而没有外键。 How can I add proterties or values for foreign key in Maqals.class? 如何在Maqals.class中为外键添加属性或值?

假设您使用的是Spring Data,并且您的数据库与您的实体保持一致,请为两个实体类中的所有ID字段添加getter和setter以便显示和设置ID。

You cannot show the data which one using foreign key. 您无法使用外键显示哪个数据。 Suppose you need to show the values means to manually the data using the foreign key. 假设您需要显示值意味着使用外键手动数据。

Otherwise: You need to remove the @JoinColumn annotation. 否则:您需要删除@JoinColumn批注。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM