hongDemoApp <---> Student DAO <---> database
Student DAO <----> Entity Manager <----> datasource <->database
public interface StudentDAO {
void save(Student theStudent);
// 여기서 Student는 JPA 엔터티
}
public class StudentDAOImpl implements StudentDAO {
private EntityManager entityManager;
// Inject the entity manager
@Autowired
public StudentDAOImpl(EntityManager entityManager) {
this.entityManager = entityManager;
}
// save the Java Object
@Override
public void save(Student theStudent) {
entityManager.persist(theStudent);
}
}
⚾<1. StudentDAO>
package com.hongJpa.hongdemo.dao;
import com.hongJpa.hongdemo.entity.Student;
public interface StudentDAO {
void save(Student theStudent);
}
⚾<2. StudentDAOImpl>
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);
}
}
⚾<3. 실행>
package com.hongJpa.hongdemo;
import com.hongJpa.hongdemo.dao.StudentDAO;
import com.hongJpa.hongdemo.entity.Student;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
@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);
};
}
private void createStudent(StudentDAO studentDAO) {
// create the student object
System.out.println("Creating new Student object...");
Student tempStudent = new Student("hongkyu", "Ryu", "minsubrother@naver.com");
// save the student object
System.out.println("saving the students");
studentDAO.save(tempStudent);
// display id of the saved student
System.out.println("saved Student Generated id: " + tempStudent.getId());
}
}
⚾<4.결과>