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);
}
}
interface ProgramDao extends JpaRepository<CarModel, Integer> {
boolean existsByRegnoAndName(String regno, String name);
}
You can also use exists
method:
Example
.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With