4 lab посты вроде функционируют

This commit is contained in:
Павел Сорокин 2023-04-04 11:43:08 +04:00
parent cbf337eea6
commit ee923e986d
6 changed files with 135 additions and 54 deletions

View File

@ -3,5 +3,5 @@ package ru.ulstu.is.sbapp.Post.repository;
import org.springframework.data.jpa.repository.JpaRepository;
import ru.ulstu.is.sbapp.Post.model.Post;
public interface PostRepository extends JpaRepository<Post, Long> {
public interface PostRepository extends JpaRepository<Post, Long>,PostRepositoryExtension {
}

View File

@ -0,0 +1,14 @@
package ru.ulstu.is.sbapp.Post.repository;
import ru.ulstu.is.sbapp.Comment.model.Comment;
import ru.ulstu.is.sbapp.Post.model.Post;
import java.util.List;
import java.util.Optional;
public interface PostRepositoryExtension {
Optional<Post> safeRemove(Long id);
void safeRemoveAll();
void addComment(Long id,Long userId,String text);
void removeComment(Long id, Long commentId);
}

View File

@ -0,0 +1,70 @@
package ru.ulstu.is.sbapp.Post.repository;
import jakarta.persistence.EntityManager;
import jakarta.persistence.PersistenceContext;
import jakarta.persistence.TypedQuery;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import ru.ulstu.is.sbapp.Comment.model.Comment;
import ru.ulstu.is.sbapp.Comment.repository.CommentRepository;
import ru.ulstu.is.sbapp.Post.model.Post;
import ru.ulstu.is.sbapp.User.model.User;
import java.util.List;
import java.util.Optional;
public class PostRepositoryImpl implements PostRepositoryExtension{
@Autowired
@Lazy
private PostRepository postRepository;
@Autowired
@Lazy
private CommentRepository commentRepository;
@PersistenceContext
private EntityManager em;
@Override
public Optional<Post> safeRemove(Long id) {
Optional<Post> optionalPost = postRepository.findById(id);
if(optionalPost.isPresent())
{
em.createQuery("Delete from Comment where post.id = :id")
.setParameter("id",id)
.executeUpdate();
em.remove(optionalPost.get());
}
return optionalPost;
}
@Override
public void safeRemoveAll() {
em.createQuery("delete from Comment").executeUpdate();
em.createQuery("delete from Post").executeUpdate();
}
@Override
public void addComment(Long id, Long userId, String text) {
Optional<Post> optionalPost = postRepository.findById(id);
if(optionalPost.get()==null){
throw new IllegalArgumentException("Post with id " + id + " not found");
}
Comment comment=new Comment(text);
comment.setPost(optionalPost.get(), em.find(User.class, userId));
commentRepository.save(comment);
}
@Override
public void removeComment(Long id, Long commentId) {
Optional<Post> optionalPost = postRepository.findById(id);
Optional<Comment> optionalComment = commentRepository.findById(commentId);
optionalPost.get().getComments().remove(optionalComment.get());
em.merge(optionalPost.get());
optionalComment.get().setPost(null, null);
em.createQuery("Delete from Comment where Id = :commentId")
.setParameter("commentId",commentId)
.executeUpdate();
}
}

View File

@ -1,93 +1,76 @@
package ru.ulstu.is.sbapp.Post.service;
import jakarta.persistence.EntityManager;
import jakarta.persistence.EntityNotFoundException;
import jakarta.persistence.PersistenceContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import ru.ulstu.is.sbapp.Comment.model.Comment;
import ru.ulstu.is.sbapp.Comment.repository.CommentRepository;
import ru.ulstu.is.sbapp.Post.model.Post;
import ru.ulstu.is.sbapp.Post.repository.PostRepository;
import ru.ulstu.is.sbapp.User.model.User;
import ru.ulstu.is.sbapp.Util.validation.ValidatorUtil;
import java.util.List;
import java.util.Optional;
@Service
public class PostService {
@PersistenceContext
private EntityManager em;
private final PostRepository postRepository;
private final CommentRepository commentRepository;
private final ValidatorUtil validatorUtil;
private static final Logger log = LoggerFactory.getLogger(PostService.class);
public PostService(PostRepository postRepository,CommentRepository commentRepository,ValidatorUtil validatorUtil)
{
this.postRepository=postRepository;
this.commentRepository=commentRepository;
this.validatorUtil=validatorUtil;
}
@Transactional
public Post addPost(String Heading, String Content) {
if (!StringUtils.hasText(Heading) || !StringUtils.hasText(Content) ) {
throw new IllegalArgumentException("Post info is null or empty");
}
final Post post = new Post(Heading,Content);
em.persist(post);
return post;
validatorUtil.validate(post);
return postRepository.save(post);
}
@Transactional(readOnly = true)
public Post findPost(Long id) {
final Post post = em.find(Post.class, id);
if (post == null) {
throw new EntityNotFoundException(String.format("Post with id [%s] is not found", id));
}
return post;
final Optional<Post> post = postRepository.findById(id);
return post.orElseThrow(() -> new PostNotFoundException(id));
}
@Transactional(readOnly = true)
public List<Post> findAllPosts() {
return em.createQuery("select p from Post p", Post.class)
.getResultList();
return postRepository.findAll();
}
@Transactional
public Post updatePost(Long id, String Heading, String Content) {
if (!StringUtils.hasText(Heading) || !StringUtils.hasText(Content) ) {
throw new IllegalArgumentException("Post info is null or empty");
}
final Post currentPost = findPost(id);
currentPost.setHeading(Heading);
currentPost.setContent(Content);
return em.merge(currentPost);
validatorUtil.validate(currentPost);
return postRepository.save(currentPost);
}
@Transactional
public Post deletePost(Long id) {
final Post currentPost = findPost(id);
em.createQuery("Delete from Comment where post.id = "+id).executeUpdate();
em.remove(currentPost);
return currentPost;
final Optional<Post> post = postRepository.safeRemove(id);
return post.orElseThrow(() -> new PostNotFoundException(id));
}
@Transactional
public void deleteAllPosts() {
em.createQuery("delete from Comment").executeUpdate();
em.createQuery("delete from Post").executeUpdate();
postRepository.safeRemoveAll();
}
@Transactional
public Comment addCommentToPost(Long id, User user, String text){
final Post post = findPost(id);
if(post == null){
throw new IllegalArgumentException("Post with id " + id + " not found");
}
Comment comment=new Comment(text);
comment.setPost(post, em.find(User.class, user.getId()));
return em.merge(comment);
public void addCommentToPost(Long id, Long userId, String text){
postRepository.addComment(id, userId, text);
}
@Transactional
public void removeCommentFromPost(Long id, Comment comment){
final Post post = findPost(id);
log.info(post.toString());
post.getComments().remove(comment);
em.merge(post);
comment.setPost(null, null);
em.createQuery("Delete from Comment where Id = "+comment.getId()).executeUpdate();
public void removeCommentFromPost(Long id, Long commentId){
postRepository.removeComment(id,commentId);
}
}

View File

@ -93,7 +93,7 @@ public class JpaClientTests {
postService.deleteAllPosts();
}
//посты и коментарии содержащие определенный текст
@Test
/*@Test
void Selected()
{
postService.deleteAllPosts();
@ -113,5 +113,5 @@ public class JpaClientTests {
List<Object[]> onk=(userService.SelectCommentByText("Привет"));
log.info(String.valueOf((userService.SelectCommentByText("Привет").size())));
}
}*/
}

View File

@ -10,6 +10,7 @@ import org.springframework.boot.test.context.SpringBootTest;
import ru.ulstu.is.sbapp.Comment.model.Comment;
import ru.ulstu.is.sbapp.Comment.service.CommentService;
import ru.ulstu.is.sbapp.Post.model.Post;
import ru.ulstu.is.sbapp.Post.service.PostNotFoundException;
import ru.ulstu.is.sbapp.Post.service.PostService;
import ru.ulstu.is.sbapp.User.model.User;
import ru.ulstu.is.sbapp.User.service.UserService;
@ -44,7 +45,7 @@ public class JpaPostTests {
@Test
void TestPostReadNotFound(){
postService.deleteAllPosts();
Assertions.assertThrows(EntityNotFoundException.class, () -> postService.findPost(-1L));
Assertions.assertThrows(PostNotFoundException.class, () -> postService.findPost(-1L));
}
@Test
@ -70,13 +71,26 @@ public class JpaPostTests {
Assertions.assertEquals(post.getHeading(), "Test2");
Assertions.assertEquals(post.getContent(), "Test2");
}
@Test
void TestDeleteAllPosts()
{
log.info("Удаление всех постов");
Post post = postService.addPost("Test1", "Test1");
Post post2 = postService.addPost("Test1", "Test1");
List<Post> posts1 = postService.findAllPosts();
log.info(posts1.toString());
postService.deleteAllPosts();
List<Post> posts = postService.findAllPosts();
log.info(posts.toString());
}
@Test
void TestDeletePost(){
postService.deleteAllPosts();
final Post post = postService.addPost("Test","Test");
postService.deletePost(post.getId());
Assertions.assertThrows(EntityNotFoundException.class, () -> postService.findPost(1L));
Assertions.assertThrows(PostNotFoundException.class, () -> postService.findPost(1L));
}
@Test
@ -91,7 +105,7 @@ public class JpaPostTests {
log.info(user2.getPosts().toString());
final Post post2=postService.findPost(post.getId());
log.info(post2.toString());
final Comment comment =postService.addCommentToPost(post.getId(),user,"Крутой пост");
postService.addCommentToPost(post.getId(),user.getId(),"Крутой пост");
final List<Comment> comments = commentService.findAllComments();
log.info(comments.toString());
final User user1=userService.findUser(user.getId());
@ -111,17 +125,17 @@ public class JpaPostTests {
log.info("Посты юзера (добавили)"+user2.getPosts().toString());
final Post post2=postService.findPost(post.getId());
log.info("Пост который добавили"+post2.toString());
final Comment comment =postService.addCommentToPost(post.getId(),user,"Крутой пост");
final Comment commentcur =postService.addCommentToPost(post.getId(),user,"Пост плохой");
postService.addCommentToPost(post.getId(),user.getId(),"Крутой пост");
postService.addCommentToPost(post.getId(),user.getId(),"Пост плохой");
final List<Comment> comments = commentService.findAllComments();
log.info("Добавили коммент"+comments.toString());
final User user1=userService.findUser(user.getId());
log.info("Комменты юзера"+user1.getComments().toString());
final Post post1=postService.findPost(post.getId());
log.info("Комменты к посту"+post1.getComments().toString());
Comment comment1 = commentService.findComment(comment.getId());
Comment comment1 = commentService.findComment(comments.get(0).getId());
log.info("Удаляем коммент");
postService.removeCommentFromPost(post.getId(),comment1);
postService.removeCommentFromPost(post.getId(),comment1.getId());
final User user3=userService.findUser(user.getId());
log.info(user3.getPosts().toString());
log.info("Комменты юзера после удаления"+user3.getComments().toString());