Hibernate-Spatial 配置
==========================

您可前往 `电科金仓官网 <https://download.kingbase.com.cn/xzzx/index.htm>`_ 下载 `Hibernate-Spatial测试用例 <https://kingbase.oss-cn-beijing.aliyuncs.com/KES_INTERFACE/testyongli/hibernate-spatial/hibernate_5.2.17_Test.zip>`_ 。

配置说明
--------------------

使用Hibernate Spatial只需将配置文件中Hibernate方言包名称替换为对应版本的Hibernate Spatial方言包名称即可。

a. Hibernate Spatial 1 替换为：

   .. code:: PROGRAMLISTING

         org.hibernatespatial.postgis.PostgisESDialect

b. Hibernate Spatial 1 以上替换为：

   .. code:: PROGRAMLISTING

         org.hibernate.spatial.dialect.postgis.PostgisESDialect

举例说明
-------------------------

以Hibernate4为例：

a. Hibernate配置文件(hibernate.cfg.xml)示例

    .. code:: PROGRAMLISTING

           <?xml version='1.0' encoding='utf-8'?>
           <!DOCTYPE hibernate-configuration PUBLIC
               "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
               "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

           <hibernate-configuration>
               <session-factory>
                   <!-- 数据库连接设置 -->
                   <property name="connection.driver_class">org.postgresql.Driver</property>
                   <property name="connection.url">jdbc:postgresql://localhost:54321/test</property>
                   <property name="connection.username">system</property>
                   <property name="connection.password">123456</property>

                   <!-- 设置连接池大小 -->
                   <property name="connection.pool_size">1</property>

                   <!-- Spatial SQL方言 -->
                   <property name="dialect">
                       org.hibernate.spatial.dialect.postgis.PostgisESDialect
                   </property>

                   <!-- 启用Hibernate的自动会话上下文管理 -->
                   <property name="current_session_context_class">thread</property>

                   <!-- 禁用二级缓存提供类  -->
                   <property name="cache.provider_class">
                       org.hibernate.cache.NoCacheProvider
                   </property>

                   <!-- 是否展示SQL输出 -->
                   <property name="show_sql">true</property>

                   <!-- 启动时删除并重新创建数据库模式对象 -->
                   <property name="hbm2ddl.auto">create</property>

                   <mapping resource="org/hibernatespatial/entity/Event.hbm.xml"/>
               </session-factory>
           </hibernate-configuration>

b. Hibernate映射文件(event.hbm.xml)示例

   .. code:: PROGRAMLISTING

           <?xml version="1.0" encoding="UTF-8"?>
           <!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
               "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

           <hibernate-mapping package="org.hibernatespatial.entity">
               <class name="Event" table="EVENTS">

                   <id name="id" column="EVENT_ID">
                       <generator class="native"/>
                   </id>

                   <property name="date" type="timestamp" column="EVENT_DATE"/>

                   <property name="title" type="string"/>

                   <property name="location" type="org.hibernate.spatial.GeometryType" column="LOC"/>
                </class>
           </hibernate-mapping>

c. java对象(event)示例

   .. code:: PROGRAMLISTING

       import java.util.Date;

       import com.vividsolutions.jts.geom.Point;

       public class Event {
           private Long id;
           private String title;
           private Date date;
           private Point location;

           public Event() {
           }

           public Long getId() {
               return id;
           }

           public void setId(Long id) {
               this.id = id;
           }

           public Date getDate() {
               return date;
           }

           public void setDate(Date date) {
               this.date = date;
           }

           public String getTitle() {
               return title;
           }

           public void setTitle(String title) {
               this.title = title;
           }

           public Point getLocation() {
               return this.location;
           }

           public void setLocation(Point location) {
               this.location = location;
           }
       }

d. Hibernate获取SessionFactory

   .. code:: PROGRAMLISTING

       package org.hibernatespatial.util;

       import org.hibernate.*;
       import org.hibernate.cfg.*;

       public class HibernateUtil {

           private static final SessionFactory sessionFactory;

           static {
               try {
                   /* 从hibernate.cfg.xml文件中创建SessionFactory */
                   sessionFactory = new Configuration().configure().buildSessionFactory();
               } catch (Throwable ex) {
                   System.err.println("Initial SessionFactory creation failed." + ex);
                   throw new ExceptionInInitializerError(ex);
               }
           }

           public static SessionFactory getSessionFactory() {
               return sessionFactory;
           }

       }

e. Hibernate的java使用例子

   .. code:: PROGRAMLISTING

       package org.hibernatespatial.test;

       import org.hibernate.Session;
       import org.hibernatespatial.entity.Event;
       import org.hibernatespatial.util.HibernateUtil;

       import java.util.Date;

       import com.vividsolutions.jts.geom.Point;
       import com.vividsolutions.jts.geom.Geometry;
       import com.vividsolutions.jts.io.WKTReader;
       import com.vividsolutions.jts.io.ParseException;

       public class EventManager {

           public static void main(String[] args) {
                           EventManager mgr = new EventManager();

                           if (args[0].equals("store")) {
                               mgr.createAndStoreEvent("My Event", new Date(), assemble(args));
                           }

                           HibernateUtil.getSessionFactory().close();
           }

           private void createAndStoreEvent(String title, Date theDate, String wktPoint) {

               /* 创建一个WKTReader对象 */
               WKTReader fromText = new WKTReader();
               Geometry geom = null;
               try {
                   geom = fromText.read(wktPoint);
               } catch (ParseException e) {
                   throw new RuntimeException("Not a WKT string:" + wktPoint);
               }
               if (!geom.getGeometryType().equals("Point")) {
                   throw new RuntimeException("Geometry must be a point. Got a " + geom.getGeometryType());
               }

               Session session = HibernateUtil.getSessionFactory().getCurrentSession();

               session.beginTransaction();

               Event theEvent = new Event();
               theEvent.setTitle(title);
               theEvent.setDate(theDate);
               theEvent.setLocation((Point) geom);
               session.save(theEvent);

               session.getTransaction().commit();
           }

           /**
           * 将数组按顺序拼接成以空格符分割的String对象
           */
           private static String assemble(String[] args) {
               StringBuilder builder = new StringBuilder();
               for (int i = 1; i < args.length; i++) {
                   builder.append(args[i]).append(" ");
               }
               return builder.toString();
           }

       }
