ORM 框架:springJPA

SpringJPA

  1. Spring JPA 封裝了統一的持久化接口,底層實現上仍是 hibernate,openJpa 等 ORM 框架;

  2. JPA 維護一個持久化上下文 Persistence Context,負責管理實體的生命週期,涉及的類,主要有 Persistence,EntityManagerFactory,EntityManager,EntityTransaction,Query 等;

  3. 實體對象與表的映射,是通過 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
  1. 持久化上下文的聲明,配置 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>
  1. 實體對象的操作,是通過 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();
	} 
  1. 更多細節,參考:http://www.cnblogs.com/holbrook/archive/2012/12/30/2839842.html;

Spring Data

  1. 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();
 	}
  1. Jpa 自動生成的實現,是查找與接口名相同,後加 Impl 的類,如果存在,就添加自動生成的方法,如,自動生成的實現,會添加到 SplitterRepositoryImpl 中;
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章