我有两个类Software,Tag - 它们与ManyToMany有关。 我们无法在不添加标签的情况下创建软件。
我想写一个测试,检查:
@Test
public void createSoftwareWithNullTags() {
List<Tag> tags = null;
Software software = new Software("software1", "description1", tags);
try {
software.save();
fail("tags should not be null");
} catch (Exception ex) {
// NEVER COME HERE !!!
}
}
List<Tag> tags = null;
Software software = new Software("software1", "description1", tags);
try {
software.save();
fail("tags should not be null");
} catch (Exception ex) {
// NEVER COME HERE !!!
}
}
所以,这个测试失败了。我想这不是一个好的测试 - 因为它甚至不会尝试将数据保存到SOFTWARE_TAG表。当然我可以手动进行验证,但我想用hibernate实现它,使用一些注释或其他东西。可能吗?或者你会怎么做?
我的实体:
@Entity
public class Tag extends Model {
public String title;
public Tag(String title) {
this.title = title;
}
@ManyToMany(
cascade = {CascadeType.ALL},
mappedBy = "tags",
targetEntity = Software.class
)
public List<Software> softwares;
public String title;
public Tag(String title) {
this.title = title;
}
@ManyToMany(
cascade = {CascadeType.ALL},
mappedBy = "tags",
targetEntity = Software.class
)
public List<Software> softwares;
}
答案 0 :(得分:2)
你不能用“普通”的Hibernate来做。您需要使用Hibernate Validator,它是“Bean Validation”JSR的实现。在这种特定情况下,您使用@Size
注释,其min
属性为,例如,1。
编辑:我真的认为如果你不希望参数为null,你应该考虑抛出NullPointerException。在我看来,您应该只使用Bean验证 来防止“用户”错误。为了防止编程错误(如无法接受的null),你应该坚持例外: - )
答案 1 :(得分:1)
M:N在Hibernate中有点“棘手”,并不适合你的场景。我建议:
如果保留当前的M:N,请记住更改级联属性。我现在说,如果你删除一个软件实体,你将删除所有相关的标签(可以被其他软件实体使用)并导致混乱。