Search code examples
javaspringspring-bootpersistence

How to make entity class and controller for biography backend using Spring Boot?


How would you make an entity class for the backend portion of a biography page (on a site). I am unsure how to approach something like this since there aren't specific things that need to be sent from the server. I have attached some code that I used for my entity class.

Does my entity class seem like the correct way to approach creating a backend for a biography page on a site using Spring Boot?

Entity Class

    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;

    @Entity
    @Table(name="BIOGRAPHY")
    public class Biography {

        @Id
        @GeneratedValue
        private Long sectionId;

        @Column(name = "section_title")
        private String titleSection;

        @Column(name = "section_text")
        private String textSection;




        public Long getSectionId() {
            return sectionId;
        }

        public String getTitleSection() {
            return titleSection;
        }

        public String getTextSection() {
            return textSection;
        }

        @Override
        public String toString() {
            return "EmployeeEntity [sectionId=" + sectionId + ", titleSection=" + titleSection +
                    ", textSection=" + textSection + "]";
        }

    }

Solution

  • Here is what you could do to implement a Spring controller that takes care of requests to the Biography entity.

    1. Your Biography entity appears to be good
    2. To work with it, you could take advantage of org.springframework.data.repository.CrudRepository;
      Namely:
    public interface BiographyRepository  extends CrudRepository <Biography, Long> {
    
    }
    
    1. Spring is pretty flexible and you can organize your code the way you like it. Here is just an example of how you could organize controller code:
    @RestController
    @RequestMapping 
    public class BiographyController {
    
      @Autowired
      private BiographyRepository biographyRepository;
    
      @RequestMapping(value = "/biography, method = RequestMethod.POST)
      public @ResponseBody
      Response create (HttpServletRequest request) {
        //read biography object from the request
        biographyRepository.save(biography);
      }
    
      //other methods...
    }
    

    Depending on what you need, a better practice could be working with the repository through a @Service in the Controller.

    Hope that helps.