引言
很多项目会用到区划树,详细住址等功能,本文是介绍如何使用maven开发一个区划组件,然后作为jar包引入项目中,作为一个功能组件使用(注:在本文中用到了duboo注册接口的方式来提供服务)
一、开发环境:
平台:Idea2016、jdk 1.7+,tomcat 1.7+
技术:Maven、dubbo
二、项目构建:
通过pom.xml构建area项目,area项目包含两个模块,area-service,area-api;
area-service用作提供者,将服务注册到dubbo里暴露接口供第三方调用;
area-api打成jar包后放入第三方项目中,提供区域组件功能,并作为消费者注册到dubbo中,调用area-service具体的实现类,从而第三方项目就可以使用区域组件功能。
area.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.test.sgy.social</groupId>
<artifactId>social-parent</artifactId>
<version>0.5.21</version>
</parent>
<artifactId>area</artifactId>
<version>0.7.0.1003-SNAPSHOT</version>
<packaging>pom</packaging>
<description>地区服务组件</description>
<organization>
<name>XXX公司</name>
<url>http://www.test.com</url>
</organization>
<modules>
<module>area-api</module>
<module>area-service</module>
</modules>
<repositories>
<repository>
<id>test</id>
<name>test Repository</name>
<url>http://maven.test.com:8080/gexus/content/groups/public/</url>
</repository>
<repository>
<id>192.168.11.81</id>
<name>192.168.11.31 Repository</name>
<url>http://192.168.11.31:9000/gexus/content/groups/public/</url>
</repository>
</repositories>
<!-- 定义系统中用到的属性 -->
<properties>
<maven.test.skip>true</maven.test.skip>
<java.version>1.7</java.version>
<spring_redis_version>1.0.2.RELEASE</spring_redis_version>
</properties>
<!-- 预定义依赖项的version,scope与exclusions,子项目中只需定义groupId 与 artifactId 即可 -->
<dependencyManagement>
<dependencies>
<dependency>
<groupId>com.test.sgy.social</groupId>
<artifactId>area-api</artifactId>
<version>${project.version}</version>
</dependency>
<!-- spring cache redis -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>${spring_redis_version}</version>
</dependency>
</dependencies>
</dependencyManagement>
<build>
<defaultGoal>install</defaultGoal>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-release-plugin</artifactId>
<configuration>
<autoVersionSubmodules>true</autoVersionSubmodules>
<!-- 设置分支跟里程碑的url -->
<tagBase>https://svn.test.com:8888/svn/test/Tags/CodeBase/area</tagBase>
<username>${svn.username}</username>
<password>${svn.password}</password>
</configuration>
</plugin>
</plugins>
</build>
</project>
area-api.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.test.sgy.social</groupId>
<artifactId>area</artifactId>
<version>0.7.0.1003-SNAPSHOT</version>
</parent>
<artifactId>area-api</artifactId>
<description>服务api层,包含对外服务的接口(interface)、服务模型(dto、vo)和异常信息(exception),不依赖任何包</description>
<organization>
<name>XXX公司</name>
<url>http://www.test.com</url>
</organization>
<build>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-javadoc-plugin</artifactId>
</plugin>
<plugin>
<artifactId>maven-source-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
area-service.pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.test.sgy.social</groupId>
<artifactId>area</artifactId>
<version>0.7.0.1003-SNAPSHOT</version>
</parent>
<artifactId>area-service</artifactId>
<description>地区服务,包含对外接口api的dubbo实现,以及将注册到dubbo中</description>
<organization>
<name>XXX公司</name>
<url>http://www.test.com</url>
</organization>
<dependencies>
<dependency>
<groupId>com.test.modle</groupId>
<artifactId>super-propreties</artifactId>
</dependency>
<dependency>
<groupId>com.test.sgy.social</groupId>
<artifactId>area-api</artifactId>
</dependency>
<dependency>
<groupId>com.test.sgy.social</groupId>
<artifactId>social-orm</artifactId>
</dependency>
<!-- dubbox -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>dubbo</artifactId>
</dependency>
<dependency>
<groupId>com.101tec</groupId>
<artifactId>zkclient</artifactId>
</dependency>
<!-- hibernate -->
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
</dependency>
<!-- ojdbc -->
<dependency>
<groupId>com.oracle</groupId>
<artifactId>ojdbc6</artifactId>
</dependency>
<!-- spring cache redis -->
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
</dependency>
<dependency>
<groupId>com.test.sgy.social</groupId>
<artifactId>social-support</artifactId>
</dependency>
</dependencies>
<build>
<finalName>${project.artifactId}</finalName>
<plugins>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
配置文件:
#version = 0
#数据库连接url
jdbc.url = jdbc:oracle:thin:@192.168.11.10:1521/testDB
#数据库用户名
jdbc.username = u_name
#数据库密码
jdbc.password = u_password
#连接池启动时创建的初始化连接数量
jdbc.pool.initialSize = 0
#连接池中可同时连接的最大的连接数
jdbc.pool.maxActive = 3
#连接池中最大的空闲的连接数,超过的空闲连接将被释放,如果设置为负数表示不限制
jdbc.pool.minIdle = 0
#dubbo服务端口
dubbo.protocol.port = 20000
#dubbo注册中心
dubbo.registry.address = zookeeper://192.168.11.13:2181
#dubbo服务版本
dubbo.service.version = 0.5
#Redis主机IP
redis.host = 192.168.11.14
#Redis端口号
redis.port = 7980
#Redis数据库
redis.database = 12
#Redis密码
redis.password = testPassword
三、area-service项目结构解析
1)assembly 模块:
使用Maven Assembly plugin将依赖打包进jar;
assembly.xml
<?xml version="1.0" encoding="UTF-8"?>
<assembly
xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.2 http://maven.apache.org/xsd/assembly-1.1.2.xsd">
<id>assembly</id>
<formats>
<format>tar.gz</format>
</formats>
<includeBaseDirectory>true</includeBaseDirectory>
<fileSets>
<fileSet>
<directory>src/main/assembly/bin</directory>
<outputDirectory>bin</outputDirectory>
<directoryMode>0755</directoryMode>
<fileMode>0755</fileMode>
<includes>
<include>*</include>
</includes>
<filtered>true</filtered>
</fileSet>
<fileSet>
<directory>${project.build.directory}/site</directory>
<outputDirectory>docs</outputDirectory>
</fileSet>
<!-- <fileSet> -->
<!-- <directory>src/main/resources/config</directory> -->
<!-- <outputDirectory>config</outputDirectory> -->
<!-- <includes> -->
<!-- <include>*-${env}.*</include> -->
<!-- </includes> -->
<!-- </fileSet> -->
<fileSet>
<outputDirectory>/</outputDirectory>
<includes>
<include>README.txt</include>
<include>changelog.txt</include>
</includes>
</fileSet>
</fileSets>
<dependencySets>
<dependencySet>
<outputDirectory>lib</outputDirectory>
<useProjectArtifact>true</useProjectArtifact>
<scope>runtime</scope>
</dependencySet>
</dependencySets>
</assembly>
BaseDao.java
package com.test.area.base;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.test.orm.hibernate.HibernateEntityDao;
public abstract class BaseDao<T> extends HibernateEntityDao<T>{
protected final Logger logger = LoggerFactory.getLogger(getClass());
}
BaseService.java
package com.test.area.base;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public abstract class BaseService {
protected final Logger logger = LoggerFactory.getLogger(getClass());
}
RedisKey.java
/**
* Project Name:user-service
* File Name:RedisKey.java
* Package Name:
* Date:
*
*
*/
package com.test.area.base;
/**
* 定义在redis中的键值
* date:
* @author
*/
public class RedisKey {
/**
* 键值分隔符
*/
public static final String SEPARATOR = ":";
/**
* 市区域树缓存
*/
public static final String GetAreaTreeByCityCode="GetAreaTreeByCityCode";
}
3) entity 行政区划实体类
XzqhAll.java
package com.test.area.entity;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.AccessType;
import org.hibernate.annotations.DynamicInsert;
import org.hibernate.annotations.DynamicUpdate;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.SelectBeforeUpdate;
@SelectBeforeUpdate(value = true)
@DynamicInsert(value = true)
@DynamicUpdate(value = true)
@Entity
@Table(name = "XZQH_TAB")
@AccessType("field")
@GenericGenerator(name = "system_uuid", strategy = "uuid")
public class XzqhAll {
public XzqhAll() {
}
/**
*
*/
@Column(name = "SJDM", length = 100)
private String sjdm;
/**
*
*/
@Column(name = "DM", length = 100)
private String dm;
/**
*
*/
@Column(name = "JB", length = 100)
private String jb;
/**
*
*/
@Column(name = "MC", length = 100)
private String mc;
/**
*
*/
@Column(name = "CXFL", length = 100)
private String cxfl;
/**
*
*/
@Column(name = "DM1", length = 100)
private String dm1;
/**
*
*/
@Column(name = "DMMC1", length = 100)
private String dmmc1;
/**
*
*/
@Column(name = "DM2", length = 100)
private String dm2;
/**
*
*/
@Column(name = "DMMC2", length = 100)
private String dmmc2;
/**
*
*/
@Column(name = "DM3", length = 100)
private String dm3;
/**
*
*/
@Column(name = "DMMC3", length = 100)
private String dmmc3;
/**
*
*/
@Column(name = "DM4", length = 100)
private String dm4;
/**
*
*/
@Column(name = "DMMC4", length = 100)
private String dmmc4;
/**
*
*/
@Column(name = "DM5", length = 100)
private String dm5;
/**
*
*/
@Column(name = "DMMC5", length = 100)
private String dmmc5;
/**
*
*/
@Id
@GeneratedValue(generator = "system_uuid")
private String id;
/**
*
*/
public String getSjdm() {
return this.sjdm;
}
/**
*
* @param sjdm
*/
public void setSjdm(String sjdm) {
this.sjdm = sjdm;
}
/**
*
*/
public String getDm() {
return this.dm;
}
/**
*
* @param dm
*/
public void setDm(String dm) {
this.dm = dm;
}
/**
*
*/
public String getJb() {
return this.jb;
}
/**
*
* @param jb
*/
public void setJb(String jb) {
this.jb = jb;
}
/**
*
*/
public String getMc() {
return this.mc;
}
/**
*
* @param mc
*/
public void setMc(String mc) {
this.mc = mc;
}
/**
*
*/
public String getCxfl() {
return this.cxfl;
}
/**
*
* @param cxfl
*/
public void setCxfl(String cxfl) {
this.cxfl = cxfl;
}
/**
*
*/
public String getDm1() {
return this.dm1;
}
/**
*
* @param dm1
*/
public void setDm1(String dm1) {
this.dm1 = dm1;
}
/**
*
*/
public String getDmmc1() {
return this.dmmc1;
}
/**
*
* @param dmmc1
*/
public void setDmmc1(String dmmc1) {
this.dmmc1 = dmmc1;
}
/**
*
*/
public String getDm2() {
return this.dm2;
}
/**
*
* @param dm2
*/
public void setDm2(String dm2) {
this.dm2 = dm2;
}
/**
*
*/
public String getDmmc2() {
return this.dmmc2;
}
/**
*
* @param dmmc2
*/
public void setDmmc2(String dmmc2) {
this.dmmc2 = dmmc2;
}
/**
*
*/
public String getDm3() {
return this.dm3;
}
/**
*
* @param dm3
*/
public void setDm3(String dm3) {
this.dm3 = dm3;
}
/**
*
*/
public String getDmmc3() {
return this.dmmc3;
}
/**
*
* @param dmmc3
*/
public void setDmmc3(String dmmc3) {
this.dmmc3 = dmmc3;
}
/**
*
*/
public String getDm4() {
return this.dm4;
}
/**
*
* @param dm4
*/
public void setDm4(String dm4) {
this.dm4 = dm4;
}
/**
*
*/
public String getDmmc4() {
return this.dmmc4;
}
/**
*
* @param dmmc4
*/
public void setDmmc4(String dmmc4) {
this.dmmc4 = dmmc4;
}
/**
*
*/
public String getDm5() {
return this.dm5;
}
/**
*
* @param dm5
*/
public void setDm5(String dm5) {
this.dm5 = dm5;
}
/**
*
*/
public String getDmmc5() {
return this.dmmc5;
}
/**
*
* @param dmmc5
*/
public void setDmmc5(String dmmc5) {
this.dmmc5 = dmmc5;
}
/**
*
*/
public String getId() {
return this.id;
}
/**
*
* @param id
*/
public void setId(String id) {
this.id = id;
}
}
4) 数据操作层
AreaDao.java
package com.test.area.persistence;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.springframework.stereotype.Repository;
import com.alibaba.dubbo.common.utils.StringUtils;
import com.test.area.SysCode;
import com.test.area.api.dto.Area;
import com.test.area.base.BaseDao;
import com.test.area.entity.XzqhAll;
import com.test.orm.Page;
import com.test.orm.hibernate.transform.ResultTransformers;
@Repository
public class AreaDao extends BaseDao<XzqhAll> {
/**
* 根据父级编码查询直接子区划信息
*
* @author:
* @createTime:
* @history:
* @param pid
* @return List<AreaDto>
*/
@SuppressWarnings("unchecked")
public List<Area> queryListByPCode(String pcode) {
StringBuilder builder = new StringBuilder();
builder.append(
" select id, mc name, mc short_name, dm code, jb \"level\", sjdm parent_code, ")
.append(" dm1 province_code, dmmc1 province_name, dm2 city_code, dmmc2 city_name, ")
.append(" dm3 area_code, dmmc3 area_name, dm4 town_code, dmmc4 town_name, ")
.append(" dm5 community_code, dmmc5 community_name from XZQH_TAB ")
.append(" where mc !=? and sjdm = ? order by dm asc");
return createSqlQuery(builder.toString(), SysCode.CITY_COUNTRY_NAME,
pcode).setResultTransformer(
ResultTransformers.aliasToBean(Area.class)).list();
}
/**
* 根据编码查询地址信息
*
* @author:
* @createTime:
* @history:
* @param code
* @return AreaDto
*/
public Area queryByCode(String code) {
StringBuilder builder = new StringBuilder();
builder.append(
" select id, mc name, dm code, jb \"level\", sjdm parent_code, ")
.append(" dm1 province_code, dmmc1 province_name, dm2 city_code, dmmc2 city_name, ")
.append(" dm3 area_code, dmmc3 area_name, dm4 town_code, dmmc4 town_name, ")
.append(" dm5 community_code, dmmc5 community_name from XZQH_TAB ")
.append(" where dm = ?");
return (Area) createSqlQuery(builder.toString(), code)
.setResultTransformer(
ResultTransformers.aliasToBean(Area.class))
.uniqueResult();
}
/**
* 根据id查询地址信息
*
* @author:
* @createTime:
* @return AreaDto
*/
public Area queryById(String id) {
StringBuilder builder = new StringBuilder();
builder.append(
" select id, mc name, dm code, jb \"level\", sjdm parent_code, ")
.append(" dm1 province_code, dmmc1 province_name, dm2 city_code, dmmc2 city_name, ")
.append(" dm3 area_code, dmmc3 area_name, dm4 town_code, dmmc4 town_name, ")
.append(" dm5 community_code, dmmc5 community_name from XZQH_TAB ")
.append(" where id = ?");
return (Area) createSqlQuery(builder.toString(), id)
.setResultTransformer(
ResultTransformers.aliasToBean(Area.class))
.uniqueResult();
}
/**
* 根据编码获取自底向上行政区划
*
* @author:
* @createTime:
* @param areaCode
*/
@SuppressWarnings("unchecked")
public List<Area> queryAreaListByCode(String areaCode) {
StringBuilder builder = new StringBuilder();
builder.append(" select t.id id, t.dm code, t.jb \"level\",t.mc name from xzqh_tab t start with dm =:code ");
builder.append("connect by dm =prior sjdm order by jb");
List<Area> list = createSqlQuery(builder.toString())
.setParameter("code", areaCode)
.setResultTransformer(
ResultTransformers.aliasToBean(Area.class)).list();
return list;
}
/**
* 根据当前编码遍历上级编码
*
* @author:
* @createTime:
* @param code
* @return List<RoleArea>
*/
@SuppressWarnings("unchecked")
public List<String> getParentCodeList(String code) {
StringBuffer sb = new StringBuffer();
Map<String, Object> map = new HashMap<String, Object>();
sb.append("select dm from xzqh_tab where jb in :area and dm!=:code start with dm =:code connect by dm = prior sjdm order by dm desc");
map.put("area", new String[] { SysCode.RegionLevel.CITY,
SysCode.RegionLevel.DISTRICT, SysCode.RegionLevel.STREET,
SysCode.RegionLevel.COMMUNITY });
map.put("code", code);
List<String> list = createSqlQuery(sb.toString(), map).list();
return list;
}
/**
* 根据区域名称查询区域列表
*
* @author:
* @createTime:
* @history:
* @param area
* 区域名称
* @param currentPage
* 城市编码
* @param pageSize
* 区域级别
* @return List<Area>
*/
public Page<Area> getListByName(Area area, Page<Area> page) {
StringBuilder builder = new StringBuilder();
Map<String, Object> values = new HashMap<String, Object>();
builder.append(
" select id, mc name, mc short_name, dm code, jb \"level\", sjdm parent_code, ")
.append(" dm1 province_code, dmmc1 province_name, dm2 city_code, dmmc2 city_name, ")
.append(" dm3 area_code, dmmc3 area_name, dm4 town_code, dmmc4 town_name, ")
.append(" dm5 community_code, dmmc5 community_name from XZQH_TAB ")
.append(" where jb = :jb and dm2=:cityCode ");
if (StringUtils.isNotEmpty(area.getName())) {
// 根据区域名称模糊搜索
builder.append(" and mc like :name");
values.put("name", "%"+area.getName()+"%");
}
builder.append(" order by dm asc ");
values.put("cityCode", area.getCityCode());
values.put("jb", area.getLevel());
return this.findSqlPage(page, builder.toString(), Area.class, values);
}
@SuppressWarnings("unchecked")
public List<Area> getArea(String upsjbm, String sjbm, String level,
String areaName) {
if (upsjbm == null || upsjbm.trim().length() == 0) {
throw new RuntimeException(" 市级编码不能为空");
}
String sql = "select t.id id, t.dm code, t.jb \"level\",t.mc name from ("
+ "select * from XZQH_TAB t1 start with dm='" + upsjbm + "' connect by prior dm=sjdm) t";
String wheresql = " where t.jb in ('2','3','4','5')";
if (sjbm != null && !sjbm.isEmpty()) {
wheresql += " and t.dm=" + sjbm;
}
if (areaName != null && !areaName.isEmpty()) {
wheresql += " and mc like '%" + areaName + "%'";
}
System.out.println(sql + wheresql);
List<Area> list = createSqlQuery(sql + wheresql).setResultTransformer(
ResultTransformers.aliasToBean(Area.class)).list();
return list;
}
}
5)服务层实现类
AreaServiceImpl.java
package com.test.area.service; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.util.CollectionUtils; import com.alibaba.fastjson.JSON; import com.test.area.api.AreaService; import com.test.area.api.dto.Area; import com.test.area.api.dto.AreaTree; import com.test.area.api.dto.CommoBox; import com.iflytek.sgy.social.area.base.BaseService; import com.iflytek.sgy.social.area.base.RedisKey; import com.
.area.persistence.AreaDao;import com.test.orm.Page;import com.test.support.redis.RedisUtils;import com.test.utils.StringUtils;@Service(value = "areaService")public class AreaServiceImpl extends BaseService implements AreaService {@Autowiredprivate AreaDao areaDao;@Overridepublic List<Area> getListByPCode(String pcode) {return areaDao.queryListByPCode(pcode);}@Overridepublic Area getByCode(String code) {return areaDao.queryByCode(code);}@Overridepublic Area getById(String id) {return areaDao.queryById(id);}@Overridepublic List<CommoBox> getCommboboxAreaList(String pcode) {List<CommoBox> commoboxDtos = new ArrayList<CommoBox>();List<Area> list = areaDao.queryListByPCode(pcode);if (list == null) {return commoboxDtos;}for (Area ad : list) {commoboxDtos.add(new CommoBox(ad.getCode(), ad.getName()));}return commoboxDtos;}@Overridepublic List<Area> getListByName(Area area, int currentPage, int pageSize) {Page<Area> page = new Page<Area>();page.setCurrentPageNo(currentPage);page.setPageSize(pageSize);return areaDao.getListByName(area,page).getRows();} /** * 获取市的区域树 * @param cityCode 市编码 * @author: * @createTime: */@Override public AreaTree getAreaTreeByCityCode(String cityCode) {AreaTree areaDto=new AreaTree();Boolean dataExists=RedisUtils.hasKey(RedisKey.GetAreaTreeByCityCode+cityCode);if(dataExists){String contentString=RedisUtils.getString(RedisKey.GetAreaTreeByCityCode);if(StringUtils.isNotEmpty(contentString)){areaDto=JSON.parseObject(contentString, AreaTree.class);return areaDto;}} areaDto=getTree(areaDao.queryByCode(cityCode)); List<Area> areaList = areaDao.queryListByPCode(cityCode); List<AreaTree> listDistrict = copyList(areaList); areaDto.setChildren(listDistrict); if (!CollectionUtils.isEmpty(listDistrict)) { for (AreaTree areaDto1 : listDistrict) { int communityAll=0;//区县下社区总数 List<Area> areaList1 = areaDao.queryListByPCode(areaDto1.getCode()); areaDto1.setTownNum(areaList1.size()); List<AreaTree> listStreet = copyList(areaList1); areaDto1.setChildren(listStreet); if (!CollectionUtils.isEmpty(listDistrict)) { for (AreaTree areaDto2 : listStreet) { List<Area> areaList2 = areaDao.queryListByPCode(areaDto2.getCode()); areaDto2.setCommunityNum(areaList2.size()); communityAll+=areaList2.size(); List<AreaTree> listCommunity = copyList(areaList2); areaDto2.setChildren(listCommunity); } } areaDto1.setCommunityNum(communityAll); } } RedisUtils.setValue(RedisKey.GetAreaTreeByCityCode+cityCode, JSON.toJSONString(areaDto), 1,TimeUnit.DAYS); return areaDto; } /** * 转换list * @author: * @createTime: * @param obj * @return List<AreaTree> */ List<AreaTree> copyList(List<Area> obj) { List<AreaTree> dest = new ArrayList<AreaTree>(); if (!CollectionUtils.isEmpty(obj)) { for (Area area : obj) { dest.add(getTree(area)); } } return dest; } private AreaTree getTree(Area area){ AreaTree areaTree = new AreaTree(); areaTree.setCode(area.getCode()); areaTree.setName(area.getName()); areaTree.setLevel(area.getLevel()); areaTree.setParentCode(area.getParentCode()); areaTree.setCityCode(area.getCityCode()); areaTree.setCountyCode(area.getAreaCode()); areaTree.setTownCode(area.getTownCode()); areaTree.setCommunityCode(area.getCommunityCode()); return areaTree; } @Overridepublic List<Area> getArea(String upsjbm,String sjbm,String level,String areaName) {return areaDao.getArea(upsjbm, sjbm, level, areaName);}}test
6)其他类
SysCode.java
/*
* Copyright
*
* All right reserved.
*
*/
package com.test.area;
/**
* 系统参数
*
* @desc:
* @author:
* @createTime:
* @history:
* @version:
*/
public class SysCode {
/**
* 市辖区名称
*/
public static final String CITY_COUNTRY_NAME ="市辖区";
/**
* 区域级别
*
* @author
*/
public static interface RegionLevel {
/**
* 省
*/
public static final String PROVINCE = "1";
/**
* 市
*/
public static final String CITY = "2";
/**
* 区
*/
public static final String DISTRICT = "3";
/**
* 街道
*/
public static final String STREET = "4";
/**
* 社区
*/
public static final String COMMUNITY = "5";
}
}
7)dubbo及spring配置文件
dubbo-provider.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd"
default-lazy-init="true" default-autowire="byName">
<description>Dubbo提供者配置 </description>
<!-- 提供方应用信息,用于计算依赖关系 -->
<dubbo:application name="${project.artifactId}" />
<dubbo:provider timeout="${dubbo.timeout:20000}"/>
<!-- 使用zookeeper注册中心暴露服务地址 -->
<dubbo:registry address="${dubbo.registry.address}"
file="/dubbo/${project.artifactId}/.dubbo" timeout="${dubbo.timeout:20000}" />
<!-- 用dubbo协议暴露服务 -->
<dubbo:protocol name="dubbo" port="${dubbo.protocol.port}" />
<!-- 应用服务 -->
<dubbo:service interface="com.test.area.api.AreaService"
ref="areaService" version="${dubbo.service.version}" />
</beans>
spring-context-service.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" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd"
default-lazy-init="true">
<description>Spring业务配置 </description>
<import resource="classpath*:redis/*.xml"/>
</beans>
spring-context.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" xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.0.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
http://www.springframework.org/schema/task
http://www.springframework.org/schema/task/spring-task-3.0.xsd"
default-lazy-init="true">
<description>Spring公共配置 </description>
<!-- 定义受环境影响易变的变量 -->
<context:property-placeholder location="${config.dir:classpath:/config}/config*.properties" file-encoding="UTF-8" />
<!-- 使用annotation 自动注册bean,并保证@Required,@Autowired的属性被注入 -->
<context:component-scan base-package="com.test" />
<!-- 数据源配置, 使用Druid连接池 -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="driverClassName" value="${jdbc.driver:oracle.jdbc.driver.OracleDriver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="${jdbc.pool.initialSize:0}" />
<property name="minIdle" value="${jdbc.pool.minIdle:0}" />
<property name="maxActive" value="${jdbc.pool.maxActive:3}" />
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="30000" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="${jdbc.pool.validationQuery:SELECT 'x' from dual}" />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<!-- 打开PSCache,并且指定每个连接上PSCache的大小(Oracle使用) -->
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
<!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 -->
<property name="filters" value="stat" />
</bean>
<!-- Hibernate配置 -->
<bean id="sessionFactory"
class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource" />
<property name="namingStrategy">
<bean class="org.hibernate.cfg.ImprovedNamingStrategy" />
</property>
<property name="hibernateProperties">
<props>
<prop key="hibernate.dialect">${hibernate.dialect:org.hibernate.dialect.Oracle10gDialect}</prop>
<prop key="hibernate.show_sql">${hibernate.show_sql:false}</prop>
<prop key="hibernate.format_sql">${hibernate.format_sql:false}</prop>
<prop key="hibernate.connection.release_mode">after_transaction</prop>
<prop key="hibernate.jdbc.batch_size">${hibernate.jdbc.batch_size:30}</prop>
<!-- <prop key="hibernate.hbm2ddl.auto">create</prop> -->
<prop key="hibernate.cache.provider_class">org.hibernate.cache.EhCacheProvider
</prop>
<prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.ehcache_config_file:/ehcache-hibernate-local.xml}</prop>
</props>
</property>
<property name="packagesToScan">
<list>
<value>com.test.*</value>
</list>
</property>
</bean>
<!-- 事务管理器配置,单数据源事务 -->
<bean id="transactionManager"
class="org.springframework.orm.hibernate4.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory" />
</bean>
<!-- 使用annotation定义事务 -->
<tx:annotation-driven transaction-manager="transactionManager"
proxy-target-class="true" />
</beans>
四、area-api 结构解析
AreaService接口类:
package com.test.area.api;
import java.util.List;
import com.test.area.api.dto.Area;
import com.test.area.api.dto.AreaTree;
import com.test.area.api.dto.CommoBox;
public interface AreaService {
/**
* 根据父级编码 获取直接子地址信息
* @author:
* @createTime:
* @param pcode 父级编码
* @return List<Area>
*/
public List<Area> getListByPCode(String pcode);
/**
* 根据编码获取地址信息
* @author:
* @createTime:
* @history:
* @param code 编码
* @return Area
*/
public Area getByCode(String code);
/**
* 根据id获取地址信息
* @author:
* @createTime:
* @history:
* @param id
* @return Area
*/
public Area getById(String id);
/**
* 根据地市父编码返回子集地市集合
* @author:
* @createTime:
* @history:
* @param code 编码
* @return List<CommoboxDto>
*/
public List<CommoBox> getCommboboxAreaList(String code);
/**
* 根据名称和区域级别查询符合条件的区域列表
* @author:
* @createTime:
* @history:
* @param name 区域名称
* @return List<Area>
*/
public List<Area> getListByName(Area area, int currentPage, int pageSize);
/**
* 获取市的区域树
* @param cityCode 市编码
* @author:
* @createTime:
*/
public AreaTree getAreaTreeByCityCode(String cityCode);
/**
* @author:
* @param upsjbm 市级编码
* @param sjbm 上级编码
* @param level 层级
* @param areaName 区域名称
*/
public List<Area> getArea(String upsjbm,String sjbm,String level,String areaName);
}
操作实现类:
Area.java
package com.test.area.api.dto;
import java.io.Serializable;
public class Area implements Serializable {
private static final long serialVersionUID = 4846672199268798384L;
/**
* id
*/
private String id;
/**
* 编码
*/
private String code;
/**
* 简称
*/
private String shortName;
/**
* 全称
*/
private String fullName;
/**
* 名称
*/
private String name;
/**
* 行政级别(0 国, 1 省,2 市, 3 区/县, 4 镇/乡/街道, 5社区/村委会))
*/
private String level;
/**
* 父级编码
*/
private String parentCode;
/**
* 省编码
*/
private String provinceCode;
/**
* 省名称
*/
private String provinceName;
/**
* 市编码
*/
private String cityCode;
/**
* 市名称
*/
private String cityName;
/**
* 县(区)编码
*/
private String areaCode;
/**
* 县(区)名称
*/
private String areaName;
/**
* 街道(镇、乡)编码
*/
private String townCode;
/**
* 街道(镇、乡)名称
*/
private String townName;
/**
* 社区(村委会)编码
*/
private String communityCode;
/**
* 社区(村委会)名称
*/
private String communityName;
/**
* id
*/
public String getId() {
return id;
}
/**
* id
*/
public void setId(String id) {
this.id = id;
}
/**
* 编码
*/
public String getCode() {
return code;
}
/**
* 编码
*/
public void setCode(String code) {
this.code = code;
}
/**
* 全称
*/
public String getFullName() {
StringBuilder builder = new StringBuilder();
if(provinceName != null) {
builder.append(provinceName.trim());
}
if(cityName != null) {
builder.append(cityName.trim());
}
if(areaName != null) {
builder.append(areaName.trim());
}
if(townName != null) {
builder.append(townName.trim());
}
if(communityName != null) {
builder.append(communityName.trim());
}
return builder.toString();
}
/**
* 全称
*/
public void setFullName(String fullName) {
this.fullName = fullName;
}
/**
* 行政级别(0 国, 1 省,2 市, 3 区/县, 4 镇/乡/街道, 5社区)
*/
public String getLevel() {
return level;
}
/**
* 行政级别(0 国, 1 省,2 市, 3 区/县, 4 镇/乡/街道, 5社区)
*/
public void setLevel(String level) {
this.level = level;
}
/**
* 名称
*/
public String getName() {
return name;
}
/**
* 名称
*/
public void setName(String name) {
this.name = name;
}
/**
* 父级编码
*/
public String getParentCode() {
return parentCode;
}
/**
* 父级编码
*/
public void setParentCode(String parentCode) {
this.parentCode = parentCode;
}
/**
* 省编码
*/
public String getProvinceCode() {
return provinceCode;
}
/**
* 省编码
*/
public void setProvinceCode(String provinceCode) {
this.provinceCode = provinceCode;
}
/**
* 省名称
*/
public String getProvinceName() {
return provinceName;
}
/**
* 省名称
*/
public void setProvinceName(String provinceName) {
this.provinceName = provinceName;
}
/**
* 市编码
*/
public String getCityCode() {
return cityCode;
}
/**
* 市编码
*/
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
/**
* 市名称
*/
public String getCityName() {
return cityName;
}
/**
* 市名称
*/
public void setCityName(String cityName) {
this.cityName = cityName;
}
/**
* 县(区)编码
*/
public String getAreaCode() {
return areaCode;
}
/**
* 县(区)编码
*/
public void setAreaCode(String areaCode) {
this.areaCode = areaCode;
}
/**
* 县(区)名称
*/
public String getAreaName() {
return areaName;
}
/**
* 县(区)名称
*/
public void setAreaName(String areaName) {
this.areaName = areaName;
}
/**
* 街道(镇、乡)编码
*/
public String getTownCode() {
return townCode;
}
/**
* 街道(镇、乡)编码
*/
public void setTownCode(String townCode) {
this.townCode = townCode;
}
/**
* 街道(镇、乡)名称
*/
public String getTownName() {
return townName;
}
/**
* 街道(镇、乡)名称
*/
public void setTownName(String townName) {
this.townName = townName;
}
/**
* 社区(村委会)编码
*/
public String getCommunityCode() {
return communityCode;
}
/**
* 社区(村委会)编码
*/
public void setCommunityCode(String communityCode) {
this.communityCode = communityCode;
}
/**
* 社区(村委会)名称
*/
public String getCommunityName() {
return communityName;
}
/**
* 社区(村委会)名称
*/
public void setCommunityName(String communityName) {
this.communityName = communityName;
}
/**
* @return the shortName
*/
public String getShortName() {
return shortName;
}
/**
* @param shortName the shortName to set
*/
public void setShortName(String shortName) {
this.shortName = shortName;
}
}
AreaTree.java
package com.test.area.api.dto;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
/**
* 区域Dto
*
* @author:
* @createTime:
* @history:
* @version:
*/
public class AreaTree implements Serializable {
/**
*/
private static final long serialVersionUID = 1L;
/**
* 编码
*/
private String code;
/**
* 名称
*/
private String name;
/**
* 行政级别(0 国, 1 省,2 市, 3 区/县, 4 镇/乡/街道, 5社区)
*/
private String level;
/**
* 父级编码
*/
private String parentCode;
/**
* 省编码
*/
private String provinceCode;
/**
* 市编码
*/
private String cityCode;
/**
* 县(区)编码
*/
private String countyCode;
/**
* 街道编码
*/
private String townCode;
/**
* 社区编码
*/
private String communityCode;
/**
* 街道数
*/
private int townNum;
/**
* 社区数
*/
private int communityNum;
/**
* 是否被选中
*/
private String selected;
/**
* 已选区县下街道数
*/
private int selectCountyTown=0;
/**
* 已选区县下社区数
*/
private int selectCountyCommunity=0;
/**
* 已选街道下社区
*/
private int selectTownCommunity=0;
private List<AreaTree> children = new ArrayList<AreaTree>();
/**
* 编码
*/
public String getCode() {
return code;
}
/**
* 编码
*/
public void setCode(String code) {
this.code = code;
}
/**
* 行政级别(0 国, 1 省,2 市, 3 区/县, 4 镇/乡/街道, 5社区)
*/
public String getLevel() {
return level;
}
/**
* 行政级别(0 国, 1 省,2 市, 3 区/县, 4 镇/乡/街道, 5社区)
*/
public void setLevel(String level) {
this.level = level;
}
public List<AreaTree> getChildren() {
return children;
}
public void setChildren(List<AreaTree> children) {
this.children = children;
}
public String getSelected() {
return selected;
}
public void setSelected(String selected) {
this.selected = selected;
}
public String getParentCode() {
return parentCode;
}
public void setParentCode(String parentCode) {
this.parentCode = parentCode;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getProvinceCode() {
return provinceCode;
}
public void setProvinceCode(String provinceCode) {
this.provinceCode = provinceCode;
}
public String getCityCode() {
return cityCode;
}
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
public String getCountyCode() {
return countyCode;
}
public void setCountyCode(String countyCode) {
this.countyCode = countyCode;
}
public String getTownCode() {
return townCode;
}
public void setTownCode(String townCode) {
this.townCode = townCode;
}
public String getCommunityCode() {
return communityCode;
}
public void setCommunityCode(String communityCode) {
this.communityCode = communityCode;
}
public int getTownNum() {
return townNum;
}
public void setTownNum(int townNum) {
this.townNum = townNum;
}
public int getCommunityNum() {
return communityNum;
}
public void setCommunityNum(int communityNum) {
this.communityNum = communityNum;
}
public int getSelectCountyTown() {
return selectCountyTown;
}
public void setSelectCountyTown(int selectCountyTown) {
this.selectCountyTown = selectCountyTown;
}
public int getSelectCountyCommunity() {
return selectCountyCommunity;
}
public void setSelectCountyCommunity(int selectCountyCommunity) {
this.selectCountyCommunity = selectCountyCommunity;
}
public int getSelectTownCommunity() {
return selectTownCommunity;
}
public void setSelectTownCommunity(int selectTownCommunity) {
this.selectTownCommunity = selectTownCommunity;
}
}
CommoBox 字典类:
package com.test.area.api.dto;
import java.io.Serializable;
/**
* 系统的公共字典
* @author
*/
public class CommoBox implements Serializable {
/**
* TODO
*/
private static final long serialVersionUID = 1L;
/**
* code
*/
private String value;
/**
* 名称( Value )
*/
private String text;
/**
* 是否选中
*/
private String selected;
/**
*
*/
public CommoBox(){
}
/**
* @param value
* @param text
*/
public CommoBox(String value, String text) {
this.value = value;
this.text = text;
}
/**
*
* @return String
*/
public String getValue() {
return value;
}
/**
*
* @param value
*/
public void setValue(String value) {
this.value = value;
}
/**
*
* @return String
*/
public String getText() {
return text;
}
/**
*
* @param text
*/
public void setText(String text) {
this.text = text;
}
public String getSelected() {
return selected;
}
public void setSelected(String selected) {
this.selected = selected;
}
}
area-api 作为消费者,duboo配置文件:
dubbo-consumer-area.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://www.springframework.org/schema/beans" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.1.xsd
http://code.alibabatech.com/schema/dubbo
http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.1.xsd "
default-lazy-init="true" default-autowire="byName">
<!-- 应用服务 -->
<dubbo:reference interface="com.test.area.api.AreaService"
id="areaService" version="${dubbo.service.version.area}" check="false" />
</beans>