Configure Spring applicationContext by taking advantage of other configuration files

1

I have the following hibernate.cfg.xml :

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
    "-//Hibernate/Hibernate Configuration DTD//EN"
    "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">

<hibernate-configuration>

    <!-- Configuração para a instância do SessionFactory -->
    <session-factory>

        <!-- Propriedades para o Hibernate -->
        <property name="hibernate.dialect">
            org.hibernate.dialect.MySQL5InnoDBDialect
        </property>
        <property name="hibernate.show_sql">
            true
        </property>
        <property name="hibernate.connection.provider_class">
            com.zaxxer.hikari.hibernate.HikariConnectionProvider
        </property>
        <property name="hibernate.current_session_context_class">
            thread
        </property>
        <property name="hibernate.generator_mappings">
            true
        </property>

        <!-- Propriedades para o Pool de Conexões HirakiCP -->
        <property name="hibernate.hikari.dataSourceClassName">
            com.mysql.jdbc.jdbc2.optional.MysqlDataSource
        </property>
        <property name="hibernate.hikari.dataSource.url">
            jdbc:mysql://localhost:3306/teste-database1?createDatabaseIfNotExist=true
        </property>
        <property name="hibernate.hikari.dataSource.user">
            root
        </property>
        <property name="hibernate.hikari.dataSource.password">
            admin123
        </property>
        <property name="hibernate.hikari.maximumPoolSize">
            10
        </property>
        <property name="hibernate.hikari.idleTimeout">
            30000
        </property>
        <property name="hibernate.hikari.dataSource.cachePrepStmts">
            true
        </property>
        <property name="hibernate.hikari.dataSource.prepStmtCacheSize">
            250
        </property>
        <property name="hibernate.hikari.dataSource.prepStmtCacheSqlLimit">
            2048
        </property>
        <property name="hibernate.hikari.dataSource.useServerPrepStmts">
            true
        </property>
        <property name="hibernate.hikari.dataSource.useLocalSessionState">
            true
        </property>
        <property name="hibernate.hikari.dataSource.useLocalTransactionState">
            true
        </property>
        <property name="hibernate.hikari.dataSource.maintainTimeStats">
            false
        </property>
        <property name="hibernate.hikari.dataSource.useUnbufferedInput">
            false
        </property>

        <!-- Mapeamento de classes -->
        <!-- <mapping package="org.sgct.model" /> -->
        <mapping class="org.teste.model.Usuario" />
        <mapping class="org.teste.model.Contato" />
        <mapping class="org.teste.model.Endereco" />

    </session-factory>

</hibernate-configuration>
  

Questions

1 - In the Spring configuration file (applicationContext.xml for example) instead of having to enter each property in this file, you can take advantage of settings of the hibernate.cfg.xml file using the following code snippet:

<bean id="sessionFactory"
    class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
    <property name="configLocation" value="classpath*:hibernate.cfg.xml" />
</bean>

But I do not know what properties it takes advantage of from the hibernate.cfg.xml file when using this code snippet. What I want to understand is what properties it takes (like perhaps class mapping snippets) in addition to the basic properties (dialect, class_provity, etc.) so I can supplement the snippet with properties it does not use.

2 - When configuring the connection pool (in my case I'm using HikariCP) is there similar way to take advantage of the configuration of another file as in the configuration section of hibernate that I presented in the previous question?

3 - I want to use JNDI in an xml file (Tomcat was the context.xml file) because in addition to Hibernate I will use Spring Security, but since I use Glassfish I do not know if This configuration that is in the HirakiCP project repository will work the same in Glassfish for the fact to be for Tomcat. I also do not know if all or part of the connection pool configuration will go to the JNDI configuration file.

4 - There is also the case of referencing the connection in the configuration section of Hibernate because as in my version of hibernate.cfg.xml that I put above I use the hibernate.connection.provider_class property but in this article the dataSource property is used. What is the difference between using one or the other? When JNDI is used which one of these?

    
asked by anonymous 27.07.2014 / 03:16

1 answer

2
  

TL; DR:

     
  • Use whatever you can / want from your application server
  •   
  • The more Application Server components you use, the simpler your configuration will be.
  •   
  • You do not need to repeat settings.
  •   
  • Almost everything that is configurable from hibernate.cfg.xml can be configured in Spring; keep the configuration in place that makes the most sense and where it can be best reused (e.g., a data source set in Spring can be used with JdbcTemplate ).
  •   

Here's a look at your questions:

  • While the Javadoc class it is not clear what features are leveraged, see that there are extra properties for loading mapping files ( setMappingDirectoryLocations , setMappingJarLocations , setMappingLocations , setMappingResources ). Spring will reuse the configuration of data source , transactions, etc., but you do not need to configure any of this in hibernate.cfg.xml .
  • Yes. See three:
  • In GlassFish you will configure a pool of connections in the console itself (which will be persisted in the domain.xml file, but this is not the case). Use GlassFish itself pool , do not worry about integrating an external pool . Additionally you would not even have to configure and use Hibernate if you do not want to. GlassFish already comes with EclipseLink, you just need to create a persistence.xml file that will already be in charge of making the libraries available to you (this is the main advantage of an App Server vs container as Tomcat). Of course you are free to set up and use Hibernate and enjoy your API if you want. In Spring there is little to be done since container will take care of pool and transactions:

    <!-- Obtém data source do GlassFish -->
    <jee:jndi-lookup id="datasSource" 
         jndi-name="jdbc/dataSourceName" expected-type="javax.sql.DataSource" />
    <!-- Detecta e configura o provedor de transações do GlassFish -->
    <tx:jta-transaction-manager/>
    

    And then your settings for LocalSessionFactoryBean or - if you prefer the pure JPA path - use the LocalContainerEntityManagerFactoryBean (see this article for details). Both consume dataSource and transactionManager .

    • In the case of Hibernate, you can either skip the data source setting so that it uses hibernate.cfg.xml setting this setting from hibernate.cfg.xml and configure everything by Spring; you can also choose between settings with or without JTA (since GlassFish provides the service, it does not cost anything). For more details see the methods setDataSource " and setJtaTransactionManager "

    • Similarly for JPA you can also skip the data source setting so that Spring uses what was specified in persistence.xml , or adopt the opposite strategy, and delete the configuration relative to that of persistence.xml , configuring only by Spring (for more details see the methods setDataSource " and setJtaDataSource .

  • This is just a Hibernate property, if you use the data source of the connection pool of GlassFish you will not have to worry about it. Imagining that you want to use an external pool and do not want to set this property directly on hibernate.cfg.xml you can also configure it by Spring:

    • Java annotation setting (see article example ):

      Properties hibernateProperties() {
          return new Properties() {
              {
                  // Demais propriedades
                  setProperty("hibernate.connection.provider_class", env.getProperty("com.zaxxer.hikari.hibernate.HikariConnectionProvider"));
              }
          };
      } 
      
    • xml configuration:

      <bean id="sessionFactory"
          class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
          <property name="configLocation" value="classpath*:hibernate.cfg.xml" />
              <property name="hibernateProperties">
              <props>
                  <property name="hibernate.connection.provider_class" 
                      value="com.zaxxer.hikari.hibernate.HikariConnectionProvider" />
              </props>
      </bean>
      
  • 27.07.2014 / 20:31