Mixing JPA annotations and XML configuration

前端 未结 3 1307
萌比男神i
萌比男神i 2021-01-14 17:44

I have a fairly large (new) project in which we have annotated many domain classes with JPA mappings. Now it is time to implement many named queries -- some entities may ha

3条回答
  •  感动是毒
    2021-01-14 18:30

    I know this is a little late but I came across this and in my project I have been using org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean (in the Spring container, of course). I really like JPA and I am sure it will make life easier but I want to use my domain classes in a project that does not use Hibernate, JPA, Spring or any of that good stuff. We decided that it would be better to leave some of our domain classes free of Java Persistence annotations if possible.

    I know this is a simple thing that is probably obvious to many but it took me a while. Below is my example POJO note that I have no annotations:

    package mypackage.domain;
    public class Profile {
        private Long id;
        private String friendlyName;
        public Long getId() { return id; }
        public void setId(Long id) { this.id = id; }
        public String getFriendlyName() { return friendlyName; }
        public void setFriendlyName(String friendlyName)
            { this.friendlyName = friendlyName; }
    }
    

    In the src/main/java/mypackage/domain/ directory (if you are using Maven) you should put a nice, traditional XML mapping file (Profile.hbm.xml):

    
    
        
            
        
        
    
    
    

    Provided you are using Hibernate 4.0.0.CR3 that should be ok, The Spring configuration (I am using 3.0.6.RELEASE) can then look like a typical JPA Hibernate configuration:

    
        
        
        
            
            
        
        
    
    

    META-INF/persistence.xml is pretty basic and, for completeness here it is:

    
        
            org.hibernate.ejb.HibernatePersistence
            mypackage.domain.Profile
        
    
    

    Of course, although I am using JPA the mapping configuration is Hibernate specific and so I have tied myself to Hibernate in this project, since I am using pure JDBC in the legacy sister project I do not see it as such a drawback.

提交回复
热议问题