一、读取Geometry对象
在java映射的数据库表实体类对象的字段中添加Geometry类型,如下:
@Column(name = "GEOM")
private Geometry geom;
这样就能读取到Geometry 对象,Geometry 有很多空间计算方法,具体可以查看源码。
例:
1.实体类:
import org.hibernate.annotations.Type;
import com.vividsolutions.jts.geom.Polygon;
/**
* Shape()
*/
//@Column(name = "Shape", jdbcType = JdbcType.STRUCT)
@Type(type = "org.hibernate.spatial.GeometryType")
@Column(name = "Shape")
private Polygon Shape;
public Polygon getShape() {
return Shape;
}
public void setShape(Polygon shape) {
Shape = shape;
}
二、写入Geometry对象
相对于读取,写入就相对麻烦一些,首先要构建一个Geometry对象,分点线面的构建:
private GeometryFactory geometryFactory = JTSFactoryFinder.getGeometryFactory(null);
点的构建
Envelope e = new Envelope(new Coordinate(x, y));
线的构建
LineString line = geometryFactory.createLineString(Coordinate[]);
line.setSRID(20131028);
rb.setGeometry(line);
其中,rb实体类对象的Geometry的定义格式如下:
@Column(name = "PKG_CONVEX", jdbcType = JdbcType.STRUCT)
private Geometry geometry;
一定要指定jdbcType 类型,Oracle数据库中Geometry对象只接收STRUCT类型的数据
三、*** hibernate注解报错注解方式下报java.lang.UnsupportedOperationException
hibernate 不支持此类型输出
结局方法,配置hibernate方言
例如Sqlserver 数据库
<bean id="hibernateJpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value=“”org.hibernate.spatial.dialect.sqlserver.SqlServer2008SpatialDialect">
</property>
<property name="generateDdl" value="${hibernate.generateDdl}"/>
<property name="showSql" value="${hibernate.showSql}"/>
</bean>
在配置hibernate.cfg.xml时需指定使用数据库的方言:
例:
<property name="dialect">org.hibernate.dialect.MySQL5Dialect</property>
以下是各数据库对应的方言(Dialect):
数据库 |
方言(Dialect) |
DB2 |
org.hibernate.dialect.DB2Dialect |
DB2 AS/400 |
org.hibernate.dialect.DB2400Dialect |
DB2 OS390 |
org.hibernate.dialect.DB2390Dialect |
PostgreSQL |
org.hibernate.dialect.PostgreSQLDialect |
MySQL5 |
org.hibernate.dialect.MySQL5Dialect |
MySQL5 with InnoDB |
org.hibernate.dialect.MySQL5InnoDBDialect |
MySQL with MyISAM |
org.hibernate.dialect.MySQLMyISAMDialect |
Oracle(any version) |
org.hibernate.dialect.OracleDialect |
Oracle 9i |
org.hibernate.dialect.Oracle9iDialect |
Oracle 10g |
org.hibernate.dialect.Oracle10gDialect |
Oracle 11g |
org.hibernate.dialect.Oracle10gDialect |
Sybase |
org.hibernate.dialect.SybaseASE15Dialect |
Sybase Anywhere |
org.hibernate.dialect.SybaseAnywhereDialect |
Microsoft SQL Server 2000 |
org.hibernate.dialect.SQLServerDialect |
Microsoft SQL Server 2005 |
org.hibernate.dialect.SQLServer2005Dialect |
Microsoft SQL Server 2008 |
org.hibernate.dialect.SQLServer2008Dialect |
SAP DB |
org.hibernate.dialect.SAPDBDialect |
Informix |
org.hibernate.dialect.InformixDialect |
HypersonicSQL |
org.hibernate.dialect.HSQLDialect |
H2 Database |
org.hibernate.dialect.H2Dialect |
Ingres |
org.hibernate.dialect.IngresDialect |
Progress |
org.hibernate.dialect.ProgressDialect |
Mckoi SQL |
org.hibernate.dialect.MckoiDialect |
Interbase |
org.hibernate.dialect.InterbaseDialect |
Pointbase |
org.hibernate.dialect.PointbaseDialect |
FrontBase |
org.hibernate.dialect.FrontbaseDialect |
Firebird |
org.hibernate.dialect.FirebirdDialect |
5.hibernate配置模板
(1)test-applicationContext-jpa.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"
xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jpa="http://www.springframework.org/schema/data/jpa"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd"
default-lazy-init="true">
<description>Spring Data JPA</description>
<!-- 使用annotation 自动注册bean, 并保证@Required、@Autowired的属性被注入 -->
<context:component-scan base-package="com.trgis"/>
<!-- Jpa Entity Manager 配置 -->
<bean id="entityManagerFactory"
class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="jpaVendorAdapter" ref="hibernateJpaVendorAdapter"/>
<property name="packagesToScan" value="com.trgis"/>
<property name="jpaProperties">
<props>
<!-- 命名规则 My_NAME->MyName -->
<prop key="hibernate.hbm2ddl.auto">${hibernate.hbm2ddl.auto}</prop>
<prop key="hibernate.dialect">${hibernate.dialect}</prop>
<prop key="hibernate.cache.region.factory_class">org.hibernate.cache.ehcache.EhCacheRegionFactory</prop>
<prop key="net.sf.ehcache.configurationResourceName">test-ehcache-hibernate-local.xml</prop>
<prop key="hibernate.ejb.naming_strategy">org.hibernate.cfg.ImprovedNamingStrategy</prop>
</props>
</property>
</bean>
<bean id="hibernateJpaVendorAdapter"
class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
<property name="databasePlatform" value="${hibernate.dialect}">
<!-- <bean factory-method="getDialect"
class="com.trgis.common.hibernate.persistence.Hibernates">
<constructor-arg ref="dataSource"/>
</bean> -->
</property>
<property name="generateDdl" value="${hibernate.generateDdl}"/>
<property name="showSql" value="${hibernate.showSql}"/>
</bean>
<!-- Spring Data Jpa配置 -->
<jpa:repositories base-package="com.trgis"
transaction-manager-ref="transactionManager"
entity-manager-factory-ref="entityManagerFactory"/>
<!-- Jpa 事务配置 -->
<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
<property name="entityManagerFactory" ref="entityManagerFactory"/>
</bean>
<!-- 使用annotation定义事务 -->
<tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/>
<!-- hibernate validator -->
<bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<!-- 基本属性 url、user、password -->
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
<!-- 配置初始化大小、最小、最大 -->
<property name="initialSize" value="1"/>
<property name="minIdle" value="10"/>
<property name="maxActive" value="80"/>
<!-- 配置获取连接等待超时的时间 -->
<property name="maxWait" value="60000"/>
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
<property name="timeBetweenEvictionRunsMillis" value="60000"/>
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
<property name="minEvictableIdleTimeMillis" value="300000"/>
<property name="validationQuery" value="SELECT 'x'"/>
<property name="testWhileIdle" value="true"/>
<property name="testOnBorrow" value="false"/>
<property name="testOnReturn" value="false"/>
<!-- 打开PSCache,并且指定每个连接上PSCache的大小 -->
<property name="poolPreparedStatements" value="true"/>
<property name="maxPoolPreparedStatementPerConnectionSize" value="20"/>
<!-- 配置监控统计拦截的filters -->
<property name="filters" value="stat"/>
</bean>
<context:property-placeholder ignore-unresolvable="true" location="classpath:/test.properties"/>
</beans>
(2)test-ehcache-hibernate-local.xml
<?xml version="1.0" encoding="UTF-8"?>
<ehcache updateCheck="false" name="hibernateCache">
<diskStore path="java.io.tmpdir/ehcache/ylly_dao_user/hibernate" />
<defaultCache
maxElementsInMemory="10000"
eternal="false"
timeToIdleSeconds="120"
timeToLiveSeconds="120"
overflowToDisk="true"
maxElementsOnDisk="1000000"
diskPersistent="false"
diskExpiryThreadIntervalSeconds="120"
memoryStoreEvictionPolicy="LRU"></defaultCache>
</ehcache>
(3)logback-test.xml
<?xml version="1.0" encoding="UTF-8" ?>
<configuration scan="true" scanPeriod="1800 seconds" debug="true">
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</encoder>
</appender>
<logger name="com.trgis" level="debug" additivity="true">
<appender-ref ref="STDOUT" />
</logger>
</configuration>
(4)
# Hibernate
hibernate.hbm2ddl.auto=update
hibernate.generateDdl=true
hibernate.showSql=true
hibernate.dialect=org.hibernate.spatial.dialect.sqlserver.SqlServer2008SpatialDialect
#===================================================
#MSSqlServer database settings
jdbc.driver=com.microsoft.sqlserver.jdbc.SQLServerDriver
jdbc.url=jdbc:jtds:sqlserver://****:1433;DatabaseName=***
jdbc.username=sa
jdbc.password=123456
将不定期更新资源,欢迎持续关注
想获得更多的学习知识请关注微信公众号:西北码农或扫下方二维码