Spring+SpringMVC+hibernate spatial+oracle spatial 映射存储Geomety空间数据过程记录

本文仅用于记录自己在摸索oracle spatial存储地理数据的过程,以便哪天忘记了,重新回顾下,由于本人过懒直接上代码没写详细步骤,参考的朋友们若有对过程不理解的部分或者看不懂的地方还请见谅,或者可以私信我,当然若有指教的地方亦可以私信或者留言,不胜感激。

实体类,注意geom字段

@Entity
@Table(name="Poly_Polygon")
public class Poly_Polygon {

	private Integer objectId;
	private Integer userid;	
	private String userName;	
	private Integer id;
	private Integer version;	
	private String polyType;
	private Polygon geom;
	private String points;
	private String attributeTag;	
	private Date  createTime;
	private Double userReputation;
	private Double trustValue;
	private Integer status;
	
	@Id
    @GeneratedValue(generator="increment")
    @GenericGenerator(name="increment", strategy = "increment")
	public Integer getObjectId() {
		return objectId;
	}
	public void setObjectId(Integer objectId) {
		this.objectId = objectId;
	}
    @Column(name="userid")
	public Integer getUserid() {
		return userid;
	}
	public void setUserid(Integer userid) {
		this.userid = userid;
	}
    @Column(name="userName")
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
    @Column(name="id")
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
    @Column(name="version")
	public Integer getVersion() {
		return version;
	}
	public void setVersion(Integer version) {
		this.version = version;
	}
    @Column(name="polyType")
	public String getPolyType() {
		return polyType;
	}
	public void setPolyType(String polyType) {
		this.polyType = polyType;
	}
    @Column(name = "geom",columnDefinition = "MDSYS.SDO_GEOMETRY")
    @Type(type="org.hibernate.spatial.GeometryType")
	public Polygon getGeom() {
		return geom;
	}
	public void setGeom(Polygon geom) {
		this.geom = geom;
	}
    @Column(name="points")
	public String getPoints() {
		return points;
	}
	public void setPoints(String points) {
		this.points = points;
	}
    @Column(name="attributeTag")
	public String getAttributeTag() {
		return attributeTag;
	}
	public void setAttributeTag(String attributeTag) {
		this.attributeTag = attributeTag;
	}
    @Temporal(TemporalType.TIMESTAMP)//特殊类型
    @Column(name="createTime")
	public Date getCreateTime() {
		return createTime;
	}
	public void setCreateTime(Date createTime) {
		this.createTime = createTime;
	}
    @Column(name="userReputation")
	public Double getUserReputation() {
		return userReputation;
	}
	public void setUserReputation(Double userReputation) {
		this.userReputation = userReputation;
	}
    @Column(name="trustValue")
	public Double getTrustValue() {
		return trustValue;
	}
	public void setTrustValue(Double trustValue) {
		this.trustValue = trustValue;
	}
    @Column(name="status")
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}


}

Dao类

import java.io.Serializable;
import java.util.List;
import com.hz.entity.Poly_Polygon;
//20170809 定义Poly_Polygon接口
public interface Poly_PolygonDao extends GenericDao<Poly_Polygon, String> {

}

Daoimpl类

@Repository("Poly_PolygonDao") 
public class Poly_PolygonDaoImpl implements Poly_PolygonDao {

	@Autowired
	private SessionFactory sessionFactory;
	private Session getCurrentSession(){
		return this.sessionFactory.getCurrentSession();
		
	}
	
	public Poly_Polygon load(String userid) {
		return (Poly_Polygon)this.getCurrentSession().load(Poly_Polygon.class, userid);
	}

	@SuppressWarnings("unchecked")//告诉编译器忽略 unchecked 警告信息,如使用List,ArrayList等未进行参数化产生的警告信息。
	public List<Poly_Polygon> loadByUserName(String username) {
		List<Poly_Polygon> Poly_Polygons=this.getCurrentSession().createSQLQuery("select * from Poly_Polygon where userName='"+username+"'").addEntity(Poly_Polygon.class).list();
		return Poly_Polygons;
	}

	public Poly_Polygon get(String userid) {

		return (Poly_Polygon)this.getCurrentSession().get(Poly_Polygon.class, userid);
	}

	public List<Poly_Polygon> findAll() {

		List<Poly_Polygon> Poly_Polygons=this.getCurrentSession().createQuery("from Poly_Polygon").setCacheable(true).list();
		return Poly_Polygons;
	}

	public void persist(Poly_Polygon entity) {
		this.getCurrentSession().persist(entity);
		
	}

	public Integer save(Poly_Polygon entity) {

		return (Integer)this.getCurrentSession().save(entity);
	}

	public void saveOrUpdate(Poly_Polygon entity) {
		this.getCurrentSession().saveOrUpdate(entity);
		
	}

	public void delete(String userid) {
		Poly_Polygon entity=this.load(userid);
		this.getCurrentSession().delete(entity);
		
	}

	public void flush() {
		this.getCurrentSession().flush();
		
	}


}

service类:

//20170809定义Poly_PolygonService接口
public interface Poly_PolygonService {

	    Poly_Polygon load(String userid);
		
		List<Poly_Polygon> loadByUserName(String username);
		
		Poly_Polygon get(String userid);
		
		List<Poly_Polygon> findAll();
		void persist(Poly_Polygon entity);
		
		Integer save(Poly_Polygon entity);
		
		void saveOrUpdate(Poly_Polygon entity);
		
		void delete(String userid);
		
		void flush();
}

serviceImpl类:

@Service("Poly_PolygonService")
public class Poly_PolygonServiceImpl implements Poly_PolygonService {

	@Autowired
	private Poly_PolygonDao polygonDao;
		
	public Poly_Polygon load(String userid) {

		return polygonDao.load(userid);
	}

	public Poly_Polygon get(String userid) {

		return polygonDao.get(userid);
	}

	public List<Poly_Polygon> findAll() {

		return polygonDao.findAll();
	}

	public void persist(Poly_Polygon entity) {

		polygonDao.persist(entity);
	}

	public Integer save(Poly_Polygon entity) {

		return polygonDao.save(entity);
	}
	
	public void saveOrUpdate(Poly_Polygon entity) {
		polygonDao.saveOrUpdate(entity);
	}

	public void delete(String userid) {
		polygonDao.delete(userid);
	}

	public void flush() {

		polygonDao.flush();
	}

	public List<Poly_Polygon> loadByUserName(String username) {
		List<Poly_Polygon> polygons=polygonDao.loadByUserName(username);
		return polygons;

	}
	
}

pom.xml配置文件:

<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/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.hz</groupId>
  <artifactId>GeoWeb_20170727</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>GeoWeb_20170727 Maven Webapp</name>
  <url>http://maven.apache.org</url>
  
  <!--添加编码、spring版本、hibernate版本、jackson版本信息  -->
    <properties>  
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>  
        <spring.version>4.1.4.RELEASE</spring.version>  
         <hibernate.version>4.3.11.Final</hibernate.version>   
        <jackson.version>2.5.0</jackson.version>  
    </properties>
  
  <dependencies>
  <!--junit(自己生成的)  -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    
  <!-- spring -->  
   
    <dependency>  
      <groupId>org.springframework</groupId>  
      <artifactId>spring-core</artifactId>  
      <version>${spring.version}</version>  
    </dependency>
    <dependency>  
      <groupId>org.springframework</groupId>  
      <artifactId>spring-beans</artifactId>  
      <version>${spring.version}</version>  
    </dependency>
    <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-beans</artifactId>  
       <version>${spring.version}</version>  
    </dependency>    
    <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-context</artifactId>  
       <version>${spring.version}</version>  
    </dependency>    
    <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-tx</artifactId>  
       <version>${spring.version}</version>  
    </dependency>    
    <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-web</artifactId>  
       <version>${spring.version}</version>  
    </dependency>    
    <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-test</artifactId>  
       <version>${spring.version}</version>  
       <scope>test</scope>  
    </dependency>
     
    <!-- 使用SpringMVC需配置 -->      
    <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-webmvc</artifactId>  
       <version>${spring.version}</version>  
    </dependency>
    
    <!-- 与关系型数据库整合时需配置 如hibernate jpa等 -->  
    <dependency>  
       <groupId>org.springframework</groupId>  
       <artifactId>spring-orm</artifactId>  
       <version>${spring.version}</version>  
    </dependency>
    
    <!-- hibernate -->  
     <dependency>  
       <groupId>org.hibernate</groupId>  
       <artifactId>hibernate-core</artifactId>  
       <version>${hibernate.version}</version>  
    </dependency>    
    <dependency>  
       <groupId>org.hibernate</groupId>  
       <artifactId>hibernate-ehcache</artifactId>  
       <version>${hibernate.version}</version>  
    </dependency>


	<dependency>
		<groupId>org.hibernate</groupId>
		<artifactId>hibernate-spatial</artifactId>
		<version>4.3-52N</version>
	</dependency>  
	
	
<dependency>
    <groupId>com.vividsolutions</groupId>
    <artifactId>jts</artifactId>
    <version>1.13</version>
</dependency>

    <!-- 二级缓存ehcache -->  
    <dependency>  
       <groupId>net.sf.ehcache</groupId>  
       <artifactId>ehcache</artifactId>  
       <version>2.9.0</version>  
    </dependency>
   
    <!-- log4j -->  
    <dependency>  
       <groupId>log4j</groupId>  
       <artifactId>log4j</artifactId>  
       <version>1.2.17</version>  
    </dependency>
    
    <!--slf4j-log4j12, 避免SLF4J: Failed to load class的问题 -->
    <dependency>
       <groupId>org.slf4j</groupId>
       <artifactId>slf4j-log4j12</artifactId>
       <version>1.7.7</version>
       <scope>test</scope>
    </dependency>    
    
   <!-- Oracle连接 -->  
    <dependency>  
       <groupId>com.oracle</groupId>  
       <artifactId>ojdbc6_11g</artifactId>  
       <version>11.2.0.1.0</version>  
   </dependency> 
   



   
   <!-- c3p0数据源 -->  
    <dependency>  
       <groupId>com.mchange</groupId>  
       <artifactId>c3p0</artifactId>  
       <version>0.9.5.2</version>  
   </dependency> 
   
   <!-- json -->  
   <dependency>
	<groupId>com.alibaba</groupId>
	<artifactId>fastjson</artifactId>
	<version>1.2.3</version>
   </dependency>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-annotations</artifactId>
		<version>${jackson.version}</version>
	</dependency>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-core</artifactId>
		<version>${jackson.version}</version>
	</dependency>
	<dependency>
		<groupId>com.fasterxml.jackson.core</groupId>
		<artifactId>jackson-databind</artifactId>
		<version>${jackson.version}</version>
	</dependency> 
    
    <!--aop  -->
	<dependency>
		<groupId>org.aspectj</groupId>
		<artifactId>aspectjweaver</artifactId>
		<version>1.8.4</version>
	</dependency>

	<!-- servlet -->
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>servlet-api</artifactId>
		<version>3.0-alpha-1</version>
		<scope>provided</scope>
	</dependency>
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>jstl</artifactId>
		<version>1.2</version>
	</dependency>

  </dependencies>
  
  
  
  <build>
    <finalName>GeoWeb_20170727</finalName>  
  
        <plugins>
	<!-- Run the JUnit unit tests in an isolated classloader -->
	<plugin>
		<groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-surefire-plugin</artifactId>
		<version>2.4.2</version>
		<configuration>
			<skipTests>true</skipTests>
		</configuration>

	</plugin>

	<plugin>
		<groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-war-plugin</artifactId>
		<version>2.3</version>
		<configuration>
			<webXml>src/main/webapp/WEB-INF/web.xml</webXml>
		</configuration>
	</plugin>

	<!-- generate java doc -->
	<plugin>
		<groupId>org.apache.maven.plugins</groupId>
		<artifactId>maven-javadoc-plugin</artifactId>
		<version>2.9.1</version>
		<configuration>
			<javadocDirectory>target/javadoc</javadocDirectory>
			<reportOutputDirectory>target/javadoc</reportOutputDirectory>
			<charset>UTF-8</charset>
			<encoding>UTF-8</encoding>
			<docencoding>UTF-8</docencoding>
			<show>private</show>
		</configuration>
	</plugin>

	<!-- 部署至本机 -->
	<plugin>
		<groupId>org.codehaus.cargo</groupId>
		<artifactId>cargo-maven2-plugin</artifactId>
		<version>1.0</version>
		<configuration>
			<container>
				<containerId>Tomcat7.0</containerId>
				<home>D:\install\Tomcat7.0\anzhaung\apache-tomcat-7.0.52</home>
			</container>
			<configuration>
				<type>existing</type>
				<home>D:\install\Tomcat7.0\anzhaung\apache-tomcat-7.0.52</home>
			</configuration>
		</configuration>
	</plugin>

	
</plugins>  

  </build>
</project>

spring.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:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans  
            http://www.springframework.org/schema/beans/spring-beans-4.1.xsd  
            http://www.springframework.org/schema/context  
            http://www.springframework.org/schema/context/spring-context-4.1.xsd">  
    
    <!-- 加载配置文件 -->        
    <context:property-placeholder location="classpath:config.properties"/>  
    
    <!-- 扫描service自动注入为bean,配置了对应包下组件bean自动注入管理,我们需要将dao,service的实现类交由spring管理,如(@Repository,@Service) -->  
    <context:component-scan base-package="com.hz.service.impl,com.hz.dao.impl" />  
  
</beans>

springMVC.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>  
<beans xmlns="http://www.springframework.org/schema/beans"  
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  
    xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"  
    xsi:schemaLocation="http://www.springframework.org/schema/beans   
        http://www.springframework.org/schema/beans/spring-beans-4.1.xsd   
        http://www.springframework.org/schema/context   
        http://www.springframework.org/schema/context/spring-context-4.1.xsd   
        http://www.springframework.org/schema/mvc   
        http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> 
 
   <!--  下面配置了包扫描Controller,将@Controller注入为spring的bean。以及springmvc的json处理,和视图 层的配置。-->
    
  
    <!-- 自动扫描@Controller注入为bean -->  
     <context:component-scan base-package="com.hz.controller"/> 
  
  
    <!-- 以下为SpringMVC配置 -->  
    <mvc:annotation-driven>  
        <!-- 返回json数据,@response使用 -->  
        <mvc:message-converters register-defaults="true">  
            <bean  
                class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">  
                <property name="supportedMediaTypes">  
                    <list>  
                        <value>text/html;charset=UTF-8</value>  
                        <value>application/json;charset=UTF-8</value>  
                    </list>  
                </property>   
            </bean>  
        </mvc:message-converters>  
    </mvc:annotation-driven>  
    
<!--   对模型视图名称的解析,即在模型视图名称添加前后缀 -->
    <bean  
        class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        
        <property name="viewClass"  
            value="org.springframework.web.servlet.view.JstlView" />  
        <property name="prefix" value="/WEB-INF/views" />  
        <property name="suffix" value=".jsp" /> 
        
    </bean>  
    
</beans>

log4j.properties配置文件:

### set log levels ###  
log4j.rootLogger = INFO , C , D , E   
  
### console ###  
log4j.appender.C = org.apache.log4j.ConsoleAppender  
log4j.appender.C.Target = System.out  
log4j.appender.C.layout = org.apache.log4j.PatternLayout  
log4j.appender.C.layout.ConversionPattern = [springmvc_hibernate_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n  
  
### log file ###  
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender  
log4j.appender.D.File = ../logs/springmvc_hibernate_demo.log  
log4j.appender.D.Append = true  
log4j.appender.D.Threshold = INFO   
log4j.appender.D.layout = org.apache.log4j.PatternLayout  
log4j.appender.D.layout.ConversionPattern = [springmvc_hibernate_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n  
  
### exception ###  
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender  
log4j.appender.E.File = ../logs/springmvc_hibernate_demo_error.log   
log4j.appender.E.Append = true  
log4j.appender.E.Threshold = ERROR   
log4j.appender.E.layout = org.apache.log4j.PatternLayout  
log4j.appender.E.layout.ConversionPattern = [sspringmvc_hibernate_demo][%p] [%-d{yyyy-MM-dd HH:mm:ss}] %C.%M(%L) | %m%n 

ehcache.xml配置文件:

<?xml version="1.0" encoding="UTF-8"?>  
<ehcache xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../config/ehcache.xsd" updateCheck="false">  
    <diskStore path="D:/install/ehcache" />  
    <!-- DefaultCache setting. -->  
     <defaultCache  
            maxElementsInMemory="1000"  
            eternal="false"  
            timeToIdleSeconds="120"  
            timeToLiveSeconds="120"  
            maxElementsOnDisk="1000000"  
            overflowToDisk="true"   
            memoryStoreEvictionPolicy="LRU">  
              
    </defaultCache>  
  
    <!-- Special objects setting. -->  
  
    <cache   
         name="package com.hz.entity.User"  
         maxElementsInMemory="2"  
         memoryStoreEvictionPolicy="LRU"   
         eternal="true"   
         diskPersistent="false"  
         overflowToDisk="false"   
         maxElementsOnDisk="1000000" />   
  
  
  
</ehcache>

hibernate.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-4.1.xsd   
        http://www.springframework.org/schema/tx   
        http://www.springframework.org/schema/tx/spring-tx-4.1.xsd  
        http://www.springframework.org/schema/aop   
        http://www.springframework.org/schema/aop/spring-aop-4.1.xsd">  

     <!--配置数据源 c3p0   -->
     <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"  
        destroy-method="close">  
        <property name="driverClass" value="${jdbc.driver}" />  
        <property name="jdbcUrl" value="${jdbc.url}" />  
        <property name="user" value="${jdbc.username}" />  
        <property name="password" value="${jdbc.password}" />  

        <property name="checkoutTimeout" value="30000" />  <!--请求超时时间   -->
        <property name="idleConnectionTestPeriod" value="30" /> <!--每60秒检查所有连接池中的空闲连接。默认值: 0,不检查   --> 
        <property name="maxIdleTime" value="30" /><!--         连接数据库连接池最大空闲时间   -->  
        <property name="initialPoolSize" value="5" />  <!--         连接池初始化连接数   -->
        <property name="minPoolSize" value="5" />  
        <property name="maxPoolSize" value="20" />  
        <property name="acquireIncrement" value="5" /> <!--当连接池中的连接耗尽的时候c3p0一次同时获取的连接数。默认值: 3   --> 
    </bean>  
     
    <!--配置hibernate的SessionFactory   -->
    <bean id="sessionFactory"  
        class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <property name="dataSource" ref="dataSource" /> <!--         注入数据源 相关信息看源码   --> 

        <property name="hibernateProperties">  <!--         hibernate配置信息   -->
            <!-- EL存取变量数据的方法很简单,例如:${username}。它的意思是取出某一范围中名称为username的变量。因为我们并没有指定哪一个范围的username,所以它会依序从Page、Request、Session、Application范围查找。
                                                   假如途中找到username,就直接回传,不再继续找下去,但是假如全部的范围都没有找到时,就回传null。 -->
            <props>                   <prop key="hibernate.dialect">${hibernate.dialect}</prop> 
                <prop key="hibernate.show_sql">${hibernate.show_sql}</prop>  
                <prop key="hibernate.format_sql">${hibernate.format_sql}</prop>  
                <prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop> 
                
                <!--配置oracle Spatial的时候必备  -->
                 <prop key="hibernate.spatial.connection_finder">${hibernate.spatial.connection_finder}</prop> 
                 <prop key="hibernate.spatial.ogc_strict">${hibernate.spatial.ogc_strict}</prop> 
                 
                <!--开启二级缓存 ehcache  --> 
                <prop key="hibernate.cache.use_second_level_cache">${hibernate.cache.use_second_level_cache}</prop>  
                <prop key="hibernate.cache.use_query_cache">${hibernate.cache.use_query_cache}</prop>  
                <prop key="hibernate.cache.region.factory_class">${hibernate.cache.region.factory_class}</prop>  
                <prop key="hibernate.cache.provider_configuration_file_resource_path">${hibernate.cache.provider_configuration_file_resource_path}  
                </prop> 
            </props> 
        </property>
        <property name="packagesToScan" value="com.hz.entity" /> <!-- 扫描hibernate注解配置的entity    -->
    </bean>  
  
     <!--配置事务管理器   -->
     <bean id="transactionManager"  
          class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <property name="sessionFactory" ref="sessionFactory" />  
    </bean>
    
     <tx:advice id="transactionAdvice" transaction-manager="transactionManager"><!--     配置事务增强处理Bean,指定事务管理器   -->  

        <tx:attributes>  <!--         配置详细事务处理语义   -->
            <tx:method name="insert*" propagation="REQUIRED" />  
            <tx:method name="update*" propagation="REQUIRED" />  
            <tx:method name="delete*" propagation="REQUIRED" />    
            <tx:method name="get*" propagation="SUPPORTS" read-only="true" />  
            <tx:method name="find*" propagation="SUPPORTS" read-only="true" />  
            <tx:method name="select*" propagation="SUPPORTS" read-only="true" />  
            <tx:method name="load*" propagation="SUPPORTS" read-only="true" />  

            <tx:method name="*" /> <!--             其他采用默认事务方式   --> 
  
        </tx:attributes>  
    </tx:advice>  


    <aop:config>  <!--     Spring aop事务管理   -->
        <!--配置切入点   -->
        <aop:pointcut id="transactionPointcut"  
            expression="execution(* com.hz.service..*Impl.*(..))" />
        <!--指定在txAdvice切入点应用txAdvice事务增强处理   -->
        <aop:advisor pointcut-ref="transactionPointcut"  
            advice-ref="transactionAdvice" />  
    </aop:config>  
  
</beans> 

config.properties配置文件:

#application configs  
  
#jdbc c3p0 config  
jdbc.driver = oracle.jdbc.driver.OracleDriver
jdbc.url = jdbc:oracle:thin:@localhost:1521:HZ
jdbc.username = hz
jdbc.password = 123456  

#hibernate config  
hibernate.dialect=org.hibernate.spatial.dialect.oracle.OracleSpatial10gDialect
hibernate.spatial.connection_finder=com.hz.util.C3P0ConnectionFinder
hibernate.spatial.ogc_strict=true
#hibernate.dialect =org.hibernate.dialect.Oracle10gDialect

hibernate.show_sql = true  
hibernate.format_sql = true  
#if there is first time to excute,"update" should be replaced by "create" ,so that can create a table of entity.(hz_write)
hibernate.hbm2ddl.auto = create
hibernate.cache.use_second_level_cache = true  
hibernate.cache.use_query_cache = true  
hibernate.cache.region.factory_class = org.hibernate.cache.ehcache.EhCacheRegionFactory  
hibernate.cache.provider_configuration_file_resource_path = ehcache.xml 

hibernate这一块解释一下:因为存储的数据是地理数据,用到了oracle数据库中的oracle spatial,因此在配置hibernate时dialog用的是

org.hibernate.spatial.dialect.oracle.OracleSpatial10gDialect

另外还需要增加两个配置:

hibernate.spatial.connection_finder=com.hz.util.C3P0ConnectionFinder
hibernate.spatial.ogc_strict=true

同样一定要记得在hibernate.xml中添加以上三个配置。

com.hz.util.C3P0ConnectionFinder

这个类需要自己定义,代码如下:

public class C3P0ConnectionFinder implements ConnectionFinder {

	public Connection find(Connection con) throws FinderException {
		// TODO Auto-generated method stub
		if (con == null) {
			return null;
		}
		if (con instanceof C3P0ProxyConnection){
			try {
				C3P0NativeJdbcExtractor c3P0NativeJdbcExtractor = new C3P0NativeJdbcExtractor();
				OracleConnection oracleConnection = (OracleConnection) c3P0NativeJdbcExtractor.getNativeConnection(con);
				return oracleConnection;
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		throw new FinderException(
				"Couldn't get at the OracleSpatial Connection object from the PreparedStatement.");
	}

}

测试类:

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:spring.xml","classpath:hibernate.xml"})
public class Poly_PolygonServiceTest {
private static final Logger LOGGER=Logger.getLogger(AdminUserServiceTest.class);
	
	@Autowired
	private Poly_PolygonService poly_polygonService; 
	
	@Test
	public void save() throws ParseException{
		Poly_Polygon polygon=new Poly_Polygon();
		polygon.setUserid(7);
		polygon.setAttributeTag("测试");
		polygon.setCreateTime(new Date());  
		String wktGeom="POLYGON((1 1,5 1,5 5,1 5,1 1),(2 2,2 3,3 3,3 2,2 2))";		 		
		Wkt_Util fromText = new Wkt_Util();  
        Polygon poly=fromText.createPolygon(wktGeom);
		polygon.setGeom(poly);
		polygon.setId(9);
		polygon.setPoints("999,222;888,777");
		polygon.setPolyType("面");
		polygon.setTrustValue(0.666);
		polygon.setUserName("hz");
		
		Integer userid= poly_polygonService.save(polygon);		
		List<Poly_Polygon>polygons =poly_polygonService.findAll();
		for(int i=0;i<polygons.size();i++){
			System.out.println(polygons.get(i).getUserName()+", Userid: "+polygons.get(i).getUserid());
		}
		LOGGER.info(JSON.toJSONString(userid));
	}
}

当然也涉及到一个WKT转换工具类:

public class Wkt_Util {
	
		private static GeometryFactory geometryFactory = new GeometryFactory();;

		public static Polygon createPolygon(String polygonWKT) throws ParseException 
		{			
	        WKTReader fromText = new WKTReader();  
	        Geometry geom = null;         
	        try {  
	            geom = fromText.read(polygonWKT);  
	        } catch (ParseException e) {  
	            throw new RuntimeException("Not a WKT string:" + polygonWKT);  
	        }  
	       
	        if (!geom.getGeometryType().equals("Polygon")) {
	            throw new RuntimeException("Geometry must be a Polygon. Got a " + geom.getGeometryType());
	        }       
	        	        
	        Polygon polygon=(Polygon)geom;
	        return polygon;
		}
}

大致过程就是如此了。

转载自:https://blog.csdn.net/xianyucishi/article/details/78404318

You may also like...