com.impetus.client.rdbms.HibernateClient Maven / Gradle / Ivy
/*******************************************************************************
* * Copyright 2012 Impetus Infotech.
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
******************************************************************************/
package com.impetus.client.rdbms;
import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.persistence.ManyToMany;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.PersistenceException;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.StatelessSession;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.criterion.Restrictions;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import com.impetus.client.rdbms.query.RDBMSQuery;
import com.impetus.kundera.client.Client;
import com.impetus.kundera.client.ClientBase;
import com.impetus.kundera.db.RelationHolder;
import com.impetus.kundera.index.IndexManager;
import com.impetus.kundera.metadata.KunderaMetadataManager;
import com.impetus.kundera.metadata.MetadataUtils;
import com.impetus.kundera.metadata.model.EntityMetadata;
import com.impetus.kundera.metadata.model.KunderaMetadata;
import com.impetus.kundera.metadata.model.MetamodelImpl;
import com.impetus.kundera.metadata.model.Relation;
import com.impetus.kundera.metadata.model.attributes.AbstractAttribute;
import com.impetus.kundera.persistence.EntityReader;
import com.impetus.kundera.persistence.context.jointable.JoinTableData;
import com.impetus.kundera.property.PropertyAccessException;
import com.impetus.kundera.property.PropertyAccessor;
import com.impetus.kundera.property.PropertyAccessorFactory;
/**
* The Class HibernateClient.
*
* @author vivek.mishra
*/
public class HibernateClient extends ClientBase implements Client
{
/** The conf. */
private Configuration conf;
/** The sf. */
private SessionFactory sf;
/** The s. */
private StatelessSession s;
/** The reader. */
private EntityReader reader;
private ServiceRegistry serviceRegistry;
private Map puProperties;
/** The Constant log. */
private static final Log log = LogFactory.getLog(HibernateClient.class);
/**
* Instantiates a new hibernate client.
*
* @param persistenceUnit
* the persistence unit
* @param indexManager
* the index manager
* @param reader
* the reader
* @param puProperties
*/
public HibernateClient(final String persistenceUnit, IndexManager indexManager, EntityReader reader,
Map puProperties)
{
conf = new Configuration().addProperties(HibernateUtils.getProperties(persistenceUnit));
Collection> classes = ((MetamodelImpl) KunderaMetadata.INSTANCE.getApplicationMetadata().getMetamodel(
persistenceUnit)).getEntityNameToClassMap().values();
// to keep hibernate happy! As in our case all scanned classes are not
// meant for rdbms, so initally i have set depth to zero!
conf.setProperty("hibernate.max_fetch_depth", "0");
serviceRegistry = new ServiceRegistryBuilder().applySettings(conf.getProperties()).buildServiceRegistry();
// / sessionFactory =
// configuration.buildSessionFactory(serviceRegistry);
for (Class> c : classes)
{
conf.addAnnotatedClass(c);
}
sf = conf.buildSessionFactory(serviceRegistry);
// TODO . once we clear this persistenceUnit stuff we need to simply
// modify this to have a properties or even pass an EMF!
this.persistenceUnit = persistenceUnit;
this.indexManager = indexManager;
this.reader = reader;
this.puProperties = puProperties;
}
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.client.Client#close()
*/
@Override
public void close()
{
this.indexManager.flush();
if (s != null)
{
s.close();
s = null;
}
if (sf != null && !sf.isClosed())
{
sf.close();
}
}
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.client.Client#delete(java.lang.Object,
* java.lang.Object)
*/
@Override
public void delete(Object entity, Object pKey)
{
s = getSessionFactory().openStatelessSession();
Transaction tx = s.beginTransaction();
s.delete(entity);
tx.commit();
EntityMetadata metadata = KunderaMetadataManager.getEntityMetadata(entity.getClass());
if (!MetadataUtils.useSecondryIndex(getPersistenceUnit()))
{
getIndexManager().remove(metadata, entity, pKey.toString());
}
}
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.client.Client#find(java.lang.Class,
* java.lang.String)
*/
@Override
public Object find(Class clazz, Object key)
{
EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(getPersistenceUnit(), clazz);
if (s == null)
{
s = getSessionFactory().openStatelessSession();
s.beginTransaction();
}
Object result = null;
try
{
result = s.get(clazz, getKey(key, (Field) entityMetadata.getIdAttribute().getJavaMember()));
}
catch (Exception e)
{
log.info(e.getMessage());
}
return result;
}
/*
* (non-Javadoc)
*
* @see com.impetus.kundera.client.Client#find(java.lang.Class,
* java.lang.String[])
*/
@Override
public List findAll(Class arg0, Object... arg1)
{
// TODO: Vivek correct it. unfortunately i need to open a new session
// for each finder to avoid lazy loading.
List objs = new ArrayList();
Session s = getSessionFactory().openSession();
Transaction tx = s.beginTransaction();
EntityMetadata entityMetadata = KunderaMetadataManager.getEntityMetadata(getPersistenceUnit(), arg0);
Object[] pKeys = getDataType(entityMetadata, arg1);
String id = ((AbstractAttribute) entityMetadata.getIdAttribute()).getJPAColumnName();
Criteria c = s.createCriteria(arg0);
c.add(Restrictions.in(id, pKeys));
return c.list();
}
@Override
public List find(Class entityClass, Map embeddedColumnMap)
{
return null;
}
@Override
protected void onPersist(EntityMetadata metadata, Object entity, Object id, List relationHolders)
{
Transaction tx = null;
s = /* getStatelessSession() */getSessionFactory().openStatelessSession();
tx = s.beginTransaction();
try
{
if (!isUpdate)
{
s.insert(entity);
// Update foreign Keys
for (RelationHolder rh : relationHolders)
{
String linkName = rh.getRelationName();
Object linkValue = rh.getRelationValue();
if (linkName != null && linkValue != null)
{
String clause = getFromClause(metadata.getSchema(), metadata.getTableName());
String updateSql = "Update " + clause + " SET " + linkName + "= '" + linkValue + "' WHERE "
+ ((AbstractAttribute) metadata.getIdAttribute()).getJPAColumnName() + " = '" + id
+ "'";
s.createSQLQuery(updateSql).executeUpdate();
}
}
tx.commit();
}
else
{
s.update(entity);
tx.commit();
}
}
// TODO: Bad code, get rid of these exceptions, currently necessary for
// handling many to one case
catch (org.hibernate.exception.ConstraintViolationException e)
{
s.update(entity);
log.info(e.getMessage());
tx.commit();
}
catch (HibernateException e)
{
log.info(e.getMessage());
throw new PersistenceException(e);
}
finally
{
}
}
/**
* Inserts records into JoinTable
*/
@Override
public void persistJoinTable(JoinTableData joinTableData)
{
String schemaName = joinTableData.getSchemaName();
String joinTableName = joinTableData.getJoinTableName();
String joinColumnName = joinTableData.getJoinColumnName();
String invJoinColumnName = joinTableData.getInverseJoinColumnName();
Map
© 2015 - 2025 Weber Informatics LLC | Privacy Policy