开发者

many to many and integrity when saving the null

I have two classes Software, Tag - they are related by ManyToMany. We CAN NOT create Software without putting the Tag to it.

I want to write a test which check that:

@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  !!!
    }

}

So, this test fails. I guess it is not good test for that case - because it even do not try to SAVE data to SOFTWARE_TAG table. Of course i could do validation manually but i want implement it with hibernate, using some annotation or something. Is it possible? Or how would you do this?

My entities:

@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;

}

@Entity public class Software extends Model {

public String title;
public String description;

@ManyToOne(optional = false)
public Author author;


@ManyToMany(cascade = CascadeType.ALL)
@JoinTable(

        name = "SOFTWARE_TAG",
        joinColumns = @JoinColumn(name = "Software_id"),
        inverseJoinColumns = @JoinColumn(name = "Tag_id")

)
public List<Tag> tags;

public Software(String title, String description, Author author, List<Tag> tags) {
    this.title = title;
    this.description = description;
    this.author = author;
    this.tags = tags;
开发者_运维知识库}

}


You can't do it with "plain" Hibernate. You'd need to use Hibernate Validator, which is an implementation of "Bean Validation" JSR. In this specific case, you'd use a @Size annotation, with a min property of, say, 1.

http://docs.jboss.org/hibernate/validator/4.2/reference/en-US/html_single/#validator-defineconstraints-builtin

Edit: I really think you should consider throwing a NullPointerException if you don't expect a parameter to be null. In my opinion, you should use Bean Validation only to prevent "user" errors. To prevent from programming mistakes (like a null where it's not acceptable), you should stick to exceptions :-)


M:N in Hibernate are a bit "tricky", and not well suited for your scenario. I would recommend to:

  • Convert the M:N relation into two rels 1:M. Software - middle class - Tag. That way you can add a @Required to software side and work with simpler 1:M rels.
  • Add some user validation for this

If you keep the current M:N, remember to change your cascade attribute. I would say that right now if you remove a Software entity, you will remove all its related tags (which could be used by other Software entities) and cause a mess.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜