sql >> Base de Datos >  >> RDS >> PostgreSQL

Configurar JPA/Hibernate/PostgreSQL sin XML

Coloque los siguientes fragmentos en una clase anotada con @Configuration y @EnableTransactionManagement

Hibernate/JPA (edite la cadena packagesToScan):

@Bean
public LocalContainerEntityManagerFactoryBean entityManagerFactory() {
    LocalContainerEntityManagerFactoryBean em = new LocalContainerEntityManagerFactoryBean();
    em.setDataSource(dataSource());
    em.setPackagesToScan(new String[] { "com.XY.model" });
    JpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter();
    em.setJpaVendorAdapter(vendorAdapter);
    em.setJpaProperties(additionalProperties());
    return em;
}

Properties additionalProperties() {
    Properties properties = new Properties();
    properties.setProperty("hibernate.hbm2ddl.auto", "update");
    properties.setProperty("hibernate.dialect", "org.hibernate.dialect.PostgreSQL9Dialect");
    properties.setProperty("hibernate.show_sql", "true");
    return properties;
}

Fuente de datos (editar nombre de usuario, contraseña y dirección de host):

@Bean
public DataSource dataSource() {
    DriverManagerDataSource dataSource = new DriverManagerDataSource();
    dataSource.setDriverClassName("org.postgresql.Driver");
    dataSource.setUrl("jdbc:postgresql://localhost:port/DB_NAME");
    dataSource.setUsername("root");
    dataSource.setPassword("");
    return dataSource;
}

Administrador de transacciones:

@Bean
public PlatformTransactionManager transactionManager(EntityManagerFactory emf) {
    JpaTransactionManager transactionManager = new JpaTransactionManager();
    transactionManager.setEntityManagerFactory(emf);
    return transactionManager;
}