Pregunta

Tengo dos entidades dentro de una relación

tag <-m:n-> software

Y quiero eliminar todos los softwares que ya no son enlaces a etiquetas después de eliminar la etiqueta particular. Escribo la consulta HQL para eso.

Yo uso PlayFramework

mi etiqueta anulada.delete ()

@Override
public Tag delete() {

    Tag t = null;

    // t = super.delete();   // commented for now

    // it should delete ONLY that softwares which are not linked with tags (tags is empty)
    Query q = Tag.em().createQuery("delete from Software s where s.tags is empty ");
    q.executeUpdate();

    return t;
}

mi prueba:

@Test
public void testDelete() throws InterruptedException {

    Tag tag1 = new Tag("tag1").save();
    Tag tag2 = new Tag("tag2").save();

    Author author1 = new Author("name", "email").save();

    Software s1 = new Software("soft1", "description1", author1, tag1).save(); // this should be deleted when tag1 is deleting

    Software s2 = new Software("soft2", "description2", author1, tag1, tag2).save(); // this should be deleted, because it links to tag2

    // checks, just in case: 
    Software ss = Software.findById(s1.id);
    assertTrue(ss.isPersistent());
    assertTrue(!ss.tags.isEmpty());
    assertEquals(1, ss.tags.size());

    tag1.delete();

    // try to find the software
    assertEquals(1, Software.findAll().size()); // here it faults, it deletes all!!!
}    

Ahora tengo el problema de que elimina todos los softwares, incluso si tienen enlaces a la etiqueta.

Pero obtengo SQL que se forma desde HQL es como:

delete from Software where not (exists (select tag.id from Tag_Software ts, Tag tag where Software.id=ts.softwares_id and ts.tags_id=tag.id))

Y es un buen SQL (lo revisé), pero ¿por qué todo esto no funciona como HQL en mi contexto ...?

Mi prueba dice:

Fracaso, esperado: <1> pero fue: <0>

El código para dos clases son:

public class Tag extends Model {

    @Column(nullable = false, unique = true)
    public String title;

    public Tag(String title) {
        this.title = title;
    }

    @ManyToMany
    public List<Software> softwares = new LinkedList<Software>();

....

@Entity
public class Software extends Model {

    public String title;
    public String description;

    @ManyToOne(optional = false)
    public Author author;

    @ManyToMany(mappedBy = "softwares")
    public List<Tag> tags = new LinkedList<Tag>();

...

¿Fue útil?

Solución

Hay formas múltiples:

`Softwares.size = 0

tamaño (softwares) = 0 `

Puedes leer esto para aprender más sobre ellos:

http://docs.jboss.org/hibernate/core/3.3/reference/en/html/queryhql.html#queryhql-expressions

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top