SpringJPA
-
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
- 持久化上下文的声明,配置 LocalContainerEntityManagerFactoryBean 的bean,属性配置 数据库连接,JPA实现等;
<bean id = "jpaVendorAdapter" class = "org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
<bean id = "entityManagerFactory" class =
"org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource" />
<!-- 指定Jpa持久化实现厂商类,这里以Hibernate为例 -->
<property name="jpaVendorAdapter" ref="jpaVendorAdapter" />
<property name="packagesToScan" value="com.dengh.*" />
<property name="jpaProperties">
<props>
<prop key="hibernate.dialect">org.hibernate.dialect.MySQL5InnoDBDialect</prop>
<prop key="hibernate.hbm2ddl.auto">update</prop>
<prop key="hibernate.show_sql">true</prop>
<prop key="hibernate.format_sql">true</prop>
</props>
</property>
</bean>
// 如果想把 Hibernate 或 JPA 异常,都转换成 spring 异常,需要配置
<bean id = "persistenceTranslation" class =
"org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"></bean>
- 实体对象的操作,是通过 EntityManager 接口定义的方法,persist(),merge(),remove(),find(),要求操作是针对被持久化上下文管理的对象;
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();
}
- 更多细节,参考:http://www.cnblogs.com/holbrook/archive/2012/12/30/2839842.html;
Spring Data
- dao 层接口,继承 JpaRepository,能够自动生成一些 curd 接口实现,对于自定义 sql 的需求,使用 @Query 来指定需要执行sql;
public interface SplitterRepository extends JpaRepository<Splitter,Long>{
@Query("select * from Splitter s where s.email like '%gmail.com'")
List<Splitter> findAllGmailSplitters();
}
- Jpa 自动生成的实现,是查找与接口名相同,后加 Impl 的类,如果存在,就添加自动生成的方法,如,自动生成的实现,会添加到 SplitterRepositoryImpl 中;