Let's now create the Course entity. Right-click on the project and select the JPA Tools | Generate Tables from Entities menu:
Make sure that CourseMgmtDBConnection is selected (refer to the Configuring JPA section of Chapter 7, Creating JEE Applications with EJB, for configuring a MySQL database connection in Eclipse) and that List generated classes in persistence.xml is selected. Click Next on this and the next page. On the Customize Defaults page, select identity as the Key generator and set the package name as packt.jee.course_management_jpa.entity:
Click Next. Verify the entity class name and the other details:
Click Finish. The Course entity class will be created in the package selected:
//skipped imports @Entity @Table(name="COURSE") @NamedQuery(name="Course.findAll", query="SELECT c FROM Course c") public class Course implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy=GenerationType.IDENTITY) private int id; private int credits; private String name; @Column(name="teacher_id") private int teacherId; //skipped setter and getters }
Note that the wizard has also created the named query to get all the courses from the table.
We now need to create EntityManagerFactory so that EntityManager can be created from it (refer to the JPA concepts section in Chapter 4, Creating JEE Database Applications). We will create a Spring bean/component to create and store EntityManagerFactory. Furthermore, we will inject (autowire) this component into the DAO class.
Create the JPAEntityFactoryBean class in the packt.jee.course_management_jpa.entity package:
//skipped imports @Component public class JPAEntityFactoryBean { EntityManagerFactory entityManagerFactory; @PostConstruct public void init() { entityManagerFactory = Persistence.createEntityManagerFactory("CourseManagementSpringMVCJPA"); } public EntityManagerFactory getEntityManagerFactory() { return entityManagerFactory; } }
In the constructor of the class, we create EntityManagerFactory. The argument to createEntityManagerFactory is the name of the persistence unit, as specified in persistence.xml.