2016-10-12 8 views
0

私はJpaRepositoryを初めて使用しています。 StudentClient.javaというクラスがあります.Hibernateを使ってレコードを挿入しています。JPARepositoryを使用してエンティティを保存

私の質問は、私がJpaRepositoryを使いたいのですが、どうすればいいですか?

レコードを挿入し、Jparepositoryを使用してエンティティを保存します。コード:

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(); 
     } 
    } 
} 

答えて

1

新しいSpringベースのアプリケーションを作成する場合は、SpringBootを使用する必要があります。 Spring Boot + Spring + Spring Dataコンボがあなたのために行うので、SpringBootベースのアプリケーションの場合、重い持ち上げコードは関係ありません。

永続性のためのSpringエコシステムのサポートに慣れるには、this Spring Data JPA guideをご覧ください。

+0

私はsetterメソッドを使用してレコードを挿入し、JPARepositoryを使用して優劣を保存できますか? –

+0

*エンティティ。もう一つの質問:jdbcTemplateとjparepositoryを同じクラスで使うことができますか?出来ますか? jdbcTemplateを使用して特定のDDL文を実行する必要があります。また、JpaRepositoryを使用してレコードを挿入する必要があります。 –

+0

はい、Entityに必要なデータを入力し、 'jpaRepository.save'を呼び出します。 – luboskrnac

関連する問題