實例掩碼地址爲:孔浩組織結構設計java
web.xml配置文件:web
1 <!-- Spring 的監聽器能夠經過這個上下文參數來獲取beans.xml的位置 --> 2 <context-param> 3 <param-name>contextConfigLocation</param-name> 4 <param-value>classpath*:beans.xml</param-value> 5 </context-param>
測試類spring
1 package org.konghao.service; 2 3 import javax.inject.Inject; 4 5 import org.hibernate.Session; 6 import org.hibernate.SessionFactory; 7 import org.junit.After; 8 import org.junit.Before; 9 import org.junit.Test; 10 import org.junit.runner.RunWith; 11 import org.konghao.sys.org.iservice.IInitService; 12 import org.springframework.orm.hibernate4.SessionHolder; 13 import org.springframework.test.context.ContextConfiguration; 14 import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; 15 import org.springframework.transaction.support.TransactionSynchronizationManager; 16 17 @RunWith(SpringJUnit4ClassRunner.class) 18 @ContextConfiguration("/beans.xml") 19 public class TestInitService { 20 @Inject 21 private IInitService initService; 22 @Inject 23 private SessionFactory sessionFactory; 24 25 @Before 26 public void setUp() { 27 //此時最好不要使用Spring的Transactional來管理,由於dbunit是經過jdbc來處理connection,再使用spring在一些編輯操做中會形成事務shisu 28 Session s = sessionFactory.openSession(); 29 TransactionSynchronizationManager.bindResource(sessionFactory, new SessionHolder(s)); 30 //SystemContext.setRealPath("D:\\teach_source\\class2\\j2EE\\dingan\\cms-da\\src\\main\\webapp"); 31 } 32 33 @After 34 public void tearDown() { 35 SessionHolder holder = (SessionHolder) TransactionSynchronizationManager.getResource(sessionFactory); 36 Session s = holder.getSession(); 37 s.flush(); 38 TransactionSynchronizationManager.unbindResource(sessionFactory); 39 } 40 @Test 41 public void testInitByXml() { 42 initService.initEntityByXml("orgs.xml"); 43 } 44 }
解析xml文件 將信息保存到數據庫;sql
1 package org.konghao.sys.org.service.impl; 2 3 import java.lang.reflect.InvocationTargetException; 4 import java.lang.reflect.Method; 5 import java.util.List; 6 7 import javax.inject.Inject; 8 9 import org.apache.commons.beanutils.BeanUtils; 10 import org.dom4j.Attribute; 11 import org.dom4j.Document; 12 import org.dom4j.DocumentException; 13 import org.dom4j.Element; 14 import org.dom4j.io.SAXReader; 15 import org.konghao.sys.org.iservice.IInitService; 16 import org.konghao.sys.org.model.SysException; 17 import org.springframework.beans.factory.BeanFactory; 18 import org.springframework.stereotype.Service; 19 20 @Service("initService") 21 public class InitService extends AbstractBaseSevice implements IInitService{ 22 23 private Document document; 24 @Inject 25 private BeanFactory factory; 26 27 @Override 28 public void initEntityByXml(String filename) { 29 Element root = this.readDocument(filename); 30 String pname = root.attributeValue("package"); 31 List<Element> initEntitys = root.selectNodes("/entitys/initEntity"); 32 for (Element element : initEntitys) { 33 //若是這個實體存在就不添加 34 if (element.attributeValue("exist") == "1") { 35 continue; 36 }else{ 37 String cname = element.attributeValue("class"); 38 cname = pname + "." + cname; 39 String method = element.attributeValue("method"); 40 List<Element> entitys = (List<Element>)element.selectNodes("entity"); 41 addElements(cname,method,entitys); 42 } 43 } 44 } 45 46 private Element readDocument(String filename){ 47 try { 48 SAXReader saxReader = new SAXReader(); 49 Document d = saxReader.read( InitService.class.getClassLoader().getResourceAsStream("init/" + filename)); 50 return d.getRootElement(); 51 } catch (DocumentException e) { 52 e.printStackTrace(); 53 } 54 return null; 55 56 } 57 58 private void addElements(String cname, String method, List<Element> entitys) { 59 for (Element element : entitys) { 60 addElement(cname , method , element); 61 } 62 } 63 64 private void addElement(String cname, String method, Element element) { 65 List<Attribute> attrs = element.attributes(); 66 try { 67 Object o = Class.forName(cname).newInstance(); 68 String[] methods = method.split("\\."); 69 if (methods.length !=2) { 70 throw new SysException("方法格式不正確"); 71 } 72 String sname = methods[0]; //對應org.xml文件的method的第一個 73 String mname = methods[1]; 74 for (Attribute attribute : attrs) { 75 System.out.println(attribute.getName() + " ; " + attribute.getValue()); 76 String name = attribute.getName(); 77 String value = attribute.getValue(); 78 BeanUtils.copyProperty(o, name, value);//利用反射進行拷貝 79 } 80 Object service = factory.getBean(sname);//該sname應該與注入的service名稱一致 ,例如本地中使用的是OrgtypeService,則對應的service也是OrgTypeService,不然將報找不到該注入的類型 81 Method m = service.getClass().getMethod(mname , o.getClass()); 82 m.invoke(service, o); 83 } catch (ClassNotFoundException e) { 84 e.printStackTrace(); 85 } catch (IllegalAccessException e) { 86 e.printStackTrace(); 87 } catch (InvocationTargetException e) { 88 e.printStackTrace(); 89 } catch (SecurityException e) { 90 e.printStackTrace(); 91 } catch (NoSuchMethodException e) { 92 e.printStackTrace(); 93 } catch (InstantiationException e) { 94 e.printStackTrace(); 95 } 96 } 97 98 99
解析文件:數據庫
1 <?xml version="1.0" encoding="UTF-8"?> 2 <entitys package="org.konghao.sys.org.model" > 3 <initEntity exist="1" class="OrgType" method="OrgTypeService.add"> 4 <entity name="學校" sn="XX" /> 5 <entity name="分校" sn="FX" /> 6 <entity name="校辦領導" sn="XBLD" /> 7 <entity name="行政部門" sn="XZBM" /> 8 <entity name="教學部門" sn="JXBM" /> 9 <entity name="專業" sn="ZY" /> 10 <entity name="班級" sn=" BJ" /> 11 </initEntity> 12 13 <initEntity exist="0" class="Position" method="PositionService.add"> 14 <entity name="校長" sn="XZ" /> 15 <entity name="副校長" sn="FXZ" /> 16 <entity name="處長" sn="CZ" /> 17 <entity name="副處長" sn="FCZ" /> 18 <entity name="科長" sn="KZ" /> 19 <entity name="輔導員" sn="RDY" /> 20 <entity name="班主任" sn="BZR" /> 21 </initEntity> 22 </entitys>
底層實現:express
1 package org.konghao.sys.org.service.impl; 2 3 import java.util.List; 4 5 import javax.inject.Inject; 6 7 import org.konghao.sys.org.idao.IOrgTypeDao; 8 import org.konghao.sys.org.iservice.IOrgTypeService; 9 import org.konghao.sys.org.model.OrgType; 10 import org.konghao.sys.org.model.SysException; 11 import org.springframework.stereotype.Service; 12 13 @Service("OrgTypeService") 14 public class OrgTypeService extends AbstractBaseSevice implements IOrgTypeService{ 15 16 @Inject 17 private IOrgTypeDao orgTypeDao; 18 19 @Override 20 public void add(OrgType orgType) { 21 if (orgTypeDao.loadBySn(orgType.getSn()) != null) { 22 throw new SysException("要添加的組織機構類型的sn已經存在"); 23 } 24 orgTypeDao.add(orgType); 25 } 26 27 28 }
spring的beans.xml配置apache
1 <?xml version="1.0" encoding="UTF-8"?> 2 <beans xmlns="http://www.springframework.org/schema/beans" 3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" 4 xmlns:context="http://www.springframework.org/schema/context" 5 xmlns:tx="http://www.springframework.org/schema/tx" 6 xsi:schemaLocation="http://www.springframework.org/schema/beans 7 http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 8 http://www.springframework.org/schema/context 9 http://www.springframework.org/schema/context/spring-context-3.0.xsd 10 http://www.springframework.org/schema/aop 11 http://www.springframework.org/schema/aop/spring-aop-3.0.xsd 12 http://www.springframework.org/schema/tx 13 http://www.springframework.org/schema/tx/spring-tx-3.0.xsd"> 14 <!-- 打開Spring的Annotation支持 --> 15 <context:annotation-config /> 16 <!-- 設定Spring 去哪些包中找Annotation --> 17 <context:component-scan base-package="org.konghao" /> 18 19 <bean id="ftlPath" class="java.lang.String"> 20 <constructor-arg value="/ftl"/> 21 </bean> 22 23 <bean id="outPath" class="java.lang.String"> 24 <constructor-arg value="/jsp/template"/> 25 </bean> 26 27 <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" 28 destroy-method="close"> 29 <property name="driverClassName" value="${jdbc.driverClassName}" /> 30 <property name="url" value="${jdbc.url}" /> 31 <property name="username" value="${jdbc.username}" /> 32 <property name="password" value="${jdbc.password}" /> 33 <!-- 配置鏈接池的初始值 --> 34 <property name="initialSize" value="1" /> 35 <!-- 鏈接池的最大值 --> 36 <!-- <property name="maxActive" value="500"/> --> 37 <!-- 最大空閒時,當通過一個高峯以後,鏈接池能夠將一些用不到的鏈接釋放,一直減小到maxIdle爲止 --> 38 <!-- <property name="maxIdle" value="2"/> --> 39 <!-- 當最小空閒時,當鏈接少於minIdle時會自動去申請一些鏈接 --> 40 <property name="minIdle" value="1" /> 41 <property name="maxActive" value="100" /> 42 <property name="maxIdle" value="20" /> 43 <property name="maxWait" value="1000" /> 44 </bean> 45 <!--建立Spring的SessionFactory工廠 --> 46 <context:property-placeholder location="classpath:jdbc.properties" /> 47 <!-- 48 和hibernate4整合沒有提供專門的針對Annotation的類,直接在LocalSessionFactoryBean中已經集成 49 --> 50 <bean id="sessionFactory" 51 class="org.springframework.orm.hibernate4.LocalSessionFactoryBean"> 52 <!-- 注入數據源 --> 53 <property name="dataSource" ref="dataSource" /> 54 <!-- 設置Spring取那個包中查找相應的實體類 --> 55 <property name="packagesToScan"> 56 <value>org.konghao.sys.org.model</value> 57 </property> 58 <property name="hibernateProperties"> 59 <!-- <value> hibernate.dialect=org.hibernate.dialect.HSQLDialect </value> --> 60 <props> 61 <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop> 62 <prop key="hibernate.show_sql">true</prop> 63 <prop key="hibernate.hbm2ddl.auto">update</prop> 64 <prop key="hibernate.format_sql">true</prop> 65 </props> 66 </property> 67 </bean> 68 69 <!-- 配置Spring的事務處理 --> 70 <!-- 建立事務管理器--> 71 <bean id="txManager" 72 class="org.springframework.orm.hibernate4.HibernateTransactionManager"> 73 <property name="sessionFactory" ref="sessionFactory" /> 74 </bean> 75 <!-- 配置AOP,Spring是經過AOP來進行事務管理的 --> 76 <aop:config> 77 <!-- 設置pointCut表示哪些方法要加入事務處理 --> 78 <!-- 如下的事務是聲明在DAO中,可是一般都會在Service來處理多個業務對象邏輯的關係,注入刪除,更新等,此時若是在執行了一個步驟以後拋出異常 79 就會致使數據不完整,因此事務不該該在DAO層處理,而應該在service,這也就是Spring所提供的一個很是方便的工具,聲明式事務 --> 80 <aop:pointcut id="allMethods" 81 expression="execution(* org.konghao.sys.org.service.impl.*.*(..))" /> 82 <!-- 經過advisor來肯定具體要加入事務控制的方法 --> 83 <aop:advisor advice-ref="txAdvice" pointcut-ref="allMethods" /> 84 </aop:config> 85 <!-- 配置哪些方法要加入事務控制 --> 86 <tx:advice id="txAdvice" transaction-manager="txManager"> 87 <tx:attributes> 88 <!-- 讓全部的方法都加入事務管理,爲了提升效率,能夠把一些查詢之類的方法設置爲只讀的事務 --> 89 <tx:method name="*" propagation="REQUIRED" read-only="true"/> 90 <!-- 如下方法都是可能設計修改的方法,就沒法設置爲只讀 --> 91 <tx:method name="add*" propagation="REQUIRED"/> 92 <tx:method name="del*" propagation="REQUIRED"/> 93 <tx:method name="update*" propagation="REQUIRED"/> 94 <tx:method name="save*" propagation="REQUIRED"/> 95 <tx:method name="clear*" propagation="REQUIRED"/> 96 <tx:method name="empty*" propagation="REQUIRED"/> 97 <tx:method name="init*" propagation="REQUIRED"/> 98 </tx:attributes> 99 </tx:advice> 100 </beans>
————————————————————————————————————————————————————————————————————————session
版本3: 多層次解析xml文件的實現app
1 package org.konghao.sys.org.service.impl; 2 3 import java.lang.reflect.InvocationTargetException; 4 import java.lang.reflect.Method; 5 import java.util.Iterator; 6 import java.util.List; 7 8 import javax.inject.Inject; 9 import javax.persistence.criteria.CriteriaBuilder.In; 10 11 import org.apache.commons.beanutils.BeanUtils; 12 import org.dom4j.Attribute; 13 import org.dom4j.Document; 14 import org.dom4j.DocumentException; 15 import org.dom4j.Element; 16 import org.dom4j.io.SAXReader; 17 import org.konghao.sys.org.iservice.IInitService; 18 import org.konghao.sys.org.model.OrgType; 19 import org.konghao.sys.org.model.SysException; 20 import org.springframework.beans.factory.BeanFactory; 21 import org.springframework.stereotype.Service; 22 23 @Service("initService") 24 public class InitService extends AbstractBaseSevice implements IInitService{ 25 26 private Document document; 27 @Inject 28 private BeanFactory factory; 29 30 @Override 31 public void initEntityByXml(String filename) { 32 Element root = this.readDocument(filename); 33 String pname = root.attributeValue("package"); 34 List<Element> initEntitys = root.selectNodes("/entitys/initEntity"); 35 for (Element element : initEntitys) { 36 String ipname = element.attributeValue("package"); 37 String cname = element.attributeValue("class"); 38 System.out.println(element.attributeValue("exist")); 39 //若是爲1 表示已經添加過了 40 if (element.attributeValue("exist") == "1" || element.attributeValue("exist").equals("1")) { 41 continue; 42 }if (ipname != null && !"".equals(ipname)) { 43 cname = ipname + "." + cname; 44 } else{ 45 cname = pname + "." + cname; 46 } 47 String method = element.attributeValue("method"); 48 List<Element> entitys = (List<Element>)element.selectNodes("entity"); 49 System.out.println(cname + " " + method ); 50 addElements(cname,method,entitys); 51 52 } 53 } 54 55 private Element readDocument(String filename){ 56 try { 57 SAXReader saxReader = new SAXReader(); 58 Document d = saxReader.read( InitService.class.getClassLoader().getResourceAsStream("init/" + filename)); 59 return d.getRootElement(); 60 } catch (DocumentException e) { 61 e.printStackTrace(); 62 } 63 return null; 64 65 } 66 67 private void addElements(String cname, String method, List<Element> entitys) { 68 for (Element element : entitys) { 69 addElement(cname , method , element , null); 70 } 71 } 72 73 private void addElement(String cname, String method, Element e,Object parent) { 74 try { 75 //獲取全部的屬性 76 List<Attribute> atts = (List<Attribute>)e.attributes(); 77 Object obj = Class.forName(cname).newInstance(); 78 String [] ms = method.split("\\."); 79 if(ms.length!=2) throw new SysException("方法格式不正確"); 80 String sname = ms[0]; String mname = ms[1]; 81 for(Attribute att:atts) { 82 String name = att.getName(); 83 String value = att.getValue(); 84 BeanUtils.copyProperty(obj, name, value); 85 } 86 if(parent!=null) { 87 BeanUtils.copyProperty(obj, "parent", parent); 88 } 89 Object service = factory.getBean(sname); 90 Method m = service.getClass().getMethod(mname,obj.getClass()); 91 m.invoke(service, obj); 92 List<Element> es = e.selectNodes("entity"); 93 for(Element ele:es) { 94 addElement(cname, method, ele, obj); 95 } 96 } catch (ClassNotFoundException e1) { 97 e1.printStackTrace(); 98 } catch (IllegalAccessException e1) { 99 e1.printStackTrace(); 100 } catch (InvocationTargetException e1) { 101 e1.printStackTrace(); 102 } catch (SecurityException e1) { 103 e1.printStackTrace(); 104 } catch (NoSuchMethodException e1) { 105 e1.printStackTrace(); 106 } catch (InstantiationException e1) { 107 e1.printStackTrace(); 108 } 109 } 110 111 }
實體類Orgdom
1 package org.konghao.sys.org.model; 2 3 import java.util.List; 4 5 import javax.persistence.Column; 6 import javax.persistence.Entity; 7 import javax.persistence.GeneratedValue; 8 import javax.persistence.Id; 9 import javax.persistence.JoinColumn; 10 import javax.persistence.ManyToOne; 11 import javax.persistence.Table; 12 13 /** 14 * 組織對象,該表能夠生成完整的組織樹 15 * 根據組織類型來具體存儲實際中存在的組織 16 * 學院 --> xx 17 * 校本部--> FX 18 * 南校區--> FX 19 * @author jrx 20 * 21 */ 22 @Entity 23 @Table(name="t_org") 24 public class Org { 25 26 /** 27 * 組織機構的id 28 */ 29 private int id; 30 /** 31 * 組織機構的名稱 32 */ 33 private String name ; 34 /** 35 * 組織機構所屬類型的id,此處不要使用ManyToOne 36 */ 37 private Integer typeId; 38 /** 39 * 組織機構所屬類型的名稱,冗餘 40 */ 41 private String typeName; 42 /** 43 * 組織機構的排序號 44 */ 45 private Integer orderNum ; 46 /** 47 * 組織機構的父親組織 48 */ 49 private Org parent ; 50 /** 51 * 管理類型 52 */ 53 private int managerType; 54 /** 55 * 組織機構的地址 56 */ 57 private String address ; 58 /** 59 * 組織機構的電話 60 */ 61 private String phone ; 62 /** 63 * 擴展屬性,用於在針對某些特殊的組織存儲相應的信息 64 */ 65 private String att1 ; 66 private String att2 ; 67 private String att3 ; 68 69 @Id 70 @GeneratedValue 71 public int getId() { 72 return id; 73 } 74 75 public void setId(int id) { 76 this.id = id; 77 } 78 79 public String getName() { 80 return name; 81 } 82 83 public void setName(String name) { 84 this.name = name; 85 } 86 87 @Column(name="tid") 88 public Integer getTypeId() { 89 return typeId; 90 } 91 92 public void setTypeId(Integer typeId) { 93 this.typeId = typeId; 94 } 95 @Column(name="tname") 96 public String getTypeName() { 97 return typeName; 98 } 99 100 public void setTypeName(String typeName) { 101 this.typeName = typeName; 102 } 103 @Column(name="order_num") 104 public Integer getOrderNum() { 105 return orderNum; 106 } 107 108 public void setOrderNum(Integer orderNum) { 109 this.orderNum = orderNum; 110 } 111 @ManyToOne 112 @JoinColumn(name="pid") 113 public Org getParent() { 114 return parent; 115 } 116 117 public void setParent(Org parent) { 118 this.parent = parent; 119 } 120 121 public String getAddress() { 122 return address; 123 } 124 125 public void setAddress(String address) { 126 this.address = address; 127 } 128 129 public String getPhone() { 130 return phone; 131 } 132 133 public void setPhone(String phone) { 134 this.phone = phone; 135 } 136 137 public String getAtt1() { 138 return att1; 139 } 140 141 public void setAtt1(String att1) { 142 this.att1 = att1; 143 } 144 145 public String getAtt2() { 146 return att2; 147 } 148 149 public void setAtt2(String att2) { 150 this.att2 = att2; 151 } 152 153 public String getAtt3() { 154 return att3; 155 } 156 157 public void setAtt3(String att3) { 158 this.att3 = att3; 159 } 160 161 @Column(name = "manager_type") 162 public int getManagerType() { 163 return managerType; 164 } 165 166 public void setManagerType(int managerType) { 167 this.managerType = managerType; 168 } 169 170 @Override 171 public String toString() { 172 return "Org [id=" + id + ", name=" + name + ", typeId=" + typeId 173 + ", typeName=" + typeName + ", orderNum=" + orderNum 174 + ", parent=" + parent + ", managerType=" + managerType 175 + ", address=" + address + ", phone=" + phone + ", att1=" 176 + att1 + ", att2=" + att2 + ", att3=" + att3 + "]"; 177 } 178 179 180 }
底層實現:
1 package org.konghao.sys.org.service.impl; 2 3 import java.util.List; 4 5 import javax.inject.Inject; 6 7 import org.konghao.basic.model.Pager; 8 import org.konghao.sys.dto.TreeDto; 9 import org.konghao.sys.org.idao.IOrgDao; 10 import org.konghao.sys.org.idao.IOrgTypeDao; 11 import org.konghao.sys.org.iservice.IOrgService; 12 import org.konghao.sys.org.model.Org; 13 import org.konghao.sys.org.model.SysException; 14 import org.springframework.stereotype.Service; 15 16 @Service("orgService") 17 public class OrgService extends AbstractBaseSevice implements IOrgService { 18 19 20 @Inject 21 private IOrgDao orgDao; 22 23 @Inject 24 private IOrgTypeDao orgTypeDao; 25 26 private void checkChildOrgNum(Org cOrg , Org pOrg){ 27 if (pOrg == null) { 28 return; 29 } 30 //獲取根據組織類型獲取某組織類型下組織的數量(數量根據OrgTypeRule的num來肯定數量,即某類型下組織數量需小於等於OrgTypeRule中num的數量) 31 int hnum = orgDao.loadNumByType(pOrg.getId(), cOrg.getTypeId()); 32 //根據組織類型的父id和子id獲取num數量 33 int rnum = orgTypeDao.loadOrgTypeRuleNum(pOrg.getTypeId(), cOrg.getTypeId()); 34 if (rnum < 0) { 35 return; 36 } 37 if (hnum >= rnum) { 38 throw new SysException(pOrg.getName() +"下的" + cOrg.getName() + "的數量已經達到最大化"); 39 } 40 } 41 42 //parent已經存在的添加 43 @Override 44 public void add(Org org) { 45 checkChildOrgNum(org, org.getParent()); 46 if (org.getParent() != null) { 47 org.setOrderNum(orgDao.getMaxOrder(org.getParent().getId())); 48 }else { 49 org.setOrderNum(null); 50 } 51 orgDao.add(org); 52 } 53 54 @Override 55 public void add(Org org, Integer pid) { 56 if (pid != null) { 57 Org p = orgDao.load(pid); 58 if (p == null) { 59 throw new SysException("要添加的父組織不存在"); 60 } 61 checkChildOrgNum(org, org.getParent()); 62 org.setParent(p); 63 } 64 org.setOrderNum(orgDao.getMaxOrder(pid)); 65 orgDao.add(org); 66 } 67 68 }