javahibernatehibernate-mapping

Hibernate Configuration for File Config via code


I'm using Hibernate 5 and I need to configure them using code. I have established the Connection. But the Entity classes are not mapped. So How can I do this.

Due to this I can't able to insert data into be. I got error Like a property inside embedded key is not found.

 public void initialize()
{
    configuration = new Configuration();
    setupPostgresDbConnectionProperties();

    while(!initilizeSessionFactory())
    {
        System.err.println("retrying to initilize session factory");
    }

}
public void setupPostgresDbConnectionProperties()
{
    configuration.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQLDialect");
    configuration.setProperty("hibernate.connection.driver_class", "org.postgresql.Driver");
    String dbUrl = String.format("jdbc:postgresql://localhost:%d/%s", appConfig.getDb_port(), appConfig.getDb_schema_name());
    configuration.setProperty("hibernate.connection.url", dbUrl);
    configuration.setProperty("hibernate.connection.username", appConfig.getDb_user_name());
    configuration.setProperty("hibernate.connection.password", appConfig.getDb_pass());
    configuration.setProperty("hibernate.hbm2ddl.auto", "update");

}
private void loadEntitiesClasses(String packageName)
{
    if(packageName == null || packageName.length() == 0)
    {
        packageName = "com.jhonny.SharePointReports";

        Set<Class<?>> entityClasses = EntityScanner.getEntityClasses(packageName);
        for(Class<?> entityClass : entityClasses)
        {

            configuration.addAnnotatedClass(entityClass);
            System.out.println("Registering Entity: " + entityClass.getSimpleName());
        }
    }
}

private boolean initilizeSessionFactory()
{
    try
    {
        ServiceRegistry serviceRegistry = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties())
                .build();

        Set<Class<?>> entityClasses = EntityScanner.getEntityClasses("com.jhonny.SharePointReports");
        MetadataSources metadataSources = new MetadataSources(serviceRegistry);
        for (Class<?> entityClass : entityClasses) {
            metadataSources.addAnnotatedClass(entityClass);
        }


        sessionFactory = metadataSources.buildMetadata().buildSessionFactory();

        System.out.println("Session Factory is initilized successFully");
        return true;
    }
    catch (Exception e)
    {
        System.err.println("error in Session Factory creation.\n error message = " + e.getMessage());
        e.printStackTrace();
    }
    return false;
}

Solution

  • Do check your project has the Spring-Boot-dev-tool dependency. If yes then the entity will be generated with the dev tool classLoader.

    After removing the dev tool dependency it works for me. Give it a shoot.

    ref this.