Query Language for retrieving objects
Similar in concept to SQL
- where, like, order by, join ...
JPQL is based on entity name and entity fields
TypedQuery<Student> theQuery = entityManager.createQuery("FROM Student", Student.class);
List<Student> students = theQuery.getResultList();
All JPQL syntax is based on entity name and entityfields
TypedQuery<Student> theQuery = entityManager.createQuery("FROM Student WHERE lastName = 'ryu'", Student.class);
List<Student> students = theQuery.getResultList();
TypedQuery<Student> theQuery = entityManager.createQuery("FROM Student WHERE email LIKE '%naver.com'", Student.class);
TypedQuery<Student> theQuery = entityManager.createQuery("FROM Student WHERE lastName = :ryu", Student.class);
theQuery.setParameter("ryu", theLastName);
return theQuery.getResultList();
JPQL Named Parameters are prefixed with a colon :
this
as a placeholder that is filled in laterStep1: Add new method to DAO interface
public interface StudentDAO {
// create
void save(Student theStudent);
//retrieve
Student findById(Integer id);
// query
List<Student> findAll();
// query LastName
List<Student> findByLastName(String theLastName);
}
Step2: Add new method to DAO implementation
@Override
public List<Student> findAll() {
// create query
TypedQuery<Student> theQuery = entityManager.createQuery("FROM Student", Student.class);
// return query results
return theQuery.getResultList();
}
@Override
public List<Student> findByLastName(String theLastName) {
// create query
TypedQuery<Student> theQuery = entityManager.createQuery(
"FROM Student WHERE lastName=:theData", Student.class);
// set query parameters
theQuery.setParameter("theData", theLastName);
// return query results
return theQuery.getResultList();
}
Step3: Update main app
@SpringBootApplication
public class HongdemoApplication {
public static void main(String[] args) {
SpringApplication.run(HongdemoApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(StudentDAO studentDAO) {
return runner -> {
// createStudent(studentDAO);
// createMultipleStudent(studentDAO);
// readStudent(studentDAO);
// queryForStudents(studentDAO);
queryForStudentsByLastName(studentDAO);
};
}
private void queryForStudentsByLastName(StudentDAO studentDAO) {
// get a List of students
List<Student> theStudents = studentDAO.findByLastName("Ryu");
// display list of students
theStudents
.forEach(System.out::println);
}
private void queryForStudents(StudentDAO studentDAO) {
// get a List of students
List<Student> theStudents = studentDAO.findAll();
// display list of students
theStudents
.forEach(System.out::println);
}