Getting Started with JPA and EntityManager

 so with the help of Query in previous tutorial were easy but over the period of time while we working on some complex query than it would be difficult to maintain the flow of query and understanding would be difficult than 

So Thats where JPA users have different apporoach

instead of Course Bean class we create Entity class with @Entity Annotation which will make that calss to Eneity Class

Step 1

@Entity

public class Course {

@Id

private long id;

@Column(name="name")

private String name;

@Column(name="author")

private String author;

// constructor, getter/setter, toString

}


Step 2

@Component

public class CourseCommandLineRunner implements CommandLineRunner {

@Autowired

CourseJPARepository courseJPARepository;


@Override

public void run(String... args) throws Exception {

courseJPARepository.insert(new Course(1, "Learn Java", "Khan Dev"));

courseJPARepository.insert(new Course(2, "Learn Spring Boot", "Irfan Khan"));

courseJPARepository.insert(new Course(3, "Learn Hibernate Boot", "Irfan Khan"));

courseJPARepository.deleteById(1);

System.out.println(courseJPARepository.findById(2));

System.out.println(courseJPARepository.findById(3));

courseJPARepository.insert(new Course(1, "AI technology", "Irfan"));

}


}


Step 3

@Repository

@Transactional

public class CourseJPARepository {


@PersistenceContext

private EntityManager entityManager;

public void insert(Course course) {

entityManager.merge(course);

}

public Course findById(long id) {

return entityManager.find(Course.class, id);

}

public void deleteById(long id) {

Course course = entityManager.find(Course.class, id);

entityManager.remove(course);

}

}


Comments

Popular posts from this blog

Introduction of RESTful Web Service

Learn JPA and Hibernate

Implementing Dynamic Filtering for Rest API