Mini-Project - Java Full Stack Developer - JPA_FP Hands-On
1. JPADemo.java
package frescojpa;
import javax.persistence.*;
import frescojpa.Student;
import java.util.*;
public class JPADemo {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("$objectdb/students.odb"); //creating an entitymanagerfactory instance with the given database
EntityManager em=emf.createEntityManager(); //enitity manager object creation
em.getTransaction().begin(); //starting the transactions
Student s1=new Student(); //creating 3 student objects
Student s2=new Student();
Student s3=new Student();
s1.setStudentName("Ramesh"); //setting the names of 3 students as given in question
s2.setStudentName("Ali");
s3.setStudentName("John");
em.persist(s1); //storing them into database
em.persist(s2);
em.persist(s3);
em.getTransaction().commit(); //committing the transactions
List<Student> students= em.createQuery("Select st from Student st").getResultList(); //fetching the students data from database
//System.out.print("size is:"+students.size());
for(int i=0;i<students.size();i++){
System.out.println(students.get(i).studentName+"'s roll number is "+students.get(i).studentRollNumber);
}
}
}
2. Student.java
package frescojpa;
import java.io.Serializable;
import javax.persistence.*;
@Entity //defining student class as the entity class
public class Student implements Serializable {
@Id
@GeneratedValue(strategy=GenerationType.AUTO) // primary key generation as auto generated
int studentRollNumber;
String studentName;
Student(){ //default constructor
}
Student(int studentRollNumber,String studentName){ //parameterized constructor
this.studentName = studentName;
this.studentRollNumber=studentRollNumber;
}
//getters and setters
public String getStudentName() {
return studentName;
}
public void setStudentName(String studentName) {
this.studentName = studentName;
}
public int getStudentRollNumber() {
return studentRollNumber;
}
public void setStudentRollNumber(int studentRollNumber) {
this.studentRollNumber = studentRollNumber;
}
}
can you plz provide the hands on solution for the course 63431
ReplyDelete