Created
December 22, 2020 14:28
-
-
Save LeoPFreitas/95d06534d81080758e9de5002da88c1d to your computer and use it in GitHub Desktop.
Hibernate configuration file for Postgresql 9.4 or later
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class HibernateUtil { | |
private static StandardServiceRegistry standardServiceRegistry; | |
private static SessionFactory sessionFactory; | |
static { | |
StandardServiceRegistryBuilder registryBuilder = new StandardServiceRegistryBuilder(); | |
Map<String, String> dbSettings = new HashMap<>(); | |
dbSettings.put(Environment.URL, "jdbc:postgresql://localhost/dbname"); | |
dbSettings.put(Environment.USER, "user"); | |
dbSettings.put(Environment.PASS, "pass"); | |
dbSettings.put(Environment.DRIVER, "org.postgresql.Driver"); | |
dbSettings.put(Environment.DIALECT, "org.hibernate.dialect.PostgreSQL82Dialect"); | |
registryBuilder.applySettings(dbSettings); | |
standardServiceRegistry = registryBuilder.build(); | |
MetadataSources sources = new MetadataSources(standardServiceRegistry); | |
Metadata metadata = sources.getMetadataBuilder().build(); | |
sessionFactory = metadata.getSessionFactoryBuilder().build(); | |
} | |
public static SessionFactory getSessionFactory() { | |
return sessionFactory; | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Main { | |
public static void main(String[] args) { | |
try(Session session = HibernateUtil.getSessionFactory().openSession()){ | |
String sql = "SELECT VERSION();"; | |
String result = (String) session.createNativeQuery(sql).getSingleResult(); | |
System.out.println("Postgres version is: "); | |
System.out.println(result); | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment