本文共 2165 字,大约阅读时间需要 7 分钟。
Spring JPA 封装了统一的持久化接口,底层实现上仍是 hibernate,openJpa 等 ORM 框架;
JPA 维护一个持久化上下文 Persistence Context,负责管理实体的生命周期,涉及的类,主要有 Persistence,EntityManagerFactory,EntityManager,EntityTransaction,Query 等;
实体对象与表的映射,是通过 annotion 或者 xml 形式定义,注解有 @Entity,@Table ,@Id,@GeneratedValue,@Column,其中 id 的生成策略有:
1.GeneratorType.AUTO ,由JPA自动生成 2.GenerationType.IDENTITY,使用数据库的自增长字段,需要数据库的支持(如SQL Server、MySQL、DB2、Derby等) 3.GenerationType.SEQUENCE,使用数据库的序列号,需要数据库的支持(如Oracle) 4.GenerationType.TABLE,使用指定的数据库表记录ID的增长 需要定义一个TableGenerator,在@GeneratedValue中引用 JPA和Hibernate主键注解参考文章: http://blog.csdn.net/z69183787/article/details/36048147 http://blog.csdn.net/oathevil/article/details/7227699
// 如果想把 Hibernate 或 JPA 异常,都转换成 spring 异常,需要配置 org.hibernate.dialect.MySQL5InnoDBDialect update true true
public void static main(){ ApplicationContext ctx = new ClassPathXmlApplicationContext("spring-jpa.xml"); JpaDao dao = ctx.getBean(JpaDao.class); EntityManager entityManager = ctx.getBean(EntityManagerFactory.class).createEntityManager(); EntityTransaction t = entityManager.getTransaction(); t.begin(); StudentOrm s = new StudentOrm();s.setName("liud");s.setAge(25);s.setLevel(1); entityManager.persist(s); t.commit(); entityManager.close(); }
public interface SplitterRepository extends JpaRepository{ @Query("select * from Splitter s where s.email like '%gmail.com'") List findAllGmailSplitters(); }