Is there a way to change the JPA fetch type on a method?

后端 未结 4 452
面向向阳花
面向向阳花 2020-12-09 10:16

Is there a way to change the JPA fetch type on a single method without editing the entity object?

I have a shared ORM layer consisting of JPA entity

4条回答
  •  无人及你
    2020-12-09 10:58

    In JPA the Fetch mode is specified on each persistence attribute, either through an annotation or in an xml mapping file.

    So a JPA vendor agnostic way to accomplish your goal is to have separate mapping file for each DAO layer. Unfortunately this will require a separate PersistenceUnit for each mapping file, but you can at least share the same entity classes and the same JPQL query.

    Code skeletons follow.

    persistence.xml :

    
        
            orm-eager.xml
        
    
        
            orm-lazy.xml
        
    
    

    orm-eager.xml :

    
        
            
                
            
         
    
    

    orm-lazy.xml :

    
        
            
                
            
         
    
    

    Then it's just a matter of creating an EntityManagerFactory for the appropriate persistence-unit in your DAO layers.

    Actually you don't need two mapping files, you could specify either LAZY or EAGER as an annotation in the Entity and then specify the opposite in an xml mapping file (you'll still want two persistence-units though).

    Might be a little more code than the Hibernate solution above, but your application should be portable to other JPA vendors.

    As an aside, OpenJPA provides similar functionality to the Hibernate solution above using FetchGroups (a concept borrowed from JDO).

    One last caveat, FetchType.LAZY is a hint in JPA, the provider may load the rows eagerly if needed.

    Updated per request.

    Consider an entity like this :

    @Entity 
    public class ErrorCode { 
        //  . . . 
        @OneToMany(fetch=FetchType.EAGER)  // default fetch is LAZY for Collections
        private Collection myCollection; 
        // . . .
    }
    

    In that case you'd still need two persistence units, but you'll only need orm-lazy.xml. I changed the field name to reflect a more realistic scenario (only collections and blobs use FetchType.LAZY by default). So the resulting orm-lazy.xml might look like this :

    
        
            
                
            
         
    
    

    And persistence.xml will look like this :

    
        
           
        
    
        
            
            orm-lazy.xml
        
    
    

提交回复
热议问题