[英]Hibernate: how can I delete an entity in the one-to-many relationship in the “many” side from the “one” side
[英]How can I create a one-to-many relationship with Spring and thymeleaf?
我想創建一個具有多個“標簽”作為集合的“產品”class。 所以一個一對多的數據庫,而產品是“一”,標簽是“多”。
標簽將在 HTML 中定義為輸入字段並按空格分隔。 例如“tag1 tag2 tag3”。
我現在的問題是:如何從輸入字段和 append 檢索字符串作為我的產品 object 的集合?
到目前為止我所擁有的:
產品
@Entity
public class Product {
@Id
@GeneratedValue
private int barcode;
public String name;
@OneToMany(mappedBy = "product", cascade = CascadeType.ALL)
private Collection<Tag> tags;
...Getter & Setter
標簽
@Entity
public class Tag {
@Id
private String tagname;
@ManyToOne(fetch = FetchType.LAZY, optional = false)
@JoinColumn(name = "barcode", nullable = false)
private Product product;
...Getter & Setter
ProductsController:我嘗試添加 Tag 對象作為測試,但會引發 Tag 表不存在的錯誤
@PostMapping("/add")
public String add(@Valid Product product, BindingResult result, Model model) {
model.addAttribute("responseMessage", result);
if(!result.hasErrors()) {
//I tried to add a static collection to the product object, but it throws errors
Collection<Tag> col = new ArrayList<>();
col.add(new Tag("test"));
col.add(new Tag("test2"));
product.setTags(col);
productRepository.save(product);
}
model.addAttribute("products",productRepository.findAll());
return "products-add";
}
因為你有用空格分隔的標簽。 首先,您需要使用正則表達式制作一個標簽字符串數組,如下所示。
String tags = "tag1 tag2 tag3";
String[] tagArr = tags.split("\\s+");
現在您需要創建一個存儲庫,如下所示。
@Repository
public interface TagRepository extends JpaRepository<Tag, Long> {
Tag findByTagname(String tagname);
}
為 TagService 創建一個接口。
public interface TagService {
Tag findByTagname(String tagname);
}
創建 TagService class 的實現
@Service
public class TagServiceImpl implements TagService{
@Autowired
private TagRepository tagRepository;
@Override
public Tag findByTagname(String tagname) {
return tagRepository.findByTagname(tagname);
}
}
現在按名稱獲取標簽已完成。 將您的 TagService 自動連接到您的 controller class
@Autowire
private TagService tagService;
將以下代碼添加到您的 controller。
String tags = "tag1 tag2 tag3";
String[] tagArr = tags.split("\\s+");
List<Tag> tagList = new ArrayList<Tag>();
for (String tagname : tagArr) {
Tag tag = tagService.findbyTagname(tagname);
tagList.add(tag);
}
現在,當您保存產品 class 時。 將此標簽列表設置到您的它中。
可能您是第一次運行它,並且您的數據庫沒有名為 Tag 的表。 請確保 hibernate 屬性 hibernate.hbm2ddl.auto 設置為“更新”,這將在執行任何數據插入之前首先自動創建所需的表。
而要轉換由空格分隔的字符串值標簽,只需使用 string.split() 方法,它會為您提供數組,然后將其轉換為要在產品 object 中設置的列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.