保存,更新和删除在Hibernate和Spring中不起作用

问题描述 投票:0回答:1

这是我的应用程序上下文,Dao实现类和Service类。如果我尝试获取任何记录,作为响应我在我的对象中有所有记录但是当我尝试保存或更新或尝试从数据库中删除对象时没有任何异常发生。

<?xml version="1.0" encoding="UTF-8"?>

    <context:annotation-config />

    <context:component-scan base-package="org.prosigns.adminity.model.layers" />

    <mvc:annotation-driven />

    <tx:annotation-driven transaction-manager="transactionManager" />

    <context:property-placeholder location="classpath:hibernate.properties" />

    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"
          p:driverClassName="${jdbc.driverClassName}" 
          p:url="${jdbc.url}"
          p:username="${jdbc.username}" 
          p:password="${jdbc.password}"/>

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource" 
          p:basename="Messages" />

    <bean id="sessionFactory" class="org.prosigns.adminity.model.common.annotation.ScanningAnnotationSessionFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="annotatedPackages">
            <list>
                <value>org.prosigns.adminity.model.layers.domain.**.*</value>
                <value>org.prosigns.adminity.model.layers.dao.**.*</value>
                <value>org.prosigns.adminity.model.layers.services.**.*</value>
            </list>
        </property>
        <property name="hibernateProperties">
            <props>
                <prop key="hibernate.dialect">${hibernate.dialect}</prop>
                <prop key="hibernate.connection.autocommit">false</prop>
                <prop key="org.hibernate.transaction">false</prop>
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>
                <prop key="hibernate.use_sql_comments">${hibernate.use_sql_comments}</prop>
                <prop key="hibernate.max_fetch_depth">${hibernate.fetch_depth}</prop>
                <prop key="hibernate.current_session_context_class">${hibernate.current_session_context_class}</prop>
                <prop key="hibernate.transaction.factory_class">${hibernate.transaction_factory_class}</prop>
                <prop key="hibernate.bytecode.use_reflection_optimizer">${hibernate.use_reflection_optimizer}</prop>
                <prop key="hibernate.connection.release_mode">${hibernate.connection_release_mode}</prop>
                <prop key="hibernate.jdbc.batch_size">${hibernate.jdbc_batch_size}</prop>
                <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache_use_second_level_cache}</prop>
                <prop key="hibernate.cache.provider_class">net.sf.ehcache.hibernate.SingletonEhCacheProvider</prop>
            </props>
        </property>
    </bean>



<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory"/>
    </bean>    

</beans>

@Repository
public class PersistenceDaoImpl<T, PK extends Serializable> implements PersistenceDao<T, PK> {

    /** Class type. */
    Class<T> type;

    /**
     * Gets the current session in use (creates one if necessary).
     * @return Session object 
     */
    public Session getSession() throws DatabaseException{
        return SessionManager.getSessionFactory().openSession();
    }

    /**
     * Default bean constructor for spring.
     */
    public PersistenceDaoImpl() {
        // default constructor for spring
    }

    /**
     * Constructor.
     * @param type class type
     */
    public PersistenceDaoImpl(Class<T> type) {
        this.type = type;
    }

    /** Helper functions.
     * @return the currently set class
     */
    public Class<T> getPersistentClass() {
        return this.type;
    }

    /**
     * Delete persistentObject from DB.
     * @param persistentObject object to delete.
     */
    public void delete(T persistentObject) throws DatabaseException{
        getSession().delete(persistentObject);

    }

    /** Deletes an object of a given Id. Will load the object internally so consider using delete (T obj) directly
     * @param id Delete key
     */
    public void delete(PK id) throws DatabaseException{
        getSession().delete(load(id));
    }

    /**
     * Loads the given Object.
     * @param id to load
     * @return T Loaded object
     */
    @SuppressWarnings("unchecked")
    public T load(PK id) throws DatabaseException{
        T t = (T) getSession().load(this.type, id);
        if (t == null){
            return (T) new Object();
        }
        return t;
    }


    /**
     * Loads the given Object.
     * @param id Id to load
     * @return An object of type T
     */
    @SuppressWarnings("unchecked")
    public T get(PK id) throws DatabaseException{
        return (T) getSession().get(this.type, id);
    }

    /**
     * Item to save.
     * @param o object to save
     * @return PK
     */
    @SuppressWarnings("unchecked")
    public PK save(T o) throws DatabaseException{
        return (PK) getSession().save(o);
    }

   /**
     * Item to refresh.
     * @param o object to refresh
     */
    public void refresh(T o) throws DatabaseException{
        getSession().refresh(o);
    }

    /**
     * Item to saveOrUpdate.
     * @param o item to save.
     */
    public void saveOrUpdate(T o) throws DatabaseException{
        getSession().saveOrUpdate(o);
    }

    /**
     * Update object.
     * @param o object to update
     */
    public void update(T o) throws DatabaseException{
        getSession().update(o);
    }

    /**
     * Get query.
     * @param s Query to execute.
     * @return Query object
     */
    public Query getQuery(String s) throws DatabaseException{
        return getSession().createQuery(s);
    }

    /** Delete object.
     * @param persistentObject to delete
     * @param session to use
     * 
     */
    public void delete(T persistentObject, Session session) throws DatabaseException{
        getSession().delete(persistentObject);
    }

    /** Deletes an object of a given Id. Will load the object internally so consider using delete (T obj) directly.
     * @param id to delete 
     * @param session to use
     */
    public void delete(PK id, Session session) throws DatabaseException{
        getSession().delete(load(id));
    }

    /**
     * Loads the given Object.
     * @param id to load
     * @param session to use
     * @return  an object of type T
     */
    @SuppressWarnings("unchecked")
    public T load(PK id, Session session) throws DatabaseException{
        return (T) session.load(this.type, id);
    }

    /**
     * Loads the given Object.
     * @param id Id to load
     * @param session Session to use
     * @return An object of type T
     */
    @SuppressWarnings("unchecked")
    public T get(PK id, Session session) throws DatabaseException{
        return (T) session.get(this.type, id);
    }

    /** Save object.
     * @param o to save 
     * @param session to use
     * @return the id of the saved object
     * 
     */
    @SuppressWarnings("unchecked")
    public PK save(T o, Session session) throws DatabaseException{
        return (PK) session.save(o);
    }

    /** Save Or Update object.
     * @param o to save
     * @param session to use.
     * 
     */
    public void saveOrUpdate(T o, Session session) throws DatabaseException{
        session.saveOrUpdate(o);
    }

    /** Update record.
     * @param o to update
     * @param session to use
     * 
     */
    public void update(T o, Session session) throws DatabaseException{
        session.update(o);
    }


    /**
     * GetQuery.
     * @param s to return
     * @param session  to use
     * @return Query object
     */
    public Query getQuery(String s, Session session) throws DatabaseException{
        return session.createQuery(s);
    }

    /** Wrapper around hibernate functions.
     * @param criterion to use
     * @return A list of matching objects
     */
    @SuppressWarnings("unchecked")
    public List<T> findByCriteria(Criterion... criterion) throws DatabaseException{
        Criteria criteria =  getSession().createCriteria(getPersistentClass());

        for (Criterion c : criterion) {
            criteria.add(c);
        }
        return criteria.list();
    }


    /** FindAll.
     * @return A list of all the objects
     */
    public List<T> findAll() throws DatabaseException{
        return findByCriteria();
    }

    /** Flushes the cache of the currently-used session.
     * @throws DatabaseException 
     * @throws HibernateException 
     * 
     */
    public void flush() throws DatabaseException {
        getSession().flush();
    }

    /** Object to evict from cache.
     * @param obj Object to evict
     */
    public void evict(Object obj) throws DatabaseException{
        getSession().evict(obj);
    }

    /** FindByExample.
     * @param exampleInstance to use
     * @param excludeProperty to use
     * @return List of matching objects
     */
    @SuppressWarnings("unchecked")
    public List<T> findByExample(T exampleInstance, String... excludeProperty) throws DatabaseException{
        Criteria criteria = getSession().createCriteria(getPersistentClass());
        Example example = Example.create(exampleInstance);
        for (String exclude : excludeProperty) {
            example.excludeProperty(exclude);
        }
        criteria.add(example);
        return criteria.list();
    }
}

@Service("crmAuthenticationService")
@Transactional(propagation = Propagation.SUPPORTS, readOnly = true)
public class CrmAuthenticationServiceImpl implements CrmAuthenticationService{

    @Transactional (readOnly = false, propagation = Propagation.REQUIRED)
    public void saveUpdate(CrmAuthenticationVO vo) throws GenericException {
        if (vo.isForUpdate()){
            vo.setUpdatedBy(WebUtils.getLoggedUserId());
            vo.setUpdatedDate(CommonUtils.getCurrentDate());
        }else {
            vo.setAddedBy(WebUtils.getLoggedUserId());
            vo.setAddedDate(CommonUtils.getCurrentDate());
        }
        CrmAuthentication domain = new CrmAuthentication();
        domain.setValueObject(vo.getValueObject());
        DaoManager.getInstance().getCrmAuthenticationDao().update(domain);
    }
}
spring hibernate service dao sessionfactory
1个回答
2
投票

您需要在事务中进行保存,更新和删除调用。

尝试将@Transactional注释添加到DAO中。 Spring将创建一个事务感知代理来包装你的DAO。当事务完成时,它将导致Hibernate刷新和提交。

© www.soinside.com 2019 - 2024. All rights reserved.