Sunday, June 10, 2012

Simple JPA Example

     In ySchool-mini week 4 assignment I did a simple JPA ( Java Persistence API) Project. In this project I used the same scenario (scenario-3) that was used in assignment-2 and  assignment-3.

What is JPA?

      The Java Persistence API  is a Java specification for accessing, persisting, and managing data between Java objects / classes and a relational database.

JPA

Scenario 3: 
a) Student marks can be entered entered in the following way
Student Name (StudentName loaded in ComboBox), Grade (1-13 ComboBox), Subject, Marks
b) User can enter these values and click "Add"
c) Here all those fields are mandatory and marks cannot be more than 100
d) System should validate those fields and show it in the response page

The source code is uploaded  in github.
https://github.com/Niroshan06/yschool_mini_nirosh_ass4

After create the database the netbeans was look like this.

Student database


  • Then I created a maven project ( yschool_mini_nirosh_ass4 ) in netbeans. Project structure was look like this.
Project structure
 
  • In index.jsp I added code for main page.
Main page

  • Then I created an entity class name "StudentsMarks".
              Right click on SourcePackages(jsf.yschool_mini_nirosh_ass4) ---> New --->
              Entity Class.. --->
 
Creating an Entity class.
                     
                Next ---> select "student" as Database Connection ---> finish.


Setup database connection.

  • In this Entity class (StudentsMarks.java) I added four variables String name, String grade, String subject and int marks. Then created getter and setter methods for this four variables.
 
  •  Then I created a Servlet, name "controller".
               Right click on SourcePackages(jsf.yschool_mini_nirosh_ass4) ---> New --->
               Servlet
 
Servlet

  • In controller.java I added a method "persist"
persist method
  • Then I wrote some codes in dopost method. You can get full codes from github.
           https://github.com/Niroshan06/yschool_mini_nirosh_ass4

  • When I run the project....



  • After click Add button a table "studentsmarks" was created automatically in the database "student".
              
studentsmarks table
 
  • To view the table values...
               Right click on the table (studentsmarks) ---> View Data...

Values in the table



No comments:

Post a Comment