Spring JPA多表关系

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

我正在尝试创建一个包含Product - > Attributes - > Options的产品目录

所以数据看起来像这样:

product_one
  attribute_one
    option_one
    option_two
  attribute_two
    option_one
    option_two

该代码可在GitHub https://github.com/ccsalway/prod_info_mngr上找到

我为每个实体创建了一个类:

@Entity
class Product {
  @Id
  @Generatedvalue
  private Long id;
  private String name;

  // getters and setters
}

@Entity
class Attribute {
  @Id
  @Generatedvalue
  private Long id;
  private String name;
  @ManyToOne(cascade = CascadeType.REMOVE)
  private Product product;

  // getters and setters
}

@Entity
class Option {
  @Id
  @Generatedvalue
  private Long id;
  private String name;
  @ManyToOne(cascade = CascadeType.REMOVE)
  private Attribute attribute;

  // getters and setters
}

我为每个实体创建了一个Repository:

@Repository
public interface ProductRepository extends PagingAndSortingRepository<Product, Long> {
}

@Repository
public interface AttributeRepository extends PagingAndSortingRepository<Attribute, Long> {
}

@Repository
public interface OptionRepository extends PagingAndSortingRepository<Option, Long> {
}

我为每个实体创建了一个服务:

@Service
public class ProductService {

    // Autowired Repositories

    // methods
}

@Service
public class AttributeService {

    // Autowired Repositories

    // methods
}

@Service
public class OptionService {

    // Autowired Repositories

    // methods
}

我为每个实体创建了一个Controller:

@Controller
@RequestMapping("/product")
public class ProductController {

    @Autowired
    private ProductService productService;

    //methods
}

@Controller
@RequestMapping("/product/{prod_id}/attribute")
public class AttributeController{

    @Autowired
    private AttributeService attributeService;

    //methods
}

@Controller
@RequestMapping("/product/{prod_id}/attribute/{attr_id}")
public class OptionController {

    @Autowired
    private OptionService optionService;

    //methods
}

并且(最后)我为每个Controller创建了几个视图(我不会在这里添加它们)。

我在product_view.jsp View中尝试做的是显示属性列表及其相关选项,如下所示:

<table id="attrTable">
    <thead>
    <tr>
        <th>Name</th>
        <th>Options</th>
    </tr>
    </thead>
    <tbody>
    <c:forEach items="${attributes}" var="attr">
        <tr data-id="${attr.id}">
            <td>${fn:htmlEscape(attr.name)}</td>
            <td><c:forEach items="${attr.options}" var="opt" varStatus="loop">
                ${opt.name}<c:if test="${!loop.last}">,</c:if>
            </c:forEach></td>
        </tr>
    </c:forEach>
    </tbody>
</table>

所以表格看起来像这样

product_one
  attribute_one    option_one, option_two
  attribute_two    option_one, option_two

第一步是在@RequestMapping创建一个ProductController

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String view(Model model, @PathVariable Long id) {
    Product product = productService.getProduct(id);
    List<Attribute> attributes = productService.getAttributes(product);
    model.addAttribute("product", product);
    model.addAttribute("attributes", attributes);
    return "products/product_view";
}

但是视图中的${attr.options}不承认options键,所以我该如何进行这项工作呢?

我试图在@OneToMany实体中添加一个Product关联,但是这在product_id|attribute_id数据库中创建了一个表,然后你必须保存该属性,然后使用new属性更新产品,这也意味着当你选择一个产品时,你正在拉动所有属性和所有选项,以防止对这些属性进行分页。

@Entity
class Product {
  @Id
  @Generatedvalue
  private Long id;
  private String name;

  @OneToMany
  List<Attribute> attributes;

 // getters and setters
}
java spring jpa spring-data-jpa
1个回答
0
投票

我找到了解决方案:

我添加了OneToManyManyToOne关系如下。此方法还允许repository.delete(id)方法级联删除。

FetchType.LAZY告诉Spring仅在请求时获取基础项。例如,当发出Product的请求时,将获取idname,但因为attributes@OneToMany,默认情况下是LAZY,所以attributes将不会从DB获取,直到特定调用product.getAttributes()是。

@Entity
public class Product {

    @Id
    @GeneratedValue
    private Long id;
    private String name;

    // OneToMany is, by default, a LAZY fetch
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "product")
    private Set<Attribute> attributes = new HashSet<>();

    // getters and setters
}

@Entity
public class Attribute {

    @Id
    @GeneratedValue
    private Long id;
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "product_id", nullable = false)
    private Product product;

    // OneToMany is, by default, a LAZY fetch
    @OneToMany(cascade = CascadeType.ALL, mappedBy = "attribute")
    private Set<Option> options = new HashSet<>();

    // getters and setters
}

@Entity
public class Option {

    @Id
    @GeneratedValue
    private Long id;

    @NotEmpty
    @Size(min = 1, max = 32)
    private String name;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "attribute_id", nullable = false)
    private Attribute attribute;

    // getters and setters
}

ProductController中,我将AttributesProduct分开,以便我可以在属性上使用Paging(而如果我只是调用product.getAttributes(),它将获取所有属性)

@RequestMapping(value = "/{id}", method = RequestMethod.GET)
public String view(Model model, @PathVariable Long id, @RequestParam(name = "page", defaultValue = "0") int page) throws ProductNotFoundException {
    Product product = productService.getProduct(id);
    model.addAttribute("product", product);
    // requesting attributes separately (as opposed to using LAZY) allows you to use paging
    Page<Attribute> attributes = productService.getAttributes(product, new PageRequest(page, 10));
    model.addAttribute("attributes", attributes);
    return "products/product_view";
}

然后在视图中,我记得如上所述循环attributes而不是product.attributes

因为options属性在LAZY实体中被设置为Attribute,所以当循环调用attr.options时,Spring将向DB请求当前OptionsAttribute

<table id="attrTable" class="table is-hoverable is-striped is-fullwidth" style="cursor:pointer;">
    <thead>
    <tr>
        <th>Name</th>
        <th>Options</th>
    </tr>
    </thead>
    <tbody>
    <c:forEach items="${attributes}" var="attr">
        <tr data-id="${attr.id}">
            <td>${fn:htmlEscape(attr.name)}</td>
            <td>
                <c:forEach items="${attr.options}" var="opt" varStatus="loop">
                    ${opt.name}<c:if test="${!loop.last}">,</c:if>
                </c:forEach>
            </td>
        </tr>
    </c:forEach>
    </tbody>
</table>
© www.soinside.com 2019 - 2024. All rights reserved.