The DAO Pattern in Java (#4372)

* Initial Commit

* Rename persistence.xml file

* Update JpaEntityManagerFactory.java

* Update pom.xml

* Update JpaEntityManagerFactory.java

* Update JpaEntityManagerFactory.java

* Update pom.xml

* Update persistence.xml
This commit is contained in:
Alejandro Gervasio 2018-05-31 21:46:28 -03:00 committed by KevinGilmore
parent f898fe9730
commit cfa5f07c96
5 changed files with 214 additions and 18 deletions

View File

@ -50,18 +50,18 @@
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.11</version>
<scope>test</scope>
</dependency>
<dependency>
<version>6.0.6</version>
<type>jar</type>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.grep4j</groupId>
<artifactId>grep4j</artifactId>
<version>${grep4j.version}</version>
</dependency>
<dependency>
<groupId>com.googlecode.grep4j</groupId>
<artifactId>grep4j</artifactId>
<version>${grep4j.version}</version>
</dependency>
</dependencies>
<properties>

View File

@ -1,5 +1,6 @@
package com.baeldung.daopattern.application;
import com.baeldung.daopattern.config.JpaEntityManagerFactory;
import com.baeldung.daopattern.daos.Dao;
import com.baeldung.daopattern.daos.JpaUserDao;
import com.baeldung.daopattern.entities.User;
@ -21,17 +22,17 @@ public class UserApplication {
getAllUsers().forEach(user -> System.out.println(user.getName()));
}
private static class JpaUserDaoHolder {
private static final JpaUserDao jpaUserDao = new JpaUserDao(new JpaEntityManagerFactory().getEntityManager());
}
public static Dao getJpaUserDao() {
if (jpaUserDao == null) {
EntityManager entityManager = Persistence.createEntityManagerFactory("user-unit").createEntityManager();
jpaUserDao = new JpaUserDao(entityManager);
}
return jpaUserDao;
return JpaUserDaoHolder.jpaUserDao;
}
public static User getUser(long id) {
Optional<User> user = getJpaUserDao().get(id);
return user.orElse(new User("Non-existing user", "no-email"));
return user.orElseGet(()-> {return new User("non-existing user", "no-email");});
}
public static List<User> getAllUsers() {

View File

@ -0,0 +1,65 @@
package com.baeldung.daopattern.config;
import com.baeldung.daopattern.entities.User;
import com.mysql.cj.jdbc.MysqlDataSource;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.stream.Collectors;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
import javax.persistence.EntityManagerFactory;
import javax.persistence.spi.PersistenceUnitInfo;
import org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl;
import org.hibernate.jpa.boot.internal.PersistenceUnitInfoDescriptor;
public class JpaEntityManagerFactory {
private final String DB_URL = "jdbc:mysql://databaseurl";
private final String DB_USER_NAME = "username";
private final String DB_PASSWORD = "password";
public EntityManager getEntityManager() {
return getEntityManagerFactory().createEntityManager();
}
protected EntityManagerFactory getEntityManagerFactory() {
PersistenceUnitInfo persistenceUnitInfo = getPersistenceUnitInfo(getClass().getSimpleName());
Map<String, Object> configuration = new HashMap<>();
return new EntityManagerFactoryBuilderImpl(new PersistenceUnitInfoDescriptor(persistenceUnitInfo), configuration)
.build();
}
protected PersistenceUnitInfoImpl getPersistenceUnitInfo(String name) {
return new PersistenceUnitInfoImpl(name, getEntityClassNames(), getProperties());
}
protected List<String> getEntityClassNames() {
return Arrays.asList(getEntities())
.stream()
.map(Class::getName)
.collect(Collectors.toList());
}
protected Properties getProperties() {
Properties properties = new Properties();
properties.put("hibernate.dialect", "org.hibernate.dialect.MySQLDialect");
properties.put("hibernate.id.new_generator_mappings", false);
properties.put("hibernate.connection.datasource", getMysqlDataSource());
return properties;
}
protected Class[] getEntities() {
return new Class[]{User.class};
}
protected DataSource getMysqlDataSource() {
MysqlDataSource mysqlDataSource = new MysqlDataSource();
mysqlDataSource.setURL(DB_URL);
mysqlDataSource.setUser(DB_USER_NAME);
mysqlDataSource.setPassword(DB_PASSWORD);
return mysqlDataSource;
}
}

View File

@ -0,0 +1,130 @@
package com.baeldung.daopattern.config;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Properties;
import javax.sql.DataSource;
import javax.persistence.SharedCacheMode;
import javax.persistence.ValidationMode;
import javax.persistence.spi.ClassTransformer;
import javax.persistence.spi.PersistenceUnitInfo;
import javax.persistence.spi.PersistenceUnitTransactionType;
import org.hibernate.jpa.HibernatePersistenceProvider;
public class PersistenceUnitInfoImpl implements PersistenceUnitInfo {
public static final String JPA_VERSION = "2.1";
private final String persistenceUnitName;
private PersistenceUnitTransactionType transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
private final List<String> managedClassNames;
private final List<String> mappingFileNames = new ArrayList<>();
private final Properties properties;
private DataSource jtaDataSource;
private DataSource nonJtaDataSource;
public PersistenceUnitInfoImpl(String persistenceUnitName, List<String> managedClassNames, Properties properties) {
this.persistenceUnitName = persistenceUnitName;
this.managedClassNames = managedClassNames;
this.properties = properties;
}
@Override
public String getPersistenceUnitName() {
return persistenceUnitName;
}
@Override
public String getPersistenceProviderClassName() {
return HibernatePersistenceProvider.class.getName();
}
@Override
public PersistenceUnitTransactionType getTransactionType() {
return transactionType;
}
@Override
public DataSource getJtaDataSource() {
return jtaDataSource;
}
public PersistenceUnitInfoImpl setJtaDataSource(DataSource jtaDataSource) {
this.jtaDataSource = jtaDataSource;
this.nonJtaDataSource = null;
transactionType = PersistenceUnitTransactionType.JTA;
return this;
}
@Override
public DataSource getNonJtaDataSource() {
return nonJtaDataSource;
}
public PersistenceUnitInfoImpl setNonJtaDataSource(DataSource nonJtaDataSource) {
this.nonJtaDataSource = nonJtaDataSource;
this.jtaDataSource = null;
transactionType = PersistenceUnitTransactionType.RESOURCE_LOCAL;
return this;
}
@Override
public List<String> getMappingFileNames() {
return mappingFileNames;
}
@Override
public List<URL> getJarFileUrls() {
return Collections.emptyList();
}
@Override
public URL getPersistenceUnitRootUrl() {
return null;
}
@Override
public List<String> getManagedClassNames() {
return managedClassNames;
}
@Override
public boolean excludeUnlistedClasses() {
return false;
}
@Override
public SharedCacheMode getSharedCacheMode() {
return SharedCacheMode.UNSPECIFIED;
}
@Override
public ValidationMode getValidationMode() {
return ValidationMode.AUTO;
}
public Properties getProperties() {
return properties;
}
@Override
public String getPersistenceXMLSchemaVersion() {
return JPA_VERSION;
}
@Override
public ClassLoader getClassLoader() {
return Thread.currentThread().getContextClassLoader();
}
@Override
public void addTransformer(ClassTransformer transformer) {
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ClassLoader getNewTempClassLoader() {
return null;
}
}

View File

@ -2,12 +2,12 @@
<persistence version="1.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="user-unit">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.baeldung.daopattern.entities.User</class>
<class>com.baeldung.pattern.daopattern.entities.User</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://url/to/database"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://databaseurl"/>
<property name="javax.persistence.jdbc.user" value="username"/>
<property name="javax.persistence.jdbc.password" value="passsword"/>
<property name="javax.persistence.jdbc.password" value="password"/>
<!-- Hibernate Properties -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect"/>
<property name="hibernate.show_sql" value="true"/>