0

I have a junction table of user_id and favorite_property_id And now I want to delete the favorite property of the user , I tried the following method in repository but its not working , Does anybody have any idea that how can i delete he entry from junction table?

User.java

@Entity
    public class User implements Serializable, UserGetters {
        private static final long serialVersionUID = 1L;

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

        @ManyToMany(fetch = FetchType.EAGER)
        private Set<Property> favouriteProperty;

    public Set<Property> getFavouriteProperty() {
            return favouriteProperty;
        }

        public void setFavouriteProperty(Set<Property> favouriteProperty) {
            this.favouriteProperty = favouriteProperty;
        }
        }

UserRepository

public interface UserRepository  extends JpaRepository<User, Long> {
//@Transactional
     // Long deleteByFavouritePropertyId(@Param("favoriteProperty") Long favoriteProperty);

    // @Query("delete favouriteProperty from user u where u.favouriteProperty.id=:favouriteProperty")
    // void unmarkFavouriteProperty(@Param("favouriteProperty")  Long favouriteProperty);

}
SFAH
  • 624
  • 15
  • 35
  • Unexpected Token : from near line 1, column 26 [delete favouriteProperty from user u where u.favouriteProperty.id=:favouriteProperty] @Afridi – SFAH May 29 '17 at 06:37

3 Answers3

2

You can do it like:

1. Load user object

User user = userRepository.findOne(userId);

2. Remove required object from list

user.getFavouriteProperty().remove(id);

3. Save User Object

userRepository.save(user);
Afridi
  • 6,753
  • 2
  • 18
  • 27
1

Try using :

Query query = session.createQuery("delete Category where id = :favorite_property_id ");
query.setParameter("favorite_property_id ", new Long(favoriteProperty));
int result = query.executeUpdate();

in your repository file. It will work fine.

Sahil Gupta
  • 73
  • 1
  • 3
  • 12
0

This was so simple :P

I can delete by using following API

API : http://localhost:8555/api/users/2/favouriteProperty/3

METHOD : DELETE

SFAH
  • 624
  • 15
  • 35