Spring JPA and persistence.xml

后端 未结 5 1805
自闭症患者
自闭症患者 2020-12-04 20:08

I\'m trying to set up a Spring JPA Hibernate simple example WAR for deployment to Glassfish. I see some examples use a persistence.xml file, and other examples do not. Some

5条回答
  •  没有蜡笔的小新
    2020-12-04 20:25

    If anyone wants to use purely Java configuration instead of xml configuration of hibernate, use this:

    You can configure Hibernate without using persistence.xml at all in Spring like like this:

    @Bean
    public LocalContainerEntityManagerFactoryBean entityManagerFactoryBean()
    {
    Map properties = new Hashtable<>();
    properties.put("javax.persistence.schema-generation.database.action",
    "none");
    HibernateJpaVendorAdapter adapter = new HibernateJpaVendorAdapter();
    adapter.setDatabasePlatform("org.hibernate.dialect.MySQL5InnoDBDialect"); //you can change this if you have a different DB
    LocalContainerEntityManagerFactoryBean factory = new LocalContainerEntityManagerFactoryBean();
    factory.setJpaVendorAdapter(adapter);
    factory.setDataSource(this.springJpaDataSource());
    factory.setPackagesToScan("package name");
    factory.setSharedCacheMode(SharedCacheMode.ENABLE_SELECTIVE);
    factory.setValidationMode(ValidationMode.NONE);
    factory.setJpaPropertyMap(properties);
    return factory;
    }
    

    Since you are not using persistence.xml, you should create a bean that returns DataSource which you specify in the above method that sets the data source:

    @Bean
    public DataSource springJpaDataSource()
    {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setUrl("jdbc:mysql://localhost/SpringJpa");
    dataSource.setUsername("tomcatUser");
    dataSource.setPassword("password1234");
    return dataSource;
    }
    

    Then you use @EnableTransactionManagement annotation over this configuration file. Now when you put that annotation, you have to create one last bean:

    @Bean
    public PlatformTransactionManager jpaTransactionManager()
    {
    return new JpaTransactionManager(
    this.entityManagerFactoryBean().getObject());
    }
    

    Now, don't forget to use @Transactional Annotation over those method that deal with DB.

    Lastly, don't forget to inject EntityManager in your repository (This repository class should have @Repository annotation over it).

提交回复
热议问题