H2的Spring JPA:使用外键添加另一个实体

时间:2019-03-09 15:00:44

标签: java sql spring-data-jpa h2

我有两个实体 Article ArticleDescription

@Entity
public class Article {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int articleId;

    private String name;
    private String manufactor;
    private float price;

    @ManyToOne
    private ArticleDescription articleDescription;


@Entity
public class ArticleDescription {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int articleDescriptionId;

    private String text;
    private String author;

    // Joshua
    @ManyToOne
    private Article article;

我想要这样的东西:

[
 {
   "articleId": "5",
   "manufactor": "Test",
   "name": "Name",
   "price": "50",
   "ArticleDescription": {
     "articleDescriptionId": "5",
     "test": "Text",
     "author": "Author"
 }
]

我也有一个ArticleJpaRepository和ArticleController:

public interface ArticleJpaRepository extends JpaRepository<Article, Integer> {
    List<Article> findByName(String name);

    List<Article> findByManufactor(String manufactor);

    List<Article> findByPrice(float price);
}

@ComponentScan
@RestController
public class ArticleController {

    @Autowired
    private ArticleJpaRepository articleJpaRepository;

    @GetMapping("/articles")
    @ResponseBody
    public List<Article> getArticles() {

        return articleJpaRepository.findAll();
    }

    // Optional, falls kein Customer gefunden wird.
    @RequestMapping("/article/{articleId}")
    @ResponseBody
    public Optional<Article> getArticle(@PathVariable("articleId") int articleId) {

        return articleJpaRepository.findById(articleId);
    }

    // Client to Server
    // POST über z.B. Postman Client
    @PostMapping("/article")
    public Article addArticle(@RequestBody Article article) {

        articleJpaRepository.save(article);

        return article;
    }

    @DeleteMapping("/article/{articleId}")
    public String deleteArticle(@PathVariable int articleId) {

        Article a = articleJpaRepository.getOne(articleId);
        articleJpaRepository.delete(a);

        return "deleted";
    }

    @PutMapping("/customer")
    public Article updateArticle(@RequestBody Article article) {

        articleJpaRepository.save(article);

        return article;
    }

我希望在将articleDescriptionId添加到他们所连接的SQL中的Article时。但是我不知道我在哪里配置这种行为。当我要将article_description的外键添加到article时,出现错误。

"Referential integrity constraint violation: 

SQL语句:

INSERT INTO article (article_Id, manufactor, name, price, ARTICLE_DESCRIPTION_ARTICLE_DESCRIPTION_ID)
VALUES ('1000', 'koezocakbasi', 'Dürüm', '4.90', '1000'),
       ('1001', 'koezocakbasi', 'Döner', '4.50', '1001'),
       ('1002', 'koezocakbasi', 'DönerTeller', '10.90', '1002');

INSERT INTO article_description (article_Description_Id, author, text)
VALUES ('1000', 'koezocakbasi', 'Dürüm'),
       ('1001', 'koezocakbasi', 'Döner'),
       ('1002', 'koezocakbasi', 'DönerTeller');

0 个答案:

没有答案