猿问

如何设置 Spring 模型以支持复杂对象的 Angular 编辑组件?

我正在用 Spring 和 Angular 编写我的第一个 Web 应用程序。我使用 PHP 大约 10 年,然后在过去的 10 年中发现并使用 Rails,并且做了几个 ASP 项目来启动,所以我对 Web 开发并不陌生,总的来说。我正在尝试创建我的第一个完整的 CRUD 操作集,但是我找不到有关如何为“复杂”对象(带有父对象和/或子对象)创建编辑表单的文档。官方的 Angular 指南仅止于此,我在互联网上的任何地方都找不到一个完整的教程。在我的示例中,我想要一个“产品”的编辑组件,我可以在其中更改当前选择的“引擎”。


在 Spring 中,我为两个初始模型配置了类、存储库和控制器,如下所示:


引擎(父)-> 产品(子)


Product.java:


package com.xyz.cddm_ng;

import lombok.*;

import org.hibernate.annotations.CreationTimestamp;

import org.hibernate.annotations.UpdateTimestamp;

import javax.persistence.*;

import java.time.LocalDateTime;

import static javax.persistence.GenerationType.IDENTITY;


@Entity

@Getter @Setter

@NoArgsConstructor

@ToString @EqualsAndHashCode

@JsonIdentityInfo(generator = ObjectIdGenerators.PropertyGenerator.class, property = "id")

public class Product {

    @Id

    @GeneratedValue(strategy=IDENTITY)

    Long id;


    @NonNull String title;


    String note;


    @CreationTimestamp

    LocalDateTime createDateTime;


    @UpdateTimestamp

    LocalDateTime updateDateTime;


    @ManyToOne(fetch = FetchType.LAZY)

    @JoinColumn(name = "engine_id")

    @JsonManagedReference

    Engine engine;

}

Engine.java (片段):


@OneToMany(fetch = FetchType.LAZY, mappedBy = "engine")

@JsonBackReference

Collection<Product> products;

控制器和存储库刚刚被淘汰。


ProductController.java:


package com.xyz.cddm_ng;


import org.springframework.web.bind.annotation.*;


@RestController

@RequestMapping("products")

@CrossOrigin(origins = "http://localhost:4200")

class ProductController { }

ProductRepository.java:


package com.xyz.cddm_ng;


import org.springframework.data.jpa.repository.JpaRepository;

import org.springframework.data.rest.core.annotation.RepositoryRestResource;

import org.springframework.web.bind.annotation.CrossOrigin;


@RepositoryRestResource

@CrossOrigin(origins = "http://localhost:4200")

interface ProductRepository extends JpaRepository<Product, Long> { }


一只斗牛犬
浏览 165回答 1
1回答

湖上湖

所以我在 Reddit 上讨论过这个问题,人们让我远离使用 Spring REST 的想法。我被指向https://github.com/spring-projects/spring-petclinic,根据其自述文件,它是 Spring 中各种项目的长期示例。在我迄今为止的所有阅读中,我从未偶然发现这一点。从pom.xml那个项目中,我看到 Spring Data JPA 和 Spring Web 的组合提供了 REST 服务——完全独立——这就是我认为我需要 Spring REST 的原因。(我似乎仍然需要 Jackson@JsonIdentityInfo注释来防止我的双向一对多关系中出现堆栈溢出递归循环,但我似乎不需要反向或托管引用注释。)从组件和弹簧的PetClinic棱角前端子项目的形式,我还可以,最后,请参阅我不必须手动设置在下拉规定的,相关联的对象实例选择(QV,https://开头的github .com/spring-petclinic/spring-petclinic-angular/blob/master/src/app/pets/pet-edit/pet-edit.component.html),然后使用服务中的父对象“重新组装”该选择在将其发送到后端的更新功能之前。这是我习惯于 Rails 为我处理的事情,我还没有看到 Angular 是否也会以某种方式为我做这件事的例子。答案似乎是,“不”。
随时随地看视频慕课网APP

相关分类

Java
我要回答