package org.openlca.core.database.mysql;

import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

import javax.persistence.EntityManagerFactory;

import org.openlca.core.database.BaseDao;
import org.openlca.core.database.IDatabase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * IDatabase implementation for MySQL database.
 */
public class Database implements IDatabase {

	private Logger log = LoggerFactory.getLogger(this.getClass());
	private EntityManagerFactory entityFactory;

	public Database(ConnectionData connectionData) {
		connect(connectionData);
	}

	private void connect(ConnectionData data) {
		log.trace("Connect to database {}", data);
		Map<Object, Object> map = new HashMap<>();
		map.put("javax.persistence.jdbc.url", data.getUrl());
		map.put("javax.persistence.jdbc.user", data.getUser());
		map.put("javax.persistence.jdbc.password", data.getPassword());
		map.put("javax.persistence.jdbc.driver", "com.mysql.jdbc.Driver");
		map.put("eclipselink.classloader", getClass().getClassLoader());
		map.put("eclipselink.target-database", "MySQL");
		entityFactory = data.getPersistenceProvider()
				.createEntityManagerFactory("openLCA", map);
	}

	@Override
	public EntityManagerFactory getEntityFactory() {
		return entityFactory;
	}

	@Override
	public Connection createConnection() {
		try {
			return entityFactory.createEntityManager().unwrap(Connection.class);
		} catch (Exception e) {
			log.error("Failed to create database connection", e);
			return null;
		}
	}

	@Override
	public void close() {
		if (entityFactory != null && entityFactory.isOpen())
			entityFactory.close();
	}

	@Override
	public <T> BaseDao<T> createDao(Class<T> clazz) {
		return new BaseDao<>(clazz, getEntityFactory());
	}
}

@@ -63,16 +63,47 @@
 ection;%0A
+import java.sql.DriverManager;%0A
 import j
@@ -545,16 +545,46 @@
 Factory;
+%0A%09private ConnectionData data;
 %0A%0A%09publi
@@ -654,16 +654,46 @@
 nData);%0A
+%09%09this.data = connectionData;%0A
 %09%7D%0A%0A%09pri
@@ -1453,67 +1453,90 @@
 urn 
-entityFactory.createEntityManager().unwrap(Connection.class
+DriverManager.getConnection(data.getUrl(), data.getUser(),%0A%09%09%09%09%09data.getPassword()
 );%0A%09

create connection