Java 使用JPARepository保存实体
我是一个新手。我有一个类StudentClient.java,在这里我使用Hibernate插入记录 我的问题是,如果我想使用JpaRepository,我该怎么做 我想插入记录,然后使用Jparepository保存实体。代码-Java 使用JPARepository保存实体,java,spring,hibernate,spring-data,spring-data-jpa,Java,Spring,Hibernate,Spring Data,Spring Data Jpa,我是一个新手。我有一个类StudentClient.java,在这里我使用Hibernate插入记录 我的问题是,如果我想使用JpaRepository,我该怎么做 我想插入记录,然后使用Jparepository保存实体。代码- public class StudentClient { public static void main(String[] args) throws Exception {
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();
}
}
}
如果您正在创建新的基于Spring的应用程序,那么应该使用Spring引导。对于基于SpringBoot的应用程序,您的繁重代码将不相关,因为SpringBoot+Spring+SpringData组合将为您完成这项工作
要开始熟悉Spring生态系统对持久性的支持,请查看 所以我可以使用setter方法插入记录,然后使用JPARepository保存ebtity,对吗?*实体。另一个问题:我可以在同一个类中使用jdbcTemplate和jparepository吗??可能吗?我需要使用jdbcTemplate执行某些DDL语句,还需要使用JpaRepository插入记录。是的,您只需使用所需数据填充实体并调用
JpaRepository.save
。我强烈建议不要将Hibernate与jdbcTemplate混合使用。用一个或另一个。