我想创建一个“产品”类,它有多个“标签”作为一个集合。所以一个一对多的数据库,而 Product 是“一个”而 Tags 是“多个”。
标签将在 HTML 中定义为输入字段并以空格分隔。例如“tag1 tag2 tag3”。
我现在的问题是:如何从输入字段中检索字符串并将它们作为集合附加到我的产品对象?
我目前拥有的:
产品
@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 创建接口(interface)。
public interface TagService {
Tag findByTagname(String tagname);
}
创建 TagService 类的实现
@Service
public class TagServiceImpl implements TagService{
@Autowired
private TagRepository tagRepository;
@Override
public Tag findByTagname(String tagname) {
return tagRepository.findByTagname(tagname);
}
}
现在通过名称获取标签已经完成。将您的 TagService Autowiring 到您的 Controller 类中
@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);
}
现在当您保存您的产品类别时。将此标签列表设置到您的列表中。
关于java - 我如何创建与 Spring 和 thymeleaf 的一对多关系?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58154155/