2.0
Spring 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"
xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
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
">
<!– 建立連接池 –>
<bean name="datasouce" class="org.apache.commons.dbcp.BasicDataSource">
<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"></property>
<property name="url" value="jdbc:oracle:thin:@127.0.0.1:1521:orcl"></property>
<property name="username" value="sa"></property>
<property name="password" value="sa123456"></property>
<property name="maxActive" value="100"></property>
<property name="maxIdle" value="30"></property>
<property name="maxWait" value="100000"></property>
<property name="defaultAutoCommit" value="false"></property>
</bean>
<bean name="sessionFactory" class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">
<property name="dataSource" ref="datasouce"></property>
<property name="hibernateProperties">
<props>
<!– 加載hibernate配置屬性dialect(方言)show_sql(顯示在數據庫執行的sql語句) –>
<prop key="hibernate.dialect">org.hibernate.dialect.Oracle9Dialect</prop>
<prop key="hibernate.show_sql">true</prop>
</props>
</property>
<!– 加載hibernate的類關於數據庫的映射文件 –>
<property name="mappingResources">
<list>
<value>com/skeyedu/crm/entity/CrmUserandcustomer.hbm.xml</value>
<value>com/skeyedu/crm/entity/User.hbm.xml</value>
<value>com/skeyedu/crm/entity/Customer.hbm.xml</value>
<value>com/skeyedu/crm/entity/CrmCustomerandlinkman.hbm.xml</value>
<value>com/skeyedu/crm/entity/LinkMan.hbm.xml</value>
<value>com/skeyedu/crm/entity/Crmfollow.hbm.xml</value>
</list>
</property>
</bean>
<!–所有dao實現類的繼承瞭HibernateDaoSupport必實現裡面的sessionFactory屬性–>
<bean name="userdao" class="com.skeyedu.crm.dao.impl.UserDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean name="customerdao" class="com.skeyedu.crm.dao.impl.CustomerDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<bean name="linkmandao" class="com.skeyedu.crm.dao.impl.LinkManDaoImpl">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<!– service層調用dao方法,配置dao接口屬性 –>
<bean name="userservice" class="com.skeyedu.crm.service.impl.UserServiceImpl">
<property name="UDao" ref="userdao"></property>
</bean>
<bean name="customerservice" class="com.skeyedu.crm.service.impl.CustomerServiceImpl">
<property name="CDao" ref="customerdao"></property>
</bean>
<bean name="linkmanservice" class="com.skeyedu.crm.service.impl.linkManServiceImpl">
<property name="CDao" ref="customerdao"></property>
<property name="LDao" ref="linkmandao"></property>
</bean>
<!–scope="prototype",表示每調用action時從新new個對象,這樣排除出現錯誤在input的時值依然存在,導致actin報錯,其他操作都無法使用,因使用的均為同一個action(struts2底層機制是使用時就new個對象)或者這樣說scope="prototype" 會在該類型的對象被請求時創建一個新的action對象。如果沒有配置scope=prototype則添加的時候不會新建一個action,他任然會保留上次訪問的過記錄的信息。 –>
<bean name="douser" class="com.skeyedu.crm.struts.DoUserAction" scope="prototype">
<property name="UService" ref="userservice"></property>
</bean>
<bean name="docustomer" class="com.skeyedu.crm.struts.DoCustmoerAction" scope="prototype">
<property name="CService" ref="customerservice"></property>
<property name="UService" ref="userservice"></property>
</bean>
<bean name="dolinkman" class="com.skeyedu.crm.struts.DoLinkmanAction" scope="prototype">
<property name="CService" ref="customerservice"></property>
<property name="LService" ref="linkmanservice"></property>
</bean>
<!– 聲明事務,僅管理service層,在調用dao層方法時異常,捕獲並回滾(例:Add*表示以事務環境管理Add開頭的方法),對不合以下規則的其他方法不做事務提交或回滾處理,是隻讀的,一般是指不涉及到數據庫更新的方法–>
<bean name="trasactionManager"
class="org.springframework.orm.hibernate3.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory"></property>
</bean>
<tx:advice id="myadvice" transaction-manager="trasactionManager">
<tx:attributes>
<tx:method name="Add*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="Edit*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="Del*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="Drop*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="Regst*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="shareuser*" propagation="REQUIRED" rollback-for="Exception"/>
<tx:method name="*" read-only="true"/>
</tx:attributes>
</tx:advice>
<!– 以aop(面向方面)聲明對的哪個包中的接口進行事務管理(列:"execution(* com.skeyedu.crm.service.*.*(..))"表示:第一個星:返回值,第二星:類,第三星:方法,(..):參數)
切點:對哪些包下面的接口進行事務管理
第一個星號代表方法返回值類型任意。
第二個星號代表包下面的接口或類名任意。
第三個星號代表包下面的接口或類的方法名任意。
小括號裡的兩個點代表方法參數任意–>
<aop:config>
<aop:pointcut expression="execution(* com.skeyedu.crm.service.*.*(..))" id="mycutpoint"/>
<!– 合並事務與切面 –>
<aop:advisor advice-ref="myadvice" pointcut-ref="mycutpoint"/>
</aop:config>
</beans>
Spring basedao(通用)
package com.test.mydb;
import java.io.Serializable;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.orm.hibernate3.HibernateCallback;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
public class SpringBasedao extends HibernateDaoSupport {
//添加單對象
public int save(Object o){
int row=0;
try {
super.getHibernateTemplate().save(o);
row=1;
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
//修改單對象
public int update(Object o){
int row=0;
try {
super.getHibernateTemplate().clear();
super.getHibernateTemplate().update(o);
row=1;
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
//刪除單對象
public int delete(Class cls,Serializable id){
int row=0;
Object o=get(cls, id);
try {
super.getHibernateTemplate().delete(o);
row=1;
} catch (Exception e) {
e.printStackTrace();
}
return row;
}
//根據ID(主鍵)獲取單個對象
public Object get(Class cls,Serializable id){
return getHibernateTemplate().get(cls, id);
}
//查詢獲取對象集合,hql查詢語句
public List getlistbyhql(String hql){
List list=new ArrayList();
list=getHibernateTemplate().find(hql);
return list;
}
public List getlistbyhql(final String hql,final String[] parms){
List list=new ArrayList();
list=getHibernateTemplate().executeFind(new HibernateCallback(){
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query=session.createQuery(hql);
if(parms!=null){
for (int i = 0; i < parms.length; i++) {
query.setString(i, parms[i]);
}
}
return query.list();
}
});
return list;
}
//查詢數據量
public Object getuniqbyhql(final String hql){
Object o=getHibernateTemplate().execute(new HibernateCallback(){
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query=session.createQuery(hql);
return query.uniqueResult();
}
});
return o;
}
public Object getuniqbyhql(final String hql,final String[] parms){
Object o=getHibernateTemplate().execute(new HibernateCallback(){
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query=session.createQuery(hql);
if(parms!=null){
for (int i = 0; i < parms.length; i++) {
query.setString(i, parms[i]);
}
}
return query.uniqueResult();
}
});
return o;
}
//執行批量更新(修改刪除)
public int exeupdatehql(final String hql){
int row=0;
row=(Integer)getHibernateTemplate().execute(new HibernateCallback(){
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query=session.createQuery(hql);
int row=query.executeUpdate();
return row;
}
});
return row;
}
public int exeupdatehql(final String hql,final String[] prams){
int row=0;
row=(Integer)getHibernateTemplate().execute(new HibernateCallback(){
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query=session.createQuery(hql);
if (prams!=null) {
for (int i = 0; i < prams.length; i++) {
query.setString(i, prams[i]);
}
}
int row=query.executeUpdate();
return row;
}
});
return row;
}
/*分頁方法,參數pagesize表示每頁顯示數據量,startpage表示數據庫從指定開始數據讀取到指定位置,
* 例:int startpage=(當前頁數-1) * pagesize;
* 當前頁數為1,pagesize為3,讀取數據庫0到2數據
* 當前頁數為2,pagesize為3,讀取數據庫3到5數據
* */
public List pageList(final String hql,final int pagesize,final int startpage){
return getHibernateTemplate().executeFind(new HibernateCallback(){
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query=session.createQuery(hql);
query.setFirstResult(startpage);
query.setMaxResults(pagesize);
List list=query.list();
return list;
}
});
}
public List pageList(final String hql,final int pagesize,final int startpage,final String[] parms){
return getHibernateTemplate().executeFind(new HibernateCallback(){
public Object doInHibernate(Session session)
throws HibernateException, SQLException {
Query query=session.createQuery(hql);
if(parms!=null){
for (int i = 0; i < parms.length; i++) {
query.setString(i, parms[i]);
}
}
query.setFirstResult(startpage);
query.setMaxResults(pagesize);
List list=query.list();
return list;
}
});
}
}
分頁代碼例子:
//page當前頁數,pagesize顯示的數據量
public List<LinkMan> pagenumber(int page, int pagesize, LinkMan linkman) {
System.out.println(page+"_"+pagesize);
List<LinkMan> list =null;
String where=" where 1=1 ";
if(linkman!=null){
if(!"".equals(linkman.getName())){
where = where+" and l.surName||l.name like '%"+linkman.getSurName()+"%' ";
}
if(!"".equals(linkman.getCustomerName())){
where = where+" and l.CustomerName like '%"+linkman.getCustomerName()+"%' ";
}
if(!"".equals(linkman.getEmail())){
where = where+" and l.Email like '%"+linkman.getEmail()+"%' ";
}
}
String hql="from LinkMan l "+where+" order by l.linkManID desc";
int startpage=(page-1) * pagesize;
list=super.pageList(hql,pagesize,startpage);
return list;
}
//根據查詢條件計數查詢出來的數據條數
public int getsearchcount(LinkMan linkman) {
int count=0;
String where=" where 1=1 ";
if(linkman!=null){
if(!"".equals(linkman.getName())){
where = where+" and l.surName||l.name like '%"+linkman.getSurName()+"%' ";
}
if(!"".equals(linkman.getCustomerName())){
where = where+" and l.CustomerName like '%"+linkman.getCustomerName()+"%' ";
}
if(!"".equals(linkman.getEmail())){
where = where+" and l.Email like '%"+linkman.getEmail()+"%' ";
}
}
String hql=" select count(*) from LinkMan l "+where;
count=Integer.valueOf(super.getuniqbyhql(hql).toString());
return count;
}
分頁action傳的頁碼值
public String dolist(){
List<LinkMan> list = lService.getAllLinkMan();
int listcount = list.size();
Page pagenum=new Page();
pagenum.setRspagecount(listcount);//總數據條數
pagenum.setUppage(1);//上一頁
pagenum.setNextpage(1);//下一頁
pagenum.setPagesize(3);//頁面顯示條數
pagenum.setPagecount((pagenum.getRspagecount()+pagenum.getPagesize()-1)/pagenum.getPagesize());//頁面總數
pagenum.setPage(1);//當前頁碼
String pagestr=ServletActionContext.getRequest().getParameter("page");
if(null==pagestr){
pagenum.setPage(1);
}
try {
pagenum.setPage(Integer.valueOf(pagestr));
} catch (Exception e) {
pagenum.setPage(1);
}
if (pagenum.getPage() <= 0) {
pagenum.setPage(1);
}
if (pagenum.getPage() > pagenum.getPagecount()) {
pagenum.setPage(pagenum.getPagecount());
}
if (pagenum.getPage() – 1 > 0) {
pagenum.setUppage(pagenum.getPage() – 1);
} else {
pagenum.setUppage(0);
}
if (pagenum.getPage() + 1 > pagenum.getPagecount()) {
pagenum.setNextpage(0);
} else {
pagenum.setNextpage(pagenum.getPage() + 1);
}
List<LinkMan> listpage=lService.getpagenumber(pagenum.getPage(), pagenum.getPagesize(), null);
request.put("list", listpage);
request.put("pagenum", pagenum);
return SUCCESS;
}
本文出自 “青春行囊” 博客