BBS项目笔记之一:Spring+Hibernate实现Dao层



之前的项目都比较小, 这个是s2sh做的 . Spring和Hibernate整合过好些次了 ,这次看别人写的还是收获挺多的



一:单分出applicationContext-dao.xml 和hibernate.cfg.xml

spring的配置文件里单分出applicationContext-dao来 ,里边只配置和Dao有关的配置

web.xml里记得加个配置就行了

<param-value>classpath:applicationContext-*.xml</param-value>

其中包括sessionFactory和事务配置

	<!-- 配置sessionFactory -->
	<bean id="sessionFactory"
		class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
		<property name="configLocation">
			<value>classpath:hibernate.cfg.xml</value>
		</property>
	</bean>

项目里并没有把hibernate的配置文件砍掉,把配置全放在spring配置里

里边除了4个连接属性

还配置了hibernate的映射文件,之前都是用annotation配置的,这次研究一下配置文件





二:mapping映射文件的配置

大致和annotation所反映出来的信息差不多,就是换了中写法,拿文章的映射文件为例

<hibernate-mapping package="com.hrl.model">
	<class name="Article" table="tb_article">
		<id name="articleId">
			<generator class="native" />
		</id>
		<property name="title" type="string" length="255"/>
		<property name="content" length="2048"/>
		<property name="emitTime" />
		<property name="lastUpdateTime" />
		<property name="articleTypeName" length="255" />
		<many-to-one name="user" column="userId" class="User" cascade="none" 
			fetch="join" />
		<many-to-one name="articleType" column="articleTypeId" class="ArticleType" cascade="none" 
			fetch="join" />
		<set name="replies" inverse="true" cascade="all" order-by="replyTime desc">
			<key column="articleId" />
			<one-to-many class="Reply" />
		</set>
		<set name="scans" inverse="true" cascade="all" order-by="scanTime desc">
			<key column="articleId" />
			<one-to-many class="Scan" />
		</set>
	</class>
</hibernate-mapping>
绝大多数也能看懂:
id是自增 , 然后全部字段都要写上 ,

join还是用来解决1+N


一对多和多对一就比annotation麻烦多了,

set name要写实体中对应的字段

cascade是级联 这个原来用过, inverse这个查了半天:

第一、概念,指定要不要当自己来维护关系。(其实根本不用去理解)
第二、在one-to-many的时候,设置inverse=“true” 当然是在 one这个地方设置
第三、在many-to-many的时候,随便在哪端先设置inverse=“true”,另一个地方设置inverse=“false”
第四、别问我:“那我不这么设置行不行,换个方法设置下看看”,取消念头,回到第二和第三条。

lazy对应fechType的lazy




三:Dao的实现

还是分为接口和实现两部分

接口中,他用了好多final 保证传输的数据不被更改 挺好

public void updateByQuery(final String queryString,
			final Object[] parameters);


实现中:还是继承HibernateDaoSupport用template

Dao的实现类技术含量很高,忍不住copy一份...这个抽象类是供具体的DaoImpl继承的,相当于一个工具类


Serializable... ids是Serializable[] ids的意思 ,里边还定义了QBC的底层操作,这个项目里用QBC做的分页

最后setParameterValue根据传参类型来赋值

public abstract class DefaultDaoImpl extends HibernateDaoSupport implements
		IDefaultDao {

	protected int queryCount = 0;

	public void setQueryCount(int count) {
		this.queryCount = count;
	}
    /**
     * 保存数据
     * @param object
     * @return
     */
	public Serializable save(Object object) {
		return getHibernateTemplate().save(object);
	}
   /**
    * 删除数据
    * @param clazz
    * @param ids
    */
	public void delete(Class clazz, Serializable... ids) {
		for (Serializable id : ids) {
			Object obj = getHibernateTemplate().load(clazz, id);
			getHibernateTemplate().delete(obj);
		}
	}
   /**
    * 修改
    */
	public void update(Object object) {
			getHibernateTemplate().update(object);
	}

	public void saveOrUpdate(Object object) {
		getHibernateTemplate().saveOrUpdate(object);
	}
    /**
     * 得到Criteria的对象,以方便进行QBC查询
     * @param clazz
     * @return
     */
	public Criteria getCriteria(Class clazz){
		return this.getHibernateTemplate().getSessionFactory().getCurrentSession().createCriteria(clazz);
	}
	
	public void updateByQuery(final String queryString,
			final Object[] parameters) {
		getHibernateTemplate().execute(new HibernateCallback() {
			public Object doInHibernate(Session session) {
				Query query = session.createQuery(queryString);
				if (parameters != null) {
					for (int i = 0; i < parameters.length; i++) {
						query.setParameter(i, parameters[i]);
					}
				}
				query.executeUpdate();
				return null;
			}
		});
	}

	protected String setEscape(String str) {
		if (str.indexOf("%") >= 0) {
			str = str.replaceAll("%", "\\\\%");
		}
		if (str.indexOf("_") >= 0) {
			str = str.replaceAll("_", "\\\\_");
		}
		return str;
	}

	protected String setEscapeChar() {
		return " escape '\\'";
	}

	public void delete(Class clazz, Serializable id) {
		getHibernateTemplate().delete(load(clazz, id));
	}

	public Integer deleteAll(final Class clazz) {
		return (Integer) getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session) {
						Query query = session.createQuery("delete "
								+ clazz.getName());
						return new Integer(query.executeUpdate());
					}
				});
	}
    /**
     * 查询实体的所有对象
     */
	public List findAll(Class clazz) {
		return getHibernateTemplate().find("from " + clazz.getName());
	}
   /**
    * 通过主键,加载对象
    */
	public Object load(Class clazz, Serializable id) {
		return getHibernateTemplate().load(clazz, id);
	}

	public Object get(Class clazz, Serializable id) {
		return getHibernateTemplate().get(clazz, id);
	}

	public List findByNamedQuery(final String queryName) {
		return getHibernateTemplate().findByNamedQuery(queryName);
	}

	public List findByNamedQuery(final String queryName, final Object parameter) {
		return getHibernateTemplate().findByNamedQuery(queryName, parameter);
	}

	public List findByNamedQuery(final String queryName,
			final Object[] parameters) {
		return getHibernateTemplate().findByNamedQuery(queryName, parameters);
	}

	public List find(final String queryString) {
		return getHibernateTemplate().find(queryString);
	}

	public List find(final String queryString, final Object[] parameters) {
		return getHibernateTemplate().find(queryString, parameters);
	}

	public Integer deleteByQuery(final String queryString,
			final Object[] parameters) {
		return (Integer) getHibernateTemplate().execute(
				new HibernateCallback() {
					public Object doInHibernate(Session session) {
						Query query = session.createQuery(queryString);
						if (parameters != null) {
							for (int i = 0; i < parameters.length; i++) {
								query.setParameter(i, parameters[i]);
							}
						}
						return new Integer(query.executeUpdate());
					}
				});
	}

	public List query(String hql, String firstResult, String maxResults) {
		Query query = this.getHibernateTemplate().getSessionFactory()
				.getCurrentSession().createQuery(hql);
		query.setFirstResult(new Integer(firstResult).intValue());
		query.setMaxResults(new Integer(maxResults).intValue());
		return query.list();
	}

	public Object get(final String queryString, final Object[] parameters) {
		List list = getHibernateTemplate().find(queryString, parameters);
		if (list != null && !list.isEmpty()) {
			return list.get(0);
		}
		return null;
	}

	/**
	 * Convenience method to set paramers in the query given based on the actual
	 * object type in passed in as the value. You may need to add more
	 * functionaly to this as desired (or not use this at all).
	 * 
	 * @param query
	 *            the Query to set
	 * @param position
	 *            the ordinal position of the current parameter within the query
	 * @param value
	 *            the object to set as the parameter
	 */
	protected void setParameterValue(Query query, int position, Object value) {
		if (null == value) {
			return;
		} else if (value instanceof Boolean) {
			query.setBoolean(position, ((Boolean) value).booleanValue());
		} else if (value instanceof String) {
			query.setString(position, (String) value);
		} else if (value instanceof Integer) {
			query.setInteger(position, ((Integer) value).intValue());
		} else if (value instanceof Long) {
			query.setLong(position, ((Long) value).longValue());
		} else if (value instanceof Float) {
			query.setFloat(position, ((Float) value).floatValue());
		} else if (value instanceof Double) {
			query.setDouble(position, ((Double) value).doubleValue());
		} else if (value instanceof BigDecimal) {
			query.setBigDecimal(position, (BigDecimal) value);
		} else if (value instanceof Byte) {
			query.setByte(position, ((Byte) value).byteValue());
		} else if (value instanceof Calendar) {
			query.setCalendar(position, (Calendar) value);
		} else if (value instanceof Character) {
			query.setCharacter(position, ((Character) value).charValue());
		} else if (value instanceof Timestamp) {
			query.setTimestamp(position, (Timestamp) value);
		} else if (value instanceof Date) {
			query.setDate(position, (Date) value);
		} else if (value instanceof Short) {
			query.setShort(position, ((Short) value).shortValue());
		}
	}

	/**
	 * Convenience method to set paramers in the query given based on the actual
	 * object type in passed in as the value. You may need to add more
	 * functionaly to this as desired (or not use this at all).
	 * 
	 * @param query
	 *            the Query to set
	 * @param key
	 *            the key name
	 * @param value
	 *            the object to set as the parameter
	 */
	protected void setParameterValue(Query query, String key, Object value) {
		if (null == key || null == value) {
			return;
		} else if (value instanceof Boolean) {
			query.setBoolean(key, ((Boolean) value).booleanValue());
		} else if (value instanceof String) {
			query.setString(key, (String) value);
		} else if (value instanceof Integer) {
			query.setInteger(key, ((Integer) value).intValue());
		} else if (value instanceof Long) {
			query.setLong(key, ((Long) value).longValue());
		} else if (value instanceof Float) {
			query.setFloat(key, ((Float) value).floatValue());
		} else if (value instanceof Double) {
			query.setDouble(key, ((Double) value).doubleValue());
		} else if (value instanceof BigDecimal) {
			query.setBigDecimal(key, (BigDecimal) value);
		} else if (value instanceof Byte) {
			query.setByte(key, ((Byte) value).byteValue());
		} else if (value instanceof Calendar) {
			query.setCalendar(key, (Calendar) value);
		} else if (value instanceof Character) {
			query.setCharacter(key, ((Character) value).charValue());
		} else if (value instanceof Timestamp) {
			query.setTimestamp(key, (Timestamp) value);
		} else if (value instanceof Date) {
			query.setDate(key, (Date) value);
		} else if (value instanceof Short) {
			query.setShort(key, ((Short) value).shortValue());
		}
	}

}














评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值