#I can't delete the photo from database, I can't figure out why.
48 messages · Page 1 of 1 (latest)
⌛ This post has been reserved for your question.
Hey @zealous bolt! Please use
/closeor theClose Postbutton 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.
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;
}
}
Logs
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
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
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
@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
the all code
does it not get deleted from the database
or does it return that the photo exists even when its deleted
check it
💤 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.
It doesn't delete from the database. The return is only temporary so I know what is returning. But it's not deleting from the database, but it deletes normally from the server.
add a check to see if its still in the database
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
h2 and mysql, I'm doing some tests, I'm using jpa
It may be a kind of solution, but making this modification manually is not my intention in this specific example.
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);
}
}
}
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;
}
}
Hiya !
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
This post has been closed by @zealous bolt.
#general message