Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

check if a record exist in database using spring boot and JPA repository

I want to check whether a record exist in database before I save. If possible I want to check using two fields i.e regno and name. method to be like checkIfRegNoAndNameExists(){}. my model class

@Entity
public class Car {
     @Id
    @GeneratedValue
    private int id;
    private String regno;
    private String name;
    // getters, setters, ...
}

my dao class

import org.springframework.data.jpa.repository.JpaRepository;
public interface ProgramDao extends JpaRepository<CarModel, Integer> {
}

my service class

@Service
public class CarServiceImpl implements ProgramService {
    @Autowired
    private CarDao carDao;
    @Override
    public carModel saveProgram(carModel car) { 
        return carDao.save(program);
    }
}
like image 504
user3736334 Avatar asked Dec 08 '19 03:12

user3736334


2 Answers

interface ProgramDao extends JpaRepository<CarModel, Integer> {
    boolean existsByRegnoAndName(String regno, String name);
}
like image 195
夢のの夢 Avatar answered Sep 28 '22 05:09

夢のの夢


You can also use exists method:

  1. Create an object you're looking for and set desired fields.
  2. convert it to Example.
  3. Use repository's exists method.

    CarModel carModel = new CarModel();
    carModel.setRegno(regno);
    carModel.setName(name);
    repo.exists(Example.of(carModel));
    

This is a generic way, that does not require creating a bunch of methods in repository.

like image 23
user1729 Avatar answered Sep 28 '22 04:09

user1729