4-SpringBoot BlogPost project Jan 25
4-SpringBoot BlogPost project Jan 25
======================
POJO:
------
public class Blog {
List<Comment>comments=new ArrayList<Comment>();
.......
}
entities:
----------
@Entity
@Table(name="blog_table")
public class Blog {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String title;
private String author;
private String content;
@OneToMany(mappedBy="blog", cascade=CascadeType.ALL)
@JsonIgnore
List<Comment>comments=new ArrayList<Comment>();
@Entity
@Table(name="comment_table")
public class Comment {
@Id @GeneratedValue(strategy=GenerationType.IDENTITY)
private Long id;
private String comment;
private LocalDateTime createdAt;
@JoinColumn(name="bid_fk")
@ManyToOne(fetch=FetchType.LAZY, optional=false)
@JsonIgnore
private Blog blog;
.......
}
repositoriies:
---------------
//blogRepo.delete(blogRepo.getOne(1L));
blogRepo.save(blog);
commentRepo.save(comment1);
commentRepo.save(comment2);
commentRepo.save(comment3);
blogRepo.save(blog2);
commentRepo.save(comment4);
commentRepo.save(comment5);
commentRepo.save(comment6);
*/
controllers:
------------
@RestController
@RequestMapping(path = "api")
public class BlogController {
@Autowired
private BlogRepo blogRepo;
@GetMapping(path = "blog")
public ResponseEntity<List<Blog>> getAllBlogs() {
return ResponseEntity.ok().body(blogRepo.findAll());
}
@PostMapping(path = "blog")
public ResponseEntity<Blog> postBlogs(@RequestBody Blog blog) {
blogRepo.save(blog);
return ResponseEntity.status(HttpStatus.CREATED).body(blog);
}
// update blog
@PutMapping(path = "blog/{id}")
public ResponseEntity<Blog> upddateBlog(@PathVariable(name = "id") Long id,
@RequestBody Blog blogReq) {
return blogRepo.findById(id).map(blog-> {
blog.setContent(blogReq.getContent());
blog.setTitle(blogReq.getTitle());
return ResponseEntity.ok().body(blogRepo.save(blog));
}).orElseThrow(() -> new ResourceNotFoundException("blog with id " + id
+ " not found"));
}
//delete blog
@DeleteMapping(path = "blog/{id}")
public ResponseEntity<?>deleteBlog(@PathVariable(name = "id") Long id){
return blogRepo.findById(id).map(blog->{
blogRepo.delete(blog);
return ResponseEntity.noContent().build();
}).orElseThrow(() -> new ResourceNotFoundException("blog with id " + id
+ " not found"));
}
//get blog by id
@GetMapping(path = "blog/{id}")
public ResponseEntity<Blog>getByIdBlog(@PathVariable(name = "id") Long id){
return blogRepo.findById(id).map(blog->{
return ResponseEntity.ok().body(blog);
}).orElseThrow(() -> new ResourceNotFoundException("blog with id " + id
+ " not found"));
}
}
@RestController
@RequestMapping(path = "api")
public class CommentController {
@Autowired
private BlogRepo blogRepo;
@Autowired
private CommentRepo commentRepo;
}
@PostMapping("/blog/{blogId}/comment")
public ResponseEntity<Comment> createComment(
@PathVariable(value = "blogId") Long blogId,
@RequestBody Comment comment) {
blog.addComment(comment);
blogRepo.save(blog);
commentRepo.save(comment);
return ResponseEntity.ok().body(comment);
@PutMapping("/blog/{blogId}/comment/{commentId}")
public ResponseEntity<Comment> updateComment(@PathVariable(value = "blogId")
Long blogId,
@PathVariable(value = "commentId") Long commentId,
@RequestBody Comment commentRequest) {
if (!blogRepo.existsById(blogId)) {
throw new ResourceNotFoundException("blogId " + blogId
+ " not found");
}
comment.setComment(commentRequest.getComment());
commentRepo.save(comment);
return ResponseEntity.ok().body(comment);
}
@DeleteMapping("/blog/{blogId}/comment/{commentId}")
public ResponseEntity<?> deleteComment(@PathVariable (value = "blogId") Long
blogId,
@PathVariable (value = "commentId") Long commentId) {
return commentRepo.findByIdAndBlogId(commentId, blogId).map(comment -> {
commentRepo.delete(comment);
return ResponseEntity.noContent().build();
}).orElseThrow(() -> new ResourceNotFoundException
("Comment not found with id " + commentId + " and blogId " +
blogId));
}
}
Exception handling:
------------------
public class ErrorDetails {
private String message;
private LocalDateTime timeStamp;
private String detail;
private String contactTo;
}
@ControllerAdvice
@RestController
public class ExceptionHandlerRestController {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<ErrorDetails> handleBookNotFoundEx(
@ExceptionHandler(Exception.class)
public ResponseEntity<ErrorDetails> handleOtherEx(
@ResponseStatus(HttpStatus.NOT_FOUND)
public class ResourceNotFoundException extends RuntimeException {
private static final long serialVersionUID = 1L;
public ResourceNotFoundException(String message) {
super(message);
}
}
#spring.security.user.name=raja
#spring.security.user.password=raja123
server.port=8090
server.servlet.context-path=/blogapp
spring.jpa.hibernate.ddl-auto=update
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/boot_demo2?useSSL=false
spring.jpa.show-sql=true
logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR