How can I set Datasource when I'm creating Hibernate SessionFactory?

后端 未结 8 386
星月不相逢
星月不相逢 2020-12-02 17:17

I\'m creating SessionFactory and I have my datasource as object in code where I\'m creating SessionFactory, but i cannot set datasource to Hibernate Configuration object. So

相关标签:
8条回答
  • 2020-12-02 18:22

    If you happen to have your DataSource stored in JNDI, then simply use:

    configuration.setProperty(
        "hibernate.connection.datasource",
        "java:comp/env/jdbc/yourDataSource");
    

    But if you use a custom data source provider like Apache DBCP or BoneCP and you don't want to use a dependency injection framework like Spring, then you may inject it on the StandardServiceRegistryBuilder before creating the SessionFactory:

    //retrieve your DataSource
    DataSource dataSource = ...;
    Configuration configuration = new Configuration()
        .configure();
    //create the SessionFactory from configuration
    SessionFactory sf = configuration
        .buildSessionFactory(
            new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties())
                //here you apply the custom dataSource
                .applySetting(Environment.DATASOURCE, dataSource)
                .build());
    

    Note that if you use this approach, you don't need to put the connection parameters in your hibernate.cfg.xml anymore. Here's an example of a compatible hibernate.cfg.xml file when using approach from above:

    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE hibernate-configuration PUBLIC
            "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
            "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
    <hibernate-configuration>
    
        <session-factory>
            <property name="hibernate.dialect">org.hibernate.dialect.MySQLInnoDBDialect</property>
            <property name="show_sql">false</property>
            <!-- your mappings to classes go here -->
        </session-factory>
    </hibernate-configuration>
    

    Code above tested on Hibernate 4.3.

    0 讨论(0)
  • 2020-12-02 18:22

    I used LocalContainerEntityManagerFactoryBean to create EntityManagerFactory instance at the configuration class.

    If it is required to set another DataSource, than it is possible to update it with entity manager factory instance at runtime:

    @Service("myService")
    public class MyService
    {
    ....
        @Autowired
        private LocalContainerEntityManagerFactoryBean emf;
    ....
        public void replaceDataSource(DataSource dataSource)
        {
            emf.setDataSource(dataSource);
            emf.afterPropertiesSet();
        }
    ....
    }
    

    It works with Hibernate 5.2.9 Final.

    0 讨论(0)
提交回复
热议问题