Miss Sunshine
Miss Sunshine

Reputation: 45

delete with entity manager nativequery doesnt do anything

Id like to allow user to delete one tag from expert entity in many to many relationship. Tags is an array list inside expert.

My model expert:

@Entity
@Table(name="experts")
public class Expert {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    private String name;
    private String surname;
    private String dni;
    private String address;
    private String mail;
    private String phone;
    private String linkedln;
    private String state;
    private String rating;
    private String availability;



    @ManyToMany(fetch = FetchType.EAGER, cascade = {CascadeType.PERSIST,CascadeType.REFRESH})
    @JoinTable(
            name = "experts_tags",
            joinColumns = {@JoinColumn(name="tags_id", referencedColumnName = "id")},
            inverseJoinColumns = {@JoinColumn(name="experts_id", referencedColumnName = "id")}
    )
    private List<Tag> tags = new ArrayList<>(); //constructor,getters and setters

My model tag:

@Entity
@Table(name="tags")
public class Tag {

    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;
    private String name;

    @ManyToMany(mappedBy="tags", cascade = {CascadeType.PERSIST})
    private List<Expert> experts = new ArrayList<>();

    public Tag() {
    }

    public Tag(String name, List<Expert> experts) {
        this.name = name;
        this.experts = experts;
    }  //getters and setters

Im trying to delete with entitity manager, using a native query that deletes tag by id from the common experts_tags column.

My tagDao method to delete:

public ResponseEntity<Void> deleteTagById(Long id) {
 
    if(id!=null){


        manager.createNativeQuery("delete from experts_tags e where tags_id="+id);
        manager.flush();


    }
    return ResponseEntity.noContent().build();

}

But this method doesnt do absolutly nothing. No error, but neither delete my tag. why this?? I dunno what is happening.

Appreciate any help!!! thanks in advance.

Upvotes: 0

Views: 728

Answers (1)

Davide D&#39;Alto
Davide D&#39;Alto

Reputation: 8236

executeUpdate() is missing:

manager
    .createNativeQuery(...)
    .executeUpdate();

You could also use a JPQL query and should also use parameters:

manager
    .createQuery("delete from Expert e where e.id = :id")
    .setParameter("id", id)
    .executeUpdate();

No need to flush.

Upvotes: 1

Related Questions