JPA without persistence.xml

后端 未结 3 1257
无人共我
无人共我 2021-01-03 11:40

I\'m trying to get started with using Guice Persist and JPA, which recommends using configuration via persistence.xml. Coming from a native Hibernate background where confi

3条回答
  •  轮回少年
    2021-01-03 11:59

    There is no need for persistence.xml if you are using a Spring version higher than 3.1 and you have already defined your entities classes.

    @Configuration
    @ComponentScan(basePackages = { "com.demoJPA.model" })
    @EnableTransactionManagement
    public class DemoJPAConfig {
    
        @Bean
        public DataSource dataSource() throws PropertyVetoException {
            ComboPooledDataSource dataSource = new ComboPooledDataSource();
            dataSource.setDriverClass("org.gjt.mm.mysql.Driver");
            dataSource.setJdbcUrl("jdbc:mysql://localhost:3306/cimto");
            dataSource.setUser("user");
            dataSource.setPassword("pass");
    
            return dataSource;
        }
    
        @Bean
        public LocalContainerEntityManagerFactoryBean entityManagerFactory() throws PropertyVetoException {
            LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
            em.setDataSource(dataSource());
            em.setJpaVendorAdapter(vendorAdapter());
            em.setPersistenceUnitName("cimtoPU");
            em.setJpaPropertyMap(getJpaProperties());
    
            return em;
        }
    
        public Map getJpaProperties() {
        return new HashMap();
        }
    
        @Bean
        public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
            JpaTransactionManager transactionManager = new JpaTransactionManager();
            transactionManager.setEntityManagerFactory(emf);
    
            return transactionManager;
        }
    
        public JpaVendorAdapter vendorAdapter() {
            HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
            vendorAdapter.setDatabase(Database.MYSQL);
        vendorAdapter.setDatabasePlatform("org.hibernate.dialect.MySQL5Dialect");
            vendorAdapter.setShowSql(true);
    
            return vendorAdapter;
        }
    }
    

    Note: com.demoJPA.model package must contain your entities classes.

提交回复
热议问题