Skip to content

Commit 557aa13

Browse files
authored
Merge pull request #85 from boolean-uk/FIX/delete-fix
Fixed delete logic for users
2 parents ebf7493 + 89ecea9 commit 557aa13

File tree

6 files changed

+51
-46
lines changed

6 files changed

+51
-46
lines changed

src/main/java/com/booleanuk/Main.java

Lines changed: 37 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -29,12 +29,12 @@
2929

3030
@SpringBootApplication
3131
public class Main implements CommandLineRunner {
32-
32+
3333
// DATABASE SIZE CONFIGURATION
3434
// Set to true for LARGE database: 3 courses, 4 cohorts per course (12 total), 30 students per cohort (360 total)
3535
// Set to false for SMALL database: 3 courses, 1 cohort per course (3 total), 10 students per cohort (30 total)
3636
private static final boolean USE_LARGE_DATABASE = false;
37-
37+
3838
@Autowired
3939
private RoleRepository roleRepository;
4040
@Autowired
@@ -57,11 +57,12 @@ public static void main(String[] args) {
5757
@Override
5858
public void run(String... args) {
5959
System.out.println("Initializing sample data...");
60-
60+
6161
// Create roles
62-
62+
6363
Role teacherRole = createOrGetRole(ERole.ROLE_TEACHER);
6464
Role studentRole = createOrGetRole(ERole.ROLE_STUDENT);
65+
6566

6667
// Create courses with start and end dates
6768
Course javaFundamentals = createOrGetCourse("Software Development",
@@ -71,12 +72,13 @@ public void run(String... args) {
7172
Course reactFundamentals = createOrGetCourse("Data Analytics",
7273
LocalDate.of(2024, 3, 1), LocalDate.of(2024, 9, 1));
7374

75+
7476
// Create cohorts based on configuration
7577
List<Cohort> allCohorts = new ArrayList<>();
76-
78+
7779
if (USE_LARGE_DATABASE) {
7880
// LARGE DATABASE: 4 cohorts per course (12 total)
79-
81+
8082
// Software Development cohorts (4 cohorts)
8183
allCohorts.add(createOrGetCohort("Software Development 2024 Q1", javaFundamentals));
8284
allCohorts.add(createOrGetCohort("Software Development 2024 Q2", javaFundamentals));
@@ -101,30 +103,30 @@ public void run(String... args) {
101103
allCohorts.add(createOrGetCohort("Data Analytics 2025", reactFundamentals));
102104
}
103105

104-
106+
105107
// Create teacher users
106108
User teacherJohn = createUser("[email protected]", "p", teacherRole);
107109
if (teacherJohn.getProfile() == null) {
108-
Profile johnProfile = new Profile(teacherJohn, "John", "Smith", "johnsmith",
109-
"https://github.com/johnsmith", "+44123456790",
110-
"Experienced Java developer and educator with 10+ years in software development.",
110+
Profile johnProfile = new Profile(teacherJohn, "John", "Smith", "johnsmith",
111+
"https://github.com/johnsmith", "+44123456790",
112+
"Experienced Java developer and educator with 10+ years in software development.",
111113
teacherRole, "Java Development", allCohorts.get(0), null);
112114
profileRepository.save(johnProfile);
113115
teacherJohn.setProfile(johnProfile);
114116
userRepository.save(teacherJohn);
115117
}
116-
118+
117119
User teacherSarah = createUser("[email protected]", "p", teacherRole);
118120
if (teacherSarah.getProfile() == null) {
119-
Profile sarahProfile = new Profile(teacherSarah, "Sarah", "Jones", "sarahjones",
120-
"https://github.com/sarahjones", "+44123456791",
121-
"Frontend specialist with expertise in React and modern web technologies.",
121+
Profile sarahProfile = new Profile(teacherSarah, "Sarah", "Jones", "sarahjones",
122+
"https://github.com/sarahjones", "+44123456791",
123+
"Frontend specialist with expertise in React and modern web technologies.",
122124
teacherRole, "Frontend Development", allCohorts.get(1), null);
123125
profileRepository.save(sarahProfile);
124126
teacherSarah.setProfile(sarahProfile);
125127
userRepository.save(teacherSarah);
126128
}
127-
129+
128130
// Create student users
129131
List<User> students = new ArrayList<>();
130132
String[] firstNames = {
@@ -141,11 +143,11 @@ public void run(String... args) {
141143
"Hernandez", "King", "Wright", "Lopez", "Hill", "Scott", "Green", "Adams",
142144
"Baker", "Gonzalez", "Nelson", "Carter", "Mitchell", "Perez", "Roberts", "Turner"
143145
};
144-
146+
145147
// Create students based on configuration
146148
int totalStudents = USE_LARGE_DATABASE ? 360 : 30; // 360 for large (30 per cohort), 30 for small (10 per cohort)
147149
int studentsPerCohort = USE_LARGE_DATABASE ? 30 : 10;
148-
150+
149151
for (int i = 0; i < totalStudents; i++) {
150152
String firstName = firstNames[i % firstNames.length];
151153
String lastName = lastNames[i % lastNames.length];
@@ -155,20 +157,20 @@ public void run(String... args) {
155157
if (student.getProfile() == null) {
156158
// Distribute students evenly across all cohorts
157159
Cohort assignedCohort = allCohorts.get(i / studentsPerCohort);
158-
159-
Profile studentProfile = new Profile(student, firstName, lastName,
160-
firstName.toLowerCase() + lastName.toLowerCase() + i,
161-
"https://github.com/" + firstName.toLowerCase() + lastName.toLowerCase() + i,
162-
"+4412345679" + String.format("%03d", i),
163-
"Passionate about learning software development and building amazing applications.",
160+
161+
Profile studentProfile = new Profile(student, firstName, lastName,
162+
firstName.toLowerCase() + lastName.toLowerCase() + i,
163+
"https://github.com/" + firstName.toLowerCase() + lastName.toLowerCase() + i,
164+
"+4412345679" + String.format("%03d", i),
165+
"Passionate about learning software development and building amazing applications.",
164166
studentRole, "Software Development", assignedCohort, null);
165167
profileRepository.save(studentProfile);
166168
student.setProfile(studentProfile);
167169
student = userRepository.save(student);
168170
}
169171
students.add(student);
170172
}
171-
173+
172174
// Create sample posts
173175
List<String> samplePosts = Arrays.asList(
174176
"Just finished my first Java application! Excited to learn more about Spring Boot.",
@@ -182,7 +184,7 @@ public void run(String... args) {
182184
"Code review session was very helpful. Learning from others is invaluable.",
183185
"Working on the final project. Bringing everything together is challenging but rewarding."
184186
);
185-
187+
186188
// Create posts from different users (only if no posts exist)
187189
if (postRepository.count() == 0) {
188190
for (int i = 0; i < samplePosts.size(); i++) {
@@ -192,12 +194,14 @@ public void run(String... args) {
192194
postRepository.save(post);
193195
}
194196
}
195-
197+
196198
System.out.println("Sample data initialization completed!");
197199
System.out.println("Created:");
198200
System.out.println("- 2 roles (Teacher, Student)");
201+
199202
System.out.println("- 3 courses with date ranges (Software Development: Jan-Jul 2024, Front-End Development: Feb-Aug 2024, Data Analytics: Mar-Sep 2024)");
200203

204+
201205
if (USE_LARGE_DATABASE) {
202206
System.out.println("- 12 cohorts (4 per course)");
203207
System.out.println("- " + (2 + students.size()) + " users with profiles (2 teachers + " + students.size() + " students)");
@@ -213,15 +217,15 @@ public void run(String... args) {
213217
System.out.println(" - Front-End Development: 1 cohort (10 students)");
214218
System.out.println(" - Data Analytics: 1 cohort (10 students)");
215219
}
216-
220+
217221
System.out.println("- " + samplePosts.size() + " sample posts");
218222
}
219-
223+
220224
private Role createOrGetRole(ERole roleName) {
221225
return roleRepository.findByName(roleName)
222226
.orElseGet(() -> roleRepository.save(new Role(roleName)));
223227
}
224-
228+
225229
private User createUser(String email, String password, Role role) {
226230
// Check if user already exists
227231
return userRepository.findByEmail(email)
@@ -233,14 +237,16 @@ private User createUser(String email, String password, Role role) {
233237
return userRepository.save(user);
234238
});
235239
}
240+
236241

237242
private Course createOrGetCourse(String name, LocalDate startDate, LocalDate endDate) {
243+
238244
return courseRepository.findAll().stream()
239245
.filter(course -> course.getName().equals(name))
240246
.findFirst()
241247
.orElseGet(() -> courseRepository.save(new Course(name, startDate, endDate, null)));
242248
}
243-
249+
244250
private Cohort createOrGetCohort(String name, Course course) {
245251
return cohortRepository.findAll().stream()
246252
.filter(cohort -> cohort.getName().equals(name))
@@ -250,4 +256,4 @@ private Cohort createOrGetCohort(String name, Course course) {
250256
return cohortRepository.save(cohort);
251257
});
252258
}
253-
}
259+
}

src/main/java/com/booleanuk/cohorts/controllers/UserController.java

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import java.util.List;
44
import java.util.Set;
55

6+
import jakarta.transaction.Transactional;
67
import org.springframework.beans.factory.annotation.Autowired;
78
import org.springframework.http.HttpStatus;
89
import org.springframework.http.ResponseEntity;
@@ -76,9 +77,14 @@ public ResponseEntity<?> deleteUser(@PathVariable int id) {
7677
error.set("not found");
7778
return new ResponseEntity<>(error, HttpStatus.NOT_FOUND);
7879
}
80+
for (Post post : user.getLikedPosts()){
81+
post.getLikedByUsers().remove(user);
82+
}
7983
user.getRoles().clear();
84+
user.getLikedPosts().clear();
8085
UserResponse userResponse = new UserResponse();
8186
userResponse.set(user);
87+
8288
try {
8389
userRepository.delete(user);
8490
return ResponseEntity.ok(userResponse);

src/main/java/com/booleanuk/cohorts/models/Post.java

Lines changed: 6 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1,22 +1,12 @@
11
package com.booleanuk.cohorts.models;
22

33
import java.time.OffsetDateTime;
4+
import java.util.HashSet;
45
import java.util.List;
6+
import java.util.Set;
57

68
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
7-
import jakarta.persistence.CascadeType;
8-
import jakarta.persistence.Column;
9-
import jakarta.persistence.Entity;
10-
import jakarta.persistence.FetchType;
11-
import jakarta.persistence.GeneratedValue;
12-
import jakarta.persistence.GenerationType;
13-
import jakarta.persistence.Id;
14-
import jakarta.persistence.JoinColumn;
15-
import jakarta.persistence.ManyToOne;
16-
import jakarta.persistence.OneToMany;
17-
import jakarta.persistence.PrePersist;
18-
import jakarta.persistence.Table;
19-
import jakarta.persistence.Transient;
9+
import jakarta.persistence.*;
2010
import lombok.AllArgsConstructor;
2111
import lombok.Data;
2212
import lombok.EqualsAndHashCode;
@@ -45,6 +35,9 @@ public class Post {
4535
@Column(name = "time_updated", nullable = false, columnDefinition = "TIMESTAMP WITH TIME ZONE")
4636
private OffsetDateTime timeUpdated;
4737

38+
@ManyToMany(mappedBy = "likedPosts")
39+
private Set<User> likedByUsers = new HashSet<>();
40+
4841
@ManyToOne
4942
@JoinColumn(name = "user_id", nullable = false)
5043
@JsonIgnoreProperties(value = {"posts", "comments", "cohort", "roles", "likedPosts"})

src/main/java/com/booleanuk/cohorts/models/User.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -49,7 +49,7 @@ public class User {
4949
@JsonIncludeProperties({"id", "content", "likes", "timeCreated", "timeUpdated" })
5050
private List<Post> posts;
5151

52-
@ManyToMany
52+
@ManyToMany(cascade = CascadeType.ALL)
5353
@JoinTable(name = "user_liked_posts",
5454
joinColumns = @JoinColumn(name = "user_id"),
5555
inverseJoinColumns = @JoinColumn(name = "post_id"))

src/main/java/com/booleanuk/cohorts/payload/request/PostRequest.java

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,5 +18,4 @@ public PostRequest(String content, int userId) {
1818
this.content = content;
1919
this.userId = userId;
2020
}
21-
2221
}

src/main/java/com/booleanuk/cohorts/repository/UserRepository.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import java.util.Optional;
44

55
import org.springframework.data.jpa.repository.JpaRepository;
6+
import org.springframework.data.jpa.repository.Modifying;
67
import org.springframework.data.jpa.repository.Query;
78
import org.springframework.data.repository.query.Param;
89
import org.springframework.stereotype.Repository;

0 commit comments

Comments
 (0)