Use Geometry and Polygon in Hibernate 5


Copy JAR files which are listed below:

antlr-2.7.7.jar
classmate-1.3.4.jar
commons-lang3-3.6.jar
commons-logging-1.1.3.jar
dom4j-1.6.1.jar
ehcache-core-2.6.11.jar
geolatte-geom-1.1.0.jar
hibernate-commons-annotations-5.0.1.Final.jar
hibernate-core-5.2.11.Final.jar
hibernate-ehcache-5.2.12.Final.jar
hibernate-ejb3-persistence.jar
hibernate-enhance-maven-plugin-4.3.7.Final.jar
hibernate-entitymanager.jar
hibernate-java8-5.2.11.Final.jar
hibernate-jpa-2.1-api-1.0.0.Final.jar
hibernate-spatial-5.2.11.Final.jar
hibernate-validator-6.0.2.Final.jar
javassist-3.16.1-GA.jar
jboss-logging-3.3.1.Final.jar
jboss-transaction-api_1.1_spec-1.0.1.Final.jar
jts-1.11.jar
mysql-connector-java-5.1.36.jar
slf4j-api-1.7.21.jar

Create a database with the name is hibernate5. This database have a table: Event table.

--
-- Table structure for table `event`
--

CREATE TABLE `event` (
  `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(250) NOT NULL,
  `location` geometry NOT NULL,
  `road` polygon DEFAULT NULL
) ENGINE=MyISAM DEFAULT CHARSET=latin1;

--
-- Dumping data for table `event`
--

INSERT INTO `event` (`name`, `location`, `road`) VALUES
(2, 'event 1', '\0\0\0\0\0\0\0\0\0\0\0\0\0$@\0\0\0\0\0\0@', '\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0ð?\0\0\0\0\0\0\0@\0\0\0\0\0\0\0@\0\0\0\0\0\04@\0\0\0\0\0\04@\0\0\0\0\0\0B@\0\0\0\0\0\0B@\0\0\0\0\0\0Y@\0\0\0\0\0\0ð?\0\0\0\0\0\0\0@');

Structures of Event Table

Student Table




Create a entity class – Event.java to represent the above table

Event.java

package entities;

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import static javax.persistence.GenerationType.IDENTITY;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import com.vividsolutions.jts.geom.*;

@Entity
@Table(name = "event")
public class Event implements java.io.Serializable {

	@Id
	@GeneratedValue(strategy = IDENTITY)
	private Long id;

	@Column
	private String name;

	@Column
	private Geometry location;

	@Column
	private Polygon road;

	public Polygon getRoad() {
		return road;
	}

	public void setRoad(Polygon road) {
		this.road = road;
	}

	public Long getId() {
		return id;
	}

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

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public Geometry getLocation() {
		return location;
	}

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

}

Hibernate Configuration File

Puts Event.java in your Hibernate configuration file, and also MySQL connection details.

<?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="hibernate.enable_lazy_load_no_trans">true</property>
		<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
		<property name="hibernate.connection.password">123456</property>
		<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/hibernate5</property>
		<property name="hibernate.connection.username">root</property>
		<property name="hibernate.dialect">org.hibernate.spatial.dialect.mysql.MySQLSpatialDialect</property>
		<property name="hibernate.current_session_context_class">thread</property>
		<mapping class="entities.Event" />
	</session-factory>
</hibernate-configuration>

The HibernateUtil class helps in creating the SessionFactory from the Hibernate configuration file. The SessionFactory is threadsafe, so it is not necessary to obtain one for each thread.

package spatial;

import org.hibernate.*;
import org.hibernate.boot.*;
import org.hibernate.boot.registry.*;

public class HibernateUtil {

	private static final SessionFactory sessionFactory;

	static {
		try {
			StandardServiceRegistry standardRegistry = new
					StandardServiceRegistryBuilder()
					.configure("hibernate.cfg.xml")
					.build();
			Metadata metaData = new MetadataSources(
					standardRegistry)
					.getMetadataBuilder()
					.build();
			sessionFactory = metaData.getSessionFactoryBuilder().build();
		} catch (Throwable th) {
			throw new ExceptionInInitializerError(th);
		}
	}

	public static SessionFactory getSessionFactory() {
		return sessionFactory;

	}
}




The EventModel class contains methods to interact with the database.

package spatial;

import java.util.List;
import org.hibernate.*;
import entities.*;

public class EventModel {

	private SessionFactory sessionFactory = HibernateUtil.getSessionFactory();

	public boolean create(Event event) {
		boolean result = true;
		Session session = null;
		Transaction transaction = null;
		try {
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			session.save(event);
			transaction.commit();
		} catch (Exception e) {
			result = false;
			if (transaction != null) {
				session.getTransaction().rollback();
			}
		} finally {
			session.close();
		}
		return result;
	}

	public List<Event> findAll() {
		List<Event> events = null;
		Session session = null;
		Transaction transaction = null;
		try {
			session = sessionFactory.openSession();
			transaction = session.beginTransaction();
			org.hibernate.query.Query query = session.createQuery("from Event");
			events = query.getResultList();
			transaction.commit();
		} catch (Exception e) {
			events = null;
			if (transaction != null) {
				transaction.rollback();
			}
		} finally {
			session.close();
		}
		return events;
	}

}
package spatial;

import com.vividsolutions.jts.geom.Coordinate;
import com.vividsolutions.jts.geom.GeometryFactory;
import com.vividsolutions.jts.geom.LinearRing;
import com.vividsolutions.jts.geom.Polygon;
import entities.Event;

public class Main {

	public static void main(String[] args) {

		EventModel eventModel = new EventModel();

		System.out.println("Add New Event");
		GeometryFactory geometryFactory = new GeometryFactory();
		Event newEvent = new Event();
		newEvent.setName("event 2");
		newEvent.setLocation(geometryFactory.createPoint(new Coordinate(10, 5)));

		// Add road to event
		Coordinate[] coordinates = new Coordinate[5];
		coordinates[0] = new Coordinate(1, 2); // Starting point
		coordinates[1] = new Coordinate(2, 20);
		coordinates[2] = new Coordinate(20, 36);
		coordinates[3] = new Coordinate(36, 100);
		coordinates[4] = new Coordinate(1, 2); // Ending point
		LinearRing linear = new GeometryFactory().createLinearRing(coordinates);
		Polygon poly = new Polygon(linear, null, geometryFactory);
		newEvent.setRoad(poly);
		System.out.println(eventModel.create(newEvent));

		System.out.println("List Events");
		for (Event event : eventModel.findAll()) {
			System.out.println("Name: " + event.getName());
			System.out.println("Geo x: " + event.getLocation().getCoordinate().x);
			System.out.println("Geo y: " + event.getLocation().getCoordinate().y);

			System.out.println("Road to event");
			Coordinate[] road = event.getRoad().getCoordinates();
			for (int j = 0; j < road.length; j++) {
				System.out.println("Point " + j + " - x: " + road[j].x);
				System.out.println("Point " + j + " - y: " + road[j].y);
				System.out.println("------------------------");
			}
		}
	}

}
Add New Event
true

List Events
Name: event 1
Geo x: 10.0
Geo y: 5.0
Road to event
Point 0 - x: 1.0
Point 0 - y: 2.0
------------------------
Point 1 - x: 2.0
Point 1 - y: 20.0
------------------------
Point 2 - x: 20.0
Point 2 - y: 36.0
------------------------
Point 3 - x: 36.0
Point 3 - y: 100.0
------------------------
Point 4 - x: 1.0
Point 4 - y: 2.0
------------------------

Name: event 2
Geo x: 10.0
Geo y: 5.0
Road to event
Point 0 - x: 1.0
Point 0 - y: 2.0
------------------------
Point 1 - x: 2.0
Point 1 - y: 20.0
------------------------
Point 2 - x: 20.0
Point 2 - y: 36.0
------------------------
Point 3 - x: 36.0
Point 3 - y: 100.0
------------------------
Point 4 - x: 1.0
Point 4 - y: 2.0
------------------------