Retrieving a Java Object with JPA
// retrieve/read from database using the primary key
// in this example, retrieve Student with primary key: 1
Student myStudent = entityManager.find(Student.class, 1);
Development Process
- Add new method to DAO interface
- Add new method to DAO implementation
- Update main app
Step 1: Add new method to DAO interface
public interface StudentDAO {
...
Student findById(Integer id);
}
Step 2: Define DAO implementation
Step 3: Update main app
@SpringBootApplication
public class CruddemoApplication {
public static void main(String[] args) {
SpringApplication.run(CruddemoApplication.class, args);
}
@Bean
public CommandLineRunner commandLineRunner(StudentDAO studentDAO){
return runner-> {
// createStudent(studentDAO);
readStudent(studentDAO);
};
}
private void readStudent(StudentDAO studentDAO) {
// create a student object
System.out.println("Creating new student object...");
Student tempStudent = new Student("Daffy","Duck", "@daffy@gmail.com");
// save the student
System.out.println("Saving the student...");
studentDAO.save(tempStudent);
// display id of the saved student
int theId = tempStudent.getId();
System.out.println("Saved student. Generated id: " + theId);
// retrieve student based on the id: primary key
System.out.println("Retrieving student with id: " + theId);
Student myStudent = studentDAO.findById(theId);
// display student
System.out.println("Found the student: " + myStudent);
}
....
}
댓글남기기