/************************************************
 * Copyright (c) Shen Li. All rights reserved.  *
 * http://joyaop.sourceforge.net                *
 * -------------------------------------------- *
 * Distributable under LGPL license.            *
 * See terms of license at gnu.org.             *
 ************************************************/
package net.sf.joyaop.demo.rbac;

import net.sf.joyaop.ObjectFactory;
import org.hibernate.criterion.Expression;

import java.util.List;

/**
 * @author Shen Li
 */
public class EntityHomeImpl implements EntityHome {
    private final ObjectFactory objectFactory;
    private final SessionManager sessionManager;

    public EntityHomeImpl(ObjectFactory objectFactory, SessionManager sessionManager) {
        this.objectFactory = objectFactory;
        this.sessionManager = sessionManager;
    }

    public Object newEntity(Class entityClass) {
        return objectFactory.newInstance(entityClass);
    }

    public void saveEntity(Object entity) {
        sessionManager.getSession().save(entity);
    }

    public Object loadEntity(Class entityClass, String propertyName, Object propertyValue) {
        List result;
        result = (List) sessionManager.getSession()
                .createCriteria(entityClass)
                .add(Expression.eq(propertyName, propertyValue))
                .list();
        if (result.size() == 0) {
            throw new RuntimeException("Entity not found.");
        }
        if (result.size() > 1) {
            throw new RuntimeException("Found more than one entity.");
        }
        return result.get(0);
    }
}
