Reputation: 122
I am new to JpaRepository. I have a class StudentClient.java, where I am inserting records using Hibernate.
My question is , if I want to use JpaRepository, how can I do this??
I want to insert the records and then save the entity using Jparepository. Code-
public class StudentClient
{
public static void main(String[] args) throws Exception
{
// create Configuration class, Configuration object parses and reads .cfg.xml file
Configuration c = new Configuration();
c.configure("/hibernate.cfg.xml");
// SessionFactory holds cfg file properties like, driver props and hibernate props and mapping file
SessionFactory sf=c.buildSessionFactory();
// create one session means Connection
Session s = sf.openSession();
// before starting save(),update(), delete() operation we need to start TX, starting tx mean con.setAutoCommit(false);
Transaction tx = s.beginTransaction();
try
{
Student std1=new Student();
std1.setSid(100);
std1.setSname("S N Rao");
std1.setSmarks(78);
std1.setSjoindate(new Date());
Student std2=new Student();
std2.setSid(101);
std2.setSname("Sumathi");
std2.setSmarks(52);
std2.setSjoindate(new Date());
s.save(std1); // stmt.addBatch("INSERT INTO school VALUES (....)");
s.save(std2);
s.flush(); // stmt.executeBatch()
tx.commit(); // con.commit();
System.out.println("Records inserted");
}
catch(Exception e)
{
tx.rollback(); // con.rollback();
}
}
}
Upvotes: 2
Views: 8841
Reputation: 24591
If you are creating new Spring based application, you should use Spring Boot. For Spring Boot based application your heavy lifting code will not be relevant, because Spring Boot + Spring + Spring Data combo will do it for you.
To start familiarize yourself to Spring ecosystem support for persistence, take a look at this Spring Data JPA guide.
Upvotes: 2