#I can't delete the photo from database, I can't figure out why.

48 messages · Page 1 of 1 (latest)

limpid pineBOT
#

This post has been reserved for your question.

Hey @zealous bolt! Please use /close or the Close Post button above when your problem is solved. Please remember to follow the help guidelines. This post will be automatically marked as dormant after 300 minutes of inactivity.

TIP: Narrow down your issue to simple and precise questions to maximize the chance that others will reply in here.

zealous bolt
#
package com.logan.restapi.models;

import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.logan.restapi.listeners.UserModelListener;
import com.logan.restapi.roles.UserRoles;
import jakarta.persistence.*;

import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.util.Date;
import java.util.Set;

@Getter
@Setter
@Entity
@Table(name = "users")
@EntityListeners(UserModelListener.class)
public class UserModel {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String username;

    @Column(nullable = false)
    private String password;

    @ElementCollection(targetClass = UserRoles.class, fetch = FetchType.EAGER)
    @CollectionTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id"))
    @Enumerated(EnumType.STRING)
    private Set<UserRoles> roles;

    @CreationTimestamp
    @Column(nullable = false, updatable = false)
    private Date createdAt;

    @UpdateTimestamp
    @Column(nullable = false)
    private Date updatedAt;

    @OneToOne(mappedBy = "user", cascade = CascadeType.ALL, orphanRemoval = true, targetEntity = PhotoModel.class)
    @JsonManagedReference
    private PhotoModel photo;
}
#
package com.logan.restapi.models;

import com.fasterxml.jackson.annotation.JsonBackReference;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.util.Date;

@Getter
@Setter
@Entity
@Table(name = "photos")
public class PhotoModel {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String filename;

    @Column(nullable = false)
    private String url;

    @CreationTimestamp
    @Column(nullable = false, updatable = false)
    private Date createdAt;

    @UpdateTimestamp
    @Column(nullable = false)
    private Date updatedAt;

    @OneToOne
    @JoinColumn(name = "user_id", referencedColumnName = "id")
    @JsonBackReference
    private UserModel user;
}
#

Method that deletes

    @Override
    public Object deletePhoto(UserFromRequest user) {
        UserModel userModel = getUserModel(user);

        PhotoModel photo = photosRepository.findByUser(userModel).orElse(null);

        System.out.println("photo: " + photo);
        if(photo != null) {
            System.out.println("PhotoId: " + photo.getId());
            System.out.println("PhotoFilename: " + photo.getFilename());
            System.out.println("PhotoUrl: " + photo.getUrl());
            System.out.println("PhotoUser: " + photo.getUser());
        }

        if (photo == null) {
            Map<String, String> response = new HashMap<>();
            response.put(ERROR, "Photo not found");
            return response;
        }

        Map<String, Object> response = new HashMap<>();

        try {
            Path photoPath = Paths.get(UPLOAD_DIR + photo.getFilename());
            Files.deleteIfExists(photoPath);

            photosRepository.delete(photo);

            response.put(PHOTO, photo);

            response.put("message", "Photo deleted successfully.");

            return response;
        } catch (Exception e) {
            logger.severe(e.getMessage());
            response.put(ERROR, "Failed to delete photo.");
            return response;
        }
    }
brittle mason
#

ur not deleting the table you are deleting just one entity

#

is your method transactional

#

and you should first delete from database then from the drive itself

zealous bolt
#

I can't delete the photo from database, I can't figure out why.

#

So, how do I fix ? Can you show an example ? I'm begginer in spring

brittle mason
#

add the transactional annotation to the method and swap the lines where you delete from db and from the drive

#

so you first delete from the repository and then from the drive

zealous bolt
# brittle mason so you first delete from the repository and then from the drive
    @Override
    @Transactional
    public Object deletePhoto(UserFromRequest user) {
        UserModel userModel = getUserModel(user);

        PhotoModel photo = photosRepository.findByUser(userModel).orElse(null);

        System.out.println("photo: " + photo);
        if(photo != null) {
            System.out.println("PhotoId: " + photo.getId());
            System.out.println("PhotoFilename: " + photo.getFilename());
            System.out.println("PhotoUrl: " + photo.getUrl());
            System.out.println("PhotoUser: " + photo.getUser());
        }

        if (photo == null) {
            Map<String, String> response = new HashMap<>();
            response.put(ERROR, "Photo not found");
            return response;
        }

        Map<String, Object> response = new HashMap<>();

        try {
            photosRepository.delete(photo);

            Path photoPath = Paths.get(UPLOAD_DIR + photo.getFilename());
            Files.deleteIfExists(photoPath);

            response.put(PHOTO, photo);

            response.put("message", "Photo deleted successfully.");

            return response;
        } catch (Exception e) {
            logger.severe(e.getMessage());
            response.put(ERROR, "Failed to delete photo.");
            return response;
        }
    }
#

like that ?

#

Still not work

brittle mason
#

does it not get deleted from the database

#

or does it return that the photo exists even when its deleted

#

check it

limpid pineBOT
#

💤 Post marked as dormant

This post has been inactive for over 300 minutes, thus, it has been archived.
If your question was not answered yet, feel free to re-open this post or create a new one.
In case your post is not getting any attention, you can try to use /help ping.
Warning: abusing this will result in moderative actions taken against you.

zealous bolt
brittle mason
#

or

#

what kind of database are you using

#

or you could also try to do something like this

#
userModel.setPhoto(null);
#

after deleting the photo from the repository

#

check if that helps in any way

#

also see if you dont get any database errors when the repository delete is called

zealous bolt
zealous bolt
zealous bolt
#

I discovered what the problem was, I was relating the tables in the wrong order, I was relating photo as the parent and user as the child, which is incorrect because when I deleted the parent, I would delete the child OR I would not be able to delete the parent, so to fix it I inverted this to get the order right and everything started working correctly,

User became the parent

Photo became the child

#
package com.logan.restapi.models;

import com.fasterxml.jackson.annotation.JsonManagedReference;
import com.logan.restapi.listeners.UserModelListener;
import com.logan.restapi.roles.UserRoles;
import jakarta.persistence.*;

import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.util.Date;
import java.util.Set;

@Getter
@Setter
@Entity
@Table(name = "users")
@EntityListeners(UserModelListener.class)
public class UserModel {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false, unique = true)
    private String username;

    @Column(nullable = false)
    private String password;

    @ElementCollection(targetClass = UserRoles.class, fetch = FetchType.EAGER)
    @CollectionTable(name = "users_roles", joinColumns = @JoinColumn(name = "user_id"))
    @Enumerated(EnumType.STRING)
    private Set<UserRoles> roles;

    @CreationTimestamp
    @Column(nullable = false, updatable = false)
    private Date createdAt;

    @UpdateTimestamp
    @Column(nullable = false)
    private Date updatedAt;

    @OneToOne(cascade = CascadeType.ALL, orphanRemoval = true)
    private PhotoModel photo;
}
#
package com.logan.restapi.models;

import com.fasterxml.jackson.annotation.JsonIgnore;
import jakarta.persistence.*;
import lombok.Getter;
import lombok.Setter;
import org.hibernate.annotations.CreationTimestamp;
import org.hibernate.annotations.UpdateTimestamp;

import java.util.Date;

@Getter
@Setter
@Entity
@Table(name = "photos")
public class PhotoModel {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    private Long id;

    @Column(nullable = false)
    private String filename;

    @Column(nullable = false)
    private String url;

    @CreationTimestamp
    @Column(nullable = false, updatable = false)
    private Date createdAt;

    @UpdateTimestamp
    @Column(nullable = false)
    private Date updatedAt;

    @OneToOne(mappedBy = "photo")
    @JsonIgnore
    private UserModel user;

    @PreRemove
    private void preRemove() {
        if(user != null) {
            user.setPhoto(null);
        }
    }
}
zealous bolt
#

Now its working fine!, Thankyou Any way!

@Override
@Transactional
public Object deletePhoto(UserFromRequest user) {
    UserModel userModel = getUserModel(user);

    PhotoModel photo = userModel.getPhoto();

    Map<String, Object> response = new HashMap<>();

    if (photo == null) {
        response.put(ERROR, "Photo not found");
        return response;
    }

    try {
        // Remove the photo from the database
        photosRepository.delete(photo);

        Path photoPath = Paths.get(UPLOAD_DIR + photo.getFilename());
        Files.deleteIfExists(photoPath);

        response.put(PHOTO, photo);

        response.put("message", "Photo deleted successfully.");

        return response;
    } catch (Exception e) {
        logger.severe(e.getMessage());
        response.put(ERROR, "Failed to delete photo.");
        return response;
    }
}
native hill
#

I was relating photo as the parent and user as the child, which is incorrect because when I deleted the parent, I would delete the child OR I would not be able to delete the parent, so to fix it I inverted this to get the order right and everything started working correctly,
I see that you talk about relationship here

#

in fact i don't see any parent - child relationship since the start of your question

#

because in OO when we talk about a parent -child, in code it means inheritance

#

like

#
class Child extends Parent {}
#

but in your case it's called association

#

or composition

#

in other words we say that "a User has a Photo", "the User deletes his Photo"

#

Also for your good future ig, i'd advise something, when you ask about something try to give a small minimal example based on the real code u have. don't copy/paste your real code, because that may make the conversation hard to read and follow to helpers

limpid pineBOT
#
Post Closed

This post has been closed by @zealous bolt.

stiff thistle
#

#general message