先直接看起初写的代码:
public List findAll(Integer start, Integer limit) {
log.debug("finding all SipNews instances");
try {
String queryString = "from SipNews";
Query query = this.getSession().createQuery(queryString);
query.setFirstResult(start);
query.setMaxResults(limit);
return query.list();
} catch (RuntimeException re) {
log.error("find all failed", re);
throw re;
}
}
打眼一看好像是没啥问题,但是这个方法被连续调用3次以上后,程序就卡住了,成假死态。 阅读全文>>
2009.12.09 / 标签:
hibernate,
Spring / 分类:
J2EE技术
继承了HibernateDaoSupport的DAO类中,一般的增删改会直接使用HibernateTemplate所提供的方法去执行,而遇到一些复杂查询时find()就不好用了,当然也可以自己拼HQL放进去查。所以这种情况下就会用Session创建Query,查询完后手工关闭session。 阅读全文>>
2009.11.21 / 标签:
hibernate,
Spring / 分类:
J2EE技术
公司项目的框架基本上已经定下来了,前台UI使用ExtJS,后台使用Spring MVC+Hibernate。由于自己对Spring的MVC还不是很了解,记得在上海找工作笔试的时候有一道题“请简述Spring MVC”没答得出来,现在是时候学习一下了。 阅读全文>>
SSH集成的一个样例,放到这里方便自己以后使用。其实就是一些配置,也没什么先后顺序。
web.xml增加
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
修改Struts-config.xml中action的type属性为org.springframework.web.struts.DelegatingActionProxy
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" "http://struts.apache.org/dtds/struts-config_1_3.dtd">
<struts-config>
<form-beans >
<form-bean name="userForm" type="cn.ineeke.ssh.web.form.UserForm" />
</form-beans>
<global-exceptions />
<global-forwards />
<action-mappings >
<action
attribute="userForm"
input="/index.jsp"
name="userForm"
parameter="action"
path="/user"
scope="request"
type="org.springframework.web.struts.DelegatingActionProxy">
<forward name="userlist" path="/list.jsp"/>
<forward name="toUpdate" path="/user_info.jsp"/>
</action>
</action-mappings>
<message-resources parameter="cn.ineeke.ssh.web.ApplicationResources" />
</struts-config>
对action进行注入,name属性必须与上面配置信息中action的path一致,class属性值为具体的action类。
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean name="/user" class="cn.ineeke.ssh.web.action.UserAction">
<property name="userBiz" ref="userBiz"/>
</bean>
</beans>
hibernate.cfg.xml的配置
<?xml version='1.0' encoding='UTF-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<!-- Generated by MyEclipse Hibernate Tools. -->
<hibernate-configuration>
<session-factory>
<property name="connection.username">root</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/ssh
</property>
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<property name="myeclipse.connection.profile">mysql</property>
<property name="connection.password">www.ineeke.com</property>
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="show_sql">true</property>
<mapping resource="cn/ineeke/ssh/entity/TUser.hbm.xml" />
</session-factory>
</hibernate-configuration>
配置AOP
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<!-- 配置sessionFactory -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="configLocation"
value="classpath:hibernate.cfg.xml">
</property>
</bean>
<!-- 配置事务管理器 -->
<bean id="transactionManager" class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory">
<ref bean="sessionFactory"/>
</property>
</bean>
<!-- 配置事务的传播性 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<tx:method name="add*" propagation="REQUIRED"/>
<tx:method name="del*" propagation="REQUIRED"/>
<tx:method name="modify*" propagation="REQUIRED"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!-- 配置哪些类及其哪些方法参与该事务 -->
<aop:config>
<aop:pointcut id="allMethod" expression="execution(* cn.ineeke.ssh.biz.impl.*.*(..))"/>
<aop:advisor advice-ref="txAdvice" pointcut-ref="allMethod"/>
</aop:config>
</beans>
O(∩_∩)O哈哈~过新年了,我的Hibernate学习也至此告一段落了,Hibernate是冬眠,也刚好过完冬天了,过春节了,我该学习Spring了。Spring I’m coming…
首先要有一个实体。
package cn.ineeke.spring;
import java.util.List;
import java.util.Map;
import java.util.Set;
public class MyBean {
private String strValue;
private int intValue;
private List listValue;
private Set setValue;
private String[] arrayValue;
private Map mapValue;
public String getStrValue() {
return strValue;
}
public void setStrValue(String strValue) {
this.strValue = strValue;
}
public int getIntValue() {
return intValue;
}
public void setIntValue(int intValue) {
this.intValue = intValue;
}
public List getListValue() {
return listValue;
}
public void setListValue(List listValue) {
this.listValue = listValue;
}
public Set getSetValue() {
return setValue;
}
public void setSetValue(Set setValue) {
this.setValue = setValue;
}
public String[] getArrayValue() {
return arrayValue;
}
public void setArrayValue(String[] arrayValue) {
this.arrayValue = arrayValue;
}
public Map getMapValue() {
return mapValue;
}
public void setMapValue(Map mapValue) {
this.mapValue = mapValue;
}
}
有了实体就可以开始配置Spring了。在crc下创建applicationContext.xml文件,当然名字你可以命名为其他的。
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">
<bean id="myBean" class="cn.ineeke.spring.MyBean">
<property name="strValue" value="Hello" />
<property name="intValue">
<value>21</value>
</property>
<property name="listValue">
<list>
<value>neeke1</value>
<value>neeke2</value>
</list>
</property>
<property name="setValue">
<set>
<value>ineeke1</value>
<value>ineeke2</value>
</set>
</property>
<property name="arrayValue">
<list>
<value>array1</value>
<value>array2</value>
</list>
</property>
<property name="mapValue">
<map>
<entry key="ek1" value="ek1"/>
<entry key="ek2" value="ek2"/>
</map>
</property>
</bean>
</beans>
现在只仅仅是配置好了,下面看看如何new出这个实体。
package cn.ineeke.spring;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.context.support.ClassPathXmlApplicationContext;
public class SpringTest {
public static void main(String[] args) {
BeanFactory factory = new ClassPathXmlApplicationContext("applicationContext.xml");
MyBean bean = (MyBean)factory.getBean("myBean");
System.out.println(bean.getIntValue());
}
}
这个主要是为了了解如何使用Spring对实体的属性进行注入,其重点又在于不同数据类型的属性如何注入以及如何使用Spring获得需要的实体。
Hibernate二级缓存也称为进程级的缓存或SessionFactory级的缓存。二级缓存是全局缓存,它可以被所有的session共享。二级缓存的生命周期和SessionFactory的生命周期一致,SessionFactory可以管理二级缓存。
二级缓存的配置使用:
1.在crc下创建echcache.xml文件,其内容如下:
<ehcache>
<diskStore path="java.io.tmpdir"/>
<defaultCache
maxElementsInMemory="10000"
eternal="false"
overflowToDisk="true"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
diskPersistent="false"
/>
</ehcache>
maxElementsInMemory属性用于指定缓存中最多可放多少个对象。
eternal属性指定缓存是否永久有效。
timeToIdleSeconds属性指定缓存多久未被使用便清理掉。
timeToLiveSeconds属性指定缓存的生命长度。
diskPersistent属性指定缓存是否被持久化到硬盘中,保存路径由标签指定。
2.修改hibernate.cfg.xml文件开启二级缓存。
<hibernate-configuration>
<session-factory>
<!-- 开启二级缓存 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 设置缓存提供者 -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<mapping resource="cn/ineeke/entity/User.hbm.xml"/>
</session-factory>
</hibernate-configuration>
3.指定哪些实体类使用缓存。经过第二步缓存是启用了,但是并没有被使用。它不会去自动把所有的实体都进行缓存了,而是需要手动指定哪个实体需要缓存,以及其缓存的策略。这里有两种方式,第一种是修改要使用缓存的实体的映射文件。如在User.hbm.xml中使用标签启用。
<hibernate-mapping>
<class name="cn.ineeke.entity.User" table="t_user">
<cache usage="read-only"/>
<id name="id">
<generator class="native"/>
</id>
<property name="name"/>
</class>
</hibernate-mapping>
第二种方式是在hibernate.cfg.xml中使用标签指定实体类并启用。
<hibernate-configuration>
<session-factory>
<!-- 开启二级缓存 -->
<property name="hibernate.cache.use_second_level_cache">true</property>
<!-- 设置缓存提供者 -->
<property name="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider</property>
<mapping resource="cn/ineeke/entity/User.hbm.xml"/>
<!-- 指定哪些实体需要使用二级缓存 -->
<class-cache class="cn.ineeke.entity.User" usage="read-only"/>
</session-factory>
</hibernate-configuration>
标签中的class属性指定要对哪个实体进行缓存,而usage属性与标签的相同,都指的是缓存策略,此值依实际需要而定,默认采用read-only。
Hibernate的一级缓存时间很短,其生命周期和session的一样,所以一级缓存也称session级缓存或事务级缓存。
在Hibernate中的get()方法和load()方法都是支持一级缓存的,而iterate()方法只有在查询实体对象时才支持一级缓存。
在Hibernate中可以使用session.clear()或session.evict()对一级缓存进行管理。
如果在使用中,所需操作的数据量特别大,需要考虑直接采用JDBC实现。
2009.01.21 / 标签:
hibernate,
HQL查询语句 / 分类:
J2EE技术
在[jsp中实现分页显示数据] 一文中,为了分页写了很长的SQL语句,很麻烦!使用Hibernate提供的分页就简单的多了。在Hibernate分页查询中,使用setFirstResult()方法设置当前页(从0开始),使用setMaxResults()方法设置每页最多显示多少条数据。
示例代码:
public void testHQL(){
Session session = super.getSession();
Query query = session.createQuery("FROM User").setFirstResult(0).setMaxResults(5).list();
List list = query.list();
}
2009.01.21 / 标签:
hibernate,
HQL查询语句 / 分类:
J2EE技术
在Hibernate映射文件中User.hbm.xml使用标签定义过滤器。
<filter-def>
<filter-param name="myid" type="java.lang.Integer"/>
</filter-def>
接下来在其标签中调用此过滤器。
<class ...>
...
<filter name="myfilter" condition="id < :myid"/>
</class>
这样一来,当我们执行查询User的时候Hibernate会自动将这个条件加到查询语句之后。这里的<是“<”的转义字符。
public void testFilterQuery(){
Session session = super.getSession();
session.enableFilter("myfilter").setParameter("myid",10);
Query query = session.createQuery("FROM User");
List list = query.list();
}
2009.01.21 / 标签:
hibernate,
HQL查询语句 / 分类:
J2EE技术
为了降低HQL与程序之间的耦合度,可以通过Hibernate外置命名查询的方式达到。
在Hibernate的映射文件中(任何一个映射文件)使用标签定义HQL语句。
<query name="searchUser">
<![CDATA[
FROM User
]]>
</query>
在程序中使用session.getNamedQuery()方法得到HQL查询语句。
public void testHQL(){
Session session = super.getSession();
Query query = session.getNamedQuery("searchUser");
List list = query.list();
}
如此,如果这个HQL语句后期需要修改的话,我们就不必再去修改程序了,而只需简单的修改标签的定义即可。不过,任何方式都有其优缺点,所以在开发中要灵活运用。