Retrieving a Java Object with JPA

류홍규·2023년 7월 5일
0

JPA

목록 보기
4/8

- Read objects

💎 Retrieving a Java Object with JPA

Student myStudent = entityManager.find(Student.class, 1);
  • Student: Entity class
  • 1: Primary key
  • if not found, returns null

⚾ Step1: Add new method to DAO interface

package com.hongJpa.hongdemo.dao;

import com.hongJpa.hongdemo.entity.Student;

public interface StudentDAO {
    // create
    void save(Student theStudent);

    //retrieve
    Student findById(Integer id);
}

⚾ Step2: Define DAO implementation

package com.hongJpa.hongdemo.dao;

import com.hongJpa.hongdemo.entity.Student;
import jakarta.persistence.EntityManager;
import jakarta.transaction.Transactional;
import org.springframework.stereotype.Repository;

@Repository
public class StudentDAOImpl implements StudentDAO{
    // define field for entity manager
    private final EntityManager entityManager;

    // inject entity manager using constructor injection
    public StudentDAOImpl(EntityManager entityManager) {
        this.entityManager = entityManager;
    }

    // implement save method
    @Override
    @Transactional
    public void save(Student theStudent) {
        entityManager.persist(theStudent);
    }

    // implement retrieve
    @Override
    public Student findById(Integer id) {
        return entityManager.find(Student.class, id);
    }
}

⚾ 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);
		};
	}

	private void readStudent(StudentDAO studentDAO) {
		// create a student object
		System.out.println("creating a new student object ....");
		Student tempStudent = new Student("puppy", "duck", "puppy@naver.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);
	}


profile
공대생의 코딩 정복기

0개의 댓글

관련 채용 정보