Spring Basic JPA

  1. Assume we have a domain class call cat as shown at the end of this page
  2. Create a new package call doa under your project package
  3. Create an interface name CatRepository that extends CrudRepository
    package com.example.demo.dao
    import com.example.demo.domain.Cat
    import org.springframework.data.repository.CrudRepository
    interface CatRepository extends CrudRepository<Cat, Long>{
        Cat findById(long id)
        List<Cat> findByName(String name)
        List<Cat> findByNameAndBreed(String name, String breed)
    }
  4. We can create some new function called findBy…, which … must be matched to the getter of the domain class. By this it spring will automatically create the method for us to search. (Yes, we do not have to implement it!)
  5. Here we have two methods findByName, and findByNameAndBreed we can call.
  6. In our controller, we do
        @Autowired
        private CatRepository catRepository;

    It will auto wired the actual object that spring will created for us, and we can use this object to CURD our domain class.

  7. Here is how we do it:
    package com.example.demo.controllers
    import com.example.demo.dao.CatRepository
    import com.example.demo.domain.Cat
    import org.springframework.beans.factory.annotation.Autowired
    import org.springframework.web.bind.annotation.*
    import java.text.DateFormat
    import java.text.SimpleDateFormat
    
    @RestController
    @RequestMapping("cat")
    class CatController {
        @Autowired
        private CatRepository catRepository;
    
        @GetMapping("/")
        index() {
            List<Cat> cats = catRepository.findAll()
            return cats
        }
    
        @PostMapping("/create")
        add(@RequestParam(value = "name", defaultValue = "") String name,
            @RequestParam(value = "breed", defaultValue = "") String breed,
            @RequestParam(value = "dob", defaultValue = "") String dob) {
                if (name != "" && breed != "" && dob != "") {
                try {
                    DateFormat format = new SimpleDateFormat("dd-MM-yyyy")
                    Date date = format.parse(dob)
                    Cat cat = new Cat(name, breed, date)
                    catRepository.save(cat)
                } catch (Exception e) {
                    return e.toString()
                }
            } else {
                return "Cannot be save!"
            }
        }
    
        @PostMapping("/update/{id}")
        update(@PathVariable long id,
               @RequestParam(value = "name", defaultValue = "") String name,
               @RequestParam(value = "breed", defaultValue = "") String breed,
               @RequestParam(value = "dob", defaultValue = "") String dob) {
            if (name != "" && breed != "" && dob != "") {
                Cat c = catRepository.findById(id)
                if (c != null) {
                    try {
                        DateFormat format = new SimpleDateFormat("dd-MM-yyyy")
                        Date date = format.parse(dob)
                        c.setName(name)
                        c.setBreed(breed)
                        c.setDateOfBirth(date)
                        catRepository.save(c)
                        return "Updated"
                    } catch (Exception e) {
                        return e.toString()
                    }
                }
            }
            return "Cannot be save!"
        }
    
        @GetMapping("/get/{id}")
        getById(@PathVariable long id) {
            Cat cat = catRepository.findById(id)
            if (cat != null)
                return cat
            else return "cat not found!"
        }
    
        @PostMapping("/delete/{id}")
        delete(@PathVariable long id) {
            try {
                catRepository.deleteById(id)
                return "Deleted"
            } catch (Exception e) {
                return e.toString()
            }
        }
    }

Our Cat domain class:

package com.example.demo.domain

import javax.persistence.Entity
import javax.persistence.GeneratedValue
import javax.persistence.GenerationType
import javax.persistence.Id

@Entity
class Cat {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Long id
    private String name
    private String breed
    private Date dateOfBirth

    protected Cat() {}

    Cat(String name, String breed, Date dateOfBirth) {
        this.name = name
        this.breed = breed
        this.dateOfBirth = dateOfBirth
    }

    Long getId() { return id }
    String getName() { return name }
    String getBreed() { return breed }
    Date getDateOfBirth() { return dateOfBirth }
    void setName(String name) { this.name = name }
    void setBreed(String breed) { this.breed = breed }
    void setDateOfBirth(Date dateOfBirth) { this.dateOfBirth = dateOfBirth }
}