I have tried to load the url, user and password in different ways, but I can't get it to connect.
Currently I use a file called config.properties from where I retrieve the credentials to connect to the database.
Persistence file
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.2"
xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
<persistence-unit name="tienda" transaction-type="RESOURCE_LOCAL">
<class>com.chisrra.tienda.entities.Producto</class><!--opcional-->
<properties>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<!-- Cargamos las propiedades de la base de datos desde el archivo database.properties -->
<property name="javax.persistence.jdbc.url" value="${tienda.db.url}"/>
<property name="javax.persistence.jdbc.user" value="${tienda.db.user}"/>
<property name="javax.persistence.jdbc.password" value="${tienda.db.password}"/>
</properties>
</persistence-unit>
</persistence>
Class where I retrieve properties
public class JPAUtils {
private static final EntityManagerFactory FACTORY = Persistence.createEntityManagerFactory("tienda");
static {
Properties properties = new Properties();
String path = "src/config.properties";
try (InputStream inputStream = new FileInputStream(path)) {
properties.load(inputStream);
String url = properties.getProperty("tienda.db.url");
String user = properties.getProperty("tienda.db.user");
String password = properties.getProperty("tienda.db.password");
} catch (FileNotFoundException e) {
throw new RuntimeException("No se encontro el archivo config.properties: " + e.getMessage(),e);
} catch (IOException e) {
throw new RuntimeException("No se pudieron cargar las propiedades del archivo config.properties: " + e.getMessage(),e);
}
}
private static Properties createProperties(String url, String user, String password) {
Properties properties = new Properties();
properties.setProperty("javax.persistence.jdbc.url", url);
properties.setProperty("javax.persistence.jdbc.user", user);
properties.setProperty("javax.persistence.jdbc.password", password);
return properties;
}
public static EntityManager getentityManager() {
return FACTORY.createEntityManager();
}
}