Setting properties programmatically in Hibernate

前端 未结 5 916
别那么骄傲
别那么骄傲 2020-11-30 11:27

How can I ensure that all properties are loaded from hibernate.cfg.xml, then add additional properties programmatically? I saw the following code snippet but it looks like a

5条回答
  •  栀梦
    栀梦 (楼主)
    2020-11-30 11:34

    import org.hibernate.SessionFactory;
    import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
    import org.hibernate.cfg.Configuration;
    public class HibernateUtil {
      private static SessionFactory sessionFactory;
    
      static {
        Configuration configuration = new Configuration();
    
        configuration.addAnnotatedClass (org.gradle.Person.class);
        configuration.setProperty("connection.driver_class","com.mysql.jdbc.Driver");
        configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/hibernate");                                
        configuration.setProperty("hibernate.connection.username", "root");     
        configuration.setProperty("hibernate.connection.password", "root");
        configuration.setProperty("dialect", "org.hibernate.dialect.MySQLDialect");
        configuration.setProperty("hibernate.hbm2ddl.auto", "update");
        configuration.setProperty("show_sql", "true");
        configuration.setProperty(" hibernate.connection.pool_size", "10");
    
        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
        sessionFactory = configuration.buildSessionFactory(builder.build());
      }
    
      public static SessionFactory getSessionFactory() {
         return sessionFactory;
      }
    } 
    

    Using .configure() makes Hibernate to look for the hibernate.cfg.xml file. So if you don't want to use the hibernate.cfg.xml file, don't use .configure().

提交回复
热议问题