我正在进行一个Spring Boot项目,我疯狂地试图正确地映射一个MySql DB的点字段(它是MariaDB,但它是同样的事情...)。
要检索数据,我使用Hibernate 5上的Spring Data JPA。
我的DB上有一张住宿表:
Field Type Null Key Default Extra
id bigint(20) unsigned NO PRI NULL auto_increment
user_id bigint(20) unsigned NO MUL NULL
accomodation_name varchar(255) NO NULL
description text NO NULL
nation varchar(255) NO NULL
region varchar(255) NO NULL
province varchar(255) NO NULL
city varchar(255) NO NULL
geographical_position point NO NULL
stars int(10) NO NULL
accomodation_typological_id bigint(20) unsigned YES NULL
accomodation_service_id bigint(20) unsigned YES NULL
phone varchar(255) YES NULL
mobile varchar(255) YES NULL
fax varchar(255) YES NULL
email varchar(255) YES NULL
time_stamp datetime YES NULL
如您所见,此表包含字段geographical_position具有点作为数据类型(归因于MySql opengGIS实现)。
上表由该住宿类别映射:
import com.vividsolutions.jts.geom.Point;
import org.hibernate.annotations.Type;
import javax.persistence.*;
import java.io.Serializable;
import java.math.BigInteger;
import java.util.List;
/**
* Created by Yngve on 30/09/16.
*/
@Entity
@Table(name = "accomodation")
public class Accomodation implements Serializable {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "id")
private Long id;
/*@ManyToOne
private Users users;
*/
@OneToMany(mappedBy = "accomodation")
private List<Room> rooms;
@Column(name = "accomodation_name")
private String name;
@Column(name = "description")
@Type(type="text")
private String description;
private String phone;
private String mobile;
private String fax;
private String email;
private Integer stars;
@Column(name = "geographical_position", columnDefinition="Point")
private Point location;
public Accomodation(){
}
// GETTER AND SETTER METHODS
}
如您所见,表上的上一个点字段由我的Java类上的该字段映射:
@Column(name = "geographical_position", columnDefinition="Point")
private Point location;
在前面的代码片段中,我还插入了所使用的Point实现的导入,由(我在一些教程中发现的)提供:
import com.vividsolutions.jts.geom.Point;
但我绝对不能确定这是必须使用的正确类。
这是实现Spring数据JPA查询的我的DAO类(该查询由Spring数据JPA使用方法签名生成):
@Repository
@Transactional(propagation = Propagation.MANDATORY)
public interface AccomodationDAO extends JpaRepository<Accomodation, Long> {
//@Query("FROM Accomodation WHERE id = :id")
Accomodation findById(@Param("id") Long id);
}
问题在于使用此JUnuit测试方法测试以前的DAO方法:
@Test
public void placeSearcherControllerTest() {
System.out.println("placeSearcherControllerTest START");
Accomodation accomodation = accomodationDAO.findById(6L);
System.out.println("placeSearcherControllerTest END");
}
我在IntelliJ控制台中获得以下错误消息:
Hibernate: select accomodati0_.id as id1_0_, accomodati0_.description as descript2_0_, accomodati0_.email as email3_0_, accomodati0_.fax as fax4_0_, accomodati0_.geographical_position as geograph5_0_, accomodati0_.mobile as mobile6_0_, accomodati0_.accomodation_name as accomoda7_0_, accomodati0_.phone as phone8_0_, accomodati0_.stars as stars9_0_ from accomodation accomodati0_ where accomodati0_.id=?
org.springframework.orm.jpa.JpaSystemException: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:333)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:244)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:491)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:59)
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:213)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:147)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:133)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:92)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:213)
at com.sun.proxy.$Proxy112.findById(Unknown Source)
at com.betriuvis.controller.test.PlaceSearcherControllerTest.placeSearcherControllerTest(PlaceSearcherControllerTest.java:58)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:117)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:42)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:262)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:84)
Caused by: org.hibernate.type.SerializationException: could not deserialize
at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:243)
at org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:287)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:138)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:113)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:27)
at org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:60)
at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:238)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:234)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:224)
at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:300)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:2738)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1729)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1655)
at org.hibernate.loader.Loader.getRow(Loader.java:1544)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:727)
at org.hibernate.loader.Loader.processResultSet(Loader.java:972)
at org.hibernate.loader.Loader.doQuery(Loader.java:930)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
at org.hibernate.loader.Loader.doList(Loader.java:2617)
at org.hibernate.loader.Loader.doList(Loader.java:2600)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2429)
at org.hibernate.loader.Loader.list(Loader.java:2424)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:501)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:371)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:216)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1326)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87)
at org.hibernate.jpa.internal.QueryImpl.list(QueryImpl.java:606)
at org.hibernate.jpa.internal.QueryImpl.getSingleResult(QueryImpl.java:529)
at org.hibernate.jpa.criteria.compile.CriteriaQueryTypeQueryAdapter.getSingleResult(CriteriaQueryTypeQueryAdapter.java:54)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:372)
at com.sun.proxy.$Proxy119.getSingleResult(Unknown Source)
at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:210)
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:82)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:114)
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:104)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.doInvoke(RepositoryFactorySupport.java:482)
at org.springframework.data.repository.core.support.RepositoryFactorySupport$QueryExecutorMethodInterceptor.invoke(RepositoryFactorySupport.java:460)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:61)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:136)
... 36 more
Caused by: java.io.StreamCorruptedException: invalid stream header: 00000000
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:806)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:299)
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:309)
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:299)
at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:218)
... 86 more
问题当然是由住宿类的映射引起的:
@Column(name = "geographical_position", columnDefinition="Point")
private Point location;
因为如果我从我的实体类中删除这个字段,我没有例外,我正确地检索了Accomodation对象(不包含location字段)。
查看前面的错误输出,我可以看到Hibernate生成了这个SQL查询:
select accomodati0_.id as id1_0_, accomodati0_.description as descript2_0_, accomodati0_.email as email3_0_, accomodati0_.fax as fax4_0_, accomodati0_.geographical_position as geograph5_0_, accomodati0_.mobile as mobile6_0_, accomodati0_.accomodation_name as accomoda7_0_, accomodati0_.phone as phone8_0_, accomodati0_.stars as stars9_0_ from accomodation accomodati0_ where accomodati0_.id=6
直接在我的数据库上执行,我获得了正确的记录。作为上一个点域的内容,我可以看到这个值[几何体-25B](什么意思是25B?)下载的文件名为accomodation-geographical_position。箱子
在DB上执行此其他查询:
select id, AsText(geographical_position) from accomodation where id = 6
我正确获取了地理位置字段中包含的坐标,事实上,我获得了查询输出:
id AsText(geographical_position)
--------------------------------------
6 POINT(41.729086 12.278478)
因此数据被正确地存储到具有点作为数据类型的geographical_position中。
所以这个问题与geographical_position字段到实体类的Point位置的映射有关。
在stackoverflow上搜索在我看来,该组织。冬眠类型SerializationException:无法反序列化异常当Hibernate无法将字段的值放入特定Java对象时会发生某种情况,因此我对导入com有一些疑问。生动的解决方案。jts。geom。Point used类用于映射Point数据库字段(可能这是旧版本Hibrnate Spatial或类似的东西上使用的类?)
或者可能是Spring启动配置问题,所以我在这里也放了我的应用程序。表示整个应用程序配置的属性文件:
#No auth protected
endpoints.shutdown.sensitive=true
#Enable shutdown endpoint
endpoints.shutdown.enabled=true
logging.file=BeTriviusController.log
logging.level.org.springframework.web=DEBUG
logging.level.org.hibernate=ERROR
# Thymeleaf
spring.thymeleaf.cache:false
# DATABASE CONFIG ----------------------------------------------------------------------------------------------------
spring.datasource.url = jdbc:mysql://localhost:3306/betriviustest
spring.datasource.username = root
spring.datasource.password =
spring.datasource.driver-class-name = com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.current_session_context_class=org.springframework.orm.hibernate4.SpringSessionContext
spring.datasource.testWhileIdle = true
spring.datasource.validationQuery = SELECT 1
# Show or not log for each sql query
spring.jpa.show-sql = true
# Hibernate ddl auto (create, create-drop, update, validate)
spring.jpa.hibernate.ddl-auto = validate
#spring.jpa.hibernate.naming-strategy = org.hibernate.cfg.ImprovedNamingStrategy
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect
也许这与Hibernate的空间配置有关?(我觉得有点奇怪,因为据我所知,它直接包含在Hibernate 5中,不再是一个需要添加和配置的外部项目)。
最后,这是我的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>
<groupId>BeTriviusController</groupId>
<artifactId>BeTriviusController</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<springboot.version>1.4.1.RELEASE</springboot.version>
</properties>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>1.4.1.RELEASE</version>
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<!--dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
</dependency>
<dependency>
<groupId>org.assertj</groupId>
<artifactId>assertj-core</artifactId>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>RELEASE</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-spatial</artifactId>
<version>5.0.1.Final</version>
<!--<version>4.0</version>-->
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
那么,怎么了?我错过了什么?如何解决此问题,并将实体类的点位置正确映射为数据类型为Point的地理位置表字段上的值?
也许这个问题发生在尝试序列化时:电话、手机、传真、电子邮件和星星。您应该在这些字段上添加@列注释。对于它应该工作的位置:@列(列定义="几何")@类型(类型="org.hibernate.spatial.几何类型")
我也有同样的问题,并且能够想出一个解决方案。因为,正如你最初指出的那样,mysql函数ST_ASTEXT(column_name)
完美地工作,这意味着数据绝对存储正确。
我意识到了这一点,并决定在此基础上构建解决方案。下面是我的@Entity
中的一个片段。
@Entity
@Table(name = "formEntryData")
public class FormEntryData {
...
@Formula("ST_ASTEXT(data_geo)")
private String dataGeo;
public Geometry getDataGeo() {
try {
WKTReader reader = new WKTReader();
return reader.read(dataGeo);
} catch (ParseException ex) {
return null;
}
}
}
然后,您需要做的是设置JacksonObjectMapper
,以便com。生动的解决方案。jts。geom*
(即,
几何体
,点
等)可以序列化为JSON。
为此,请将此依赖项添加到依赖项管理器(我使用了maven):
<dependency>
<groupId>com.bedatadriven</groupId>
<artifactId>jackson-datatype-jts</artifactId>
<version>2.3</version>
</dependency>
然后,您只需要将其与Spring Boot的配置机制连接起来。
@Configuration
public class JacksonConfig {
@Bean
public JtsModule jtsModule() {
return new JtsModule();
}
}
瞧!您现在可以从mysql读取几何类型并输出接受的GeoJSON格式!希望有帮助!
我想从sqlite数据库添加的数据中在listview中显示我的所有数据。当我单击save按钮时,它显示一条消息“added successful”。但每次它都显示错误消息“data not found”。为什么不显示listview? 错误显示如下: MyDatabaseHelper.java
我有一个Spring Data JPA项目来访问我的数据库并检索用户凭据。我将这个项目打包为jar(不是可执行jar),并将其作为maven依赖项包含到另一个Spring boot项目中,因为我想重用以前开发的相同实体和存储库。每次运行Spring Boot应用程序时,都会出现以下错误: 我开始怀疑我正在做的事情是否可能?PS:我不想将JPA项目与控制器和服务项目混合在一起
所以,实际上我对Java编程语言还是新手,并且还在学习如何转换数据类型,所以在这种情况下,我很难将字节转换为短字节。你们能帮帮我吗?? 所以在这种情况下,我可以正常地从(int)转换为(long)数据类型,因为(long)数据大小大于(int)。这与我尝试将其从(short)转换为(int)时的情况相同。但为什么我不能使用这个概念将数据类型从(byte)转换为(short)??即使(短)数据大小大
描述:com.cavion.services.UserDataService中得字段userDataRepo需要一个名为“Entity ManagerFactory”得bean,但找不到该bean.操作:考虑在您的配置中定义一个名为'Entity ManagerFactory‘的bean。 我需要在我的JPA存储库上指定entityManagerFactoryRef。 但是我有许多存储库类,其中一
我在Spring Batch上有点麻烦。我正处于这种情况:我必须分析文件中的数据,并将所有内容插入数据库(Oracle)。我面临的问题是,当我试图配置用于保存数据的数据库时,应用程序崩溃并关闭。我有一条错误消息: Application.Properties 用于配置数据库的MultipleDBConfig.java Bean
问题内容: 我正在尝试配置Spring + Hibernate + JPA以使用两个数据库(MySQL和MSSQL)。 我的datasource-context.xml: 每个persistence.xml包含一个单元,如下所示: PersistenceUnitManager导致以下异常: 如果只留下一个没有列表的persistence.xml,则每个列表都可以正常工作,但我需要2个单元… 我还尝