Spring Data JPA - one to one mapping bidirectional - spring-boot

I have a table called symbols and symbol history,
Symbols
symbols(Pk)
SymbolsHistorical
id
symbols
Forign key name - symbols_fk (FK)
I created my HibernateMapping and in my DTO classes,
In SymbolsHistorical,
#OneToOne
#JoinColumn(foreignKey = #ForeignKey(name = "symbols_fk"))
private Symbols symbol;
I did in Symbols class,
#OneToOne(mappedBy = "symbol")
private SymbolsHistorical symbolsHistorical;
Whenever I need to read symbols, I need its symbolsHistorical as well,
Iam using findBySymbol method to get symbolsData. Whenever I do the above mapping, am getting,
Unknown column 'symbols0_.symbols_historical_id' in 'field list'
What am doing wrong?
Update:
Error
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755)
at com.fasterxml.jackson.databind.ser.BeanSerializer.serialize(BeanSerializer.java:178)
at com.fasterxml.jackson.databind.ser.BeanPropertyWriter.serializeAsField(BeanPropertyWriter.java:728)
at com.fasterxml.jackson.databind.ser.std.BeanSerializerBase.serializeFields(BeanSerializerBase.java:755)
[2m2021-07-05 15:31:29.458[0;39m [31mERROR[0;39m [35m76390[0;39m [2m---[0;39m [2m[nio-8080-exec-1][0;39m [36ms.e.ErrorMvcAutoConfiguration$StaticView[0;39m [2m:[0;39m Cannot render error page for request [/symbols/A] and exception [] as the response has already been committed. As a result, the response may have the wrong status code.

Taken from your tables the foreign key name is symbols.
So the mapping must be in Symbols class:
#OneToOne
#JoinColumn(name="symbols")
private Symbols symbol;
As you are using JSON serialization you will get a StackOverflowError because of the bi-directional mapping.
So you have to add an annotation to the Symbol or SymbolsHistorical class (depending on what you want to serialize) to break the loop.
For example
#JsonBackReference // this property will not be serialized
#OneToOne(mappedBy = "symbol")
private SymbolsHistorical symbolsHistorical;

Related

Unknown column in 'field list' in cascading persistance

I am using Spring Boot Version 2.5.2 , spring data jpa and MySQL Database
CREATE TABLE Timesheet (
`id` BIGINT(20) NOT NULL AUTO_INCREMENT,
`tsYear` VARCHAR(4) NOT NULL,
`weekNumber` INT NOT NULL,
`startDate` DATE NOT NULL,
`endDate` DATE NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE TimesheetDays (
`id` INT NOT NULL AUTO_INCREMENT,
`timesheetId` BIGINT(20) NOT NULL,
`dayNumber` INT NOT NULL,
`dayDate` DATE NOT NULL,
PRIMARY KEY (`id`),
CONSTRAINT `tsdTimesheetId`
FOREIGN KEY (`timesheetId`)
REFERENCES Timesheet (`id`)
);
#Entity
#Table(name = "timesheet")
public class Timesheet {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#OneToMany(cascade = {CascadeType.PERSIST, CascadeType.MERGE }, mappedBy = "timesheet")
private List<TimesheetDay> days = null;
}
#Entity
#Table(name = "timesheetdays")
public class TimesheetDay {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#ManyToOne
private Timesheet timesheet;
}
When i tried to save (timesheet and timesheetdays), for timesheetdays table, hibernate is
generating wrong column.
[2m2021-11-05 18:29:44.147[0;39m [32mDEBUG[0;39m [35m15036[0;39m [2m---[0;39m [2m[nio-8080-exec-2][0;39m [36morg.hibernate.SQL [0;39m [2m:[0;39m insert into timesheetdays (daydate, daynumber, timesheet_id) values (?, ?, ?)
[2m2021-11-05 18:29:44.147[0;39m [32mTRACE[0;39m [35m15036[0;39m [2m---[0;39m [2m[nio-8080-exec-2][0;39m [36mo.h.type.descriptor.sql.BasicBinder [0;39m [2m:[0;39m binding parameter [1] as [DATE] - [2017-12-20]
[2m2021-11-05 18:29:44.148[0;39m [32mTRACE[0;39m [35m15036[0;39m [2m---[0;39m [2m[nio-8080-exec-2][0;39m [36mo.h.type.descriptor.sql.BasicBinder [0;39m [2m:[0;39m binding parameter [2] as [INTEGER] - [1]
[2m2021-11-05 18:29:44.148[0;39m [32mTRACE[0;39m [35m15036[0;39m [2m---[0;39m [2m[nio-8080-exec-2][0;39m [36mo.h.type.descriptor.sql.BasicBinder [0;39m [2m:[0;39m binding parameter [3] as [INTEGER] - [18]
[2m2021-11-05 18:29:44.148[0;39m [33m WARN[0;39m [35m15036[0;39m [2m---[0;39m [2m[nio-8080-exec-2][0;39m [36mo.h.engine.jdbc.spi.SqlExceptionHelper [0;39m [2m:[0;39m SQL Error: 1054, SQLState: 42S22
[2m2021-11-05 18:29:44.148[0;39m [31mERROR[0;39m [35m15036[0;39m [2m---[0;39m [2m[nio-8080-exec-2][0;39m [36mo.h.engine.jdbc.spi.SqlExceptionHelper [0;39m [2m:[0;39m Unknown column 'timesheet_id' in 'field list'
Since the generated column name is timesheet_id, it is not working.
If the generated column name becomes timesheetid, it will work.
Please help to resolve this issue
You need to add the #JoinColumn annotation to give the column name value specifically in your TimesheetDay entity.
#ManyToOne
#JoinColumn(name="timesheetid")
private Timesheet timesheet;

Hibernate Envers audit Table Column Changes from jsonb to uuid

I have a jsonb column in an Entity annotated as shown in the sample code. Everything works fine without the #Audited annotation. Adding the Audited annotation creates the org_master_aud table with the column custom_fields of type uuid instead of jsonb and the insert fails
#TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
#Audited
public class OrgMaster {
#Type(type = "jsonb")
#Column(columnDefinition = "jsonb",name="custom_fields",nullable=false)
private JsonNode customFields;
}
org.springframework.orm.jpa.JpaSystemException: Unable to perform beforeTransactionCompletion callback: org.hibernate.exception.DataException: could not execute statement; nested exception is org.hibernate.HibernateException: Unable to perform beforeTransactionCompletion callback: org.hibernate.exception.DataException: could not execute statement
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:353)
.
.
.
.
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1352)
... 94 more
Caused by: org.postgresql.util.PSQLException: ERROR: invalid input syntax for type uuid: "{}"
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2578)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2313)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:331)
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:448)
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:369)
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:159)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:125)
at com.zaxxer.hikari.pool.ProxyPreparedStatement.executeUpdate(ProxyPreparedStatement.java:61)
at com.zaxxer.hikari.pool.HikariProxyPreparedStatement.executeUpdate(HikariProxyPreparedStatement.java)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:197)
... 105 more
Find below the Snapshots of the custom_fields column in main and audit table where the audit table column is uuid whereas the main table is jsonb. Both are autogenerated.
This issue was resolved after updating the hibernate version from 5.4.12.Final to 5.4.14.Final.
This was a bug introduced in versions > 5.4.10 and was fixed in 5.4.14. Here is the link to jira issue.
https://hibernate.atlassian.net/browse/HHH-13886

Spring data Cassandra Rest Id must be assignable to Serializable!: null

Given below Entity and Repository, I get Id must be assignable to Serializable!: null error when I access rest resource for repository.
curl -H 'Accept: application/json' http://localhost:8080/properties
{"cause":null,"message":"Id must be assignable to Serializable!: null"}
Groovy code
#Component
interface PropertyRepository extends CassandraRepository<Property, String> {
}
#Table("property_v1")
#Canonical
class Property {
#PrimaryKeyColumn(value = "name", type = PARTITIONED)
String name
#PrimaryKeyColumn(value = "environment", type = CLUSTERED)
String environment
#Column("value")
String value
}
I tried adding #Id annotation to primary key field but spring does not allow #Id and #PrimaryKeyColumn annotations on the same entity.
I get #Table types must not define both #Id and #PrimaryKeyColumn properties error.
How do I access spring data Cassandra entities over rest?
I tried using RepositoryRestResource annotation as well on Repository class but received same error.
#RepositoryRestResource(path = "/properties", collectionResourceRel = "properties")
Versions:
Spring boot: 2.0.1.RELEASE
Uses spring-boot-starter-data-cassandra, spring-boot-starter-data-rest moduldes
Exception Stacktrace:
java.lang.IllegalArgumentException: Id must be assignable to Serializable!: null
at org.springframework.util.Assert.instanceCheckFailed(Assert.java:637)
at org.springframework.util.Assert.isInstanceOf(Assert.java:537)
at org.springframework.data.rest.webmvc.support.RepositoryEntityLinks.linkToSingleResource(RepositoryEntityLinks.java:135)
at org.springframework.data.rest.core.support.DefaultSelfLinkProvider.createSelfLinkFor(DefaultSelfLinkProvider.java:68)
at org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler.getSelfLinkFor(PersistentEntityResourceAssembler.java:99)
at org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler.wrap(PersistentEntityResourceAssembler.java:76)
at org.springframework.data.rest.webmvc.PersistentEntityResourceAssembler.toResource(PersistentEntityResourceAssembler.java:55)
at org.springframework.data.rest.webmvc.AbstractRepositoryRestController.entitiesToResources(AbstractRepositoryRestController.java:110)
at org.springframework.data.rest.webmvc.AbstractRepositoryRestController.toResources(AbstractRepositoryRestController.java:80)
at org.springframework.data.rest.webmvc.RepositoryEntityController.getCollectionResource(RepositoryEntityController.java:209)
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:498)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:209)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:136)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:102)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:877)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:783)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:991)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:925)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:974)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:866)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:622)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:851)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:230)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:192)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:165)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:99)
Figured out the issue.
If an entity class has a composite key, spring data rest works only if I have a dedicated class for Primary Key columns.
Changing the class structure to below, enabled rest resources for spring data entities. I used a nested static class for key. But it could be very well a public class of its own.
I feel this boiler plate should be removed from developers and instead spring could look into partition key column and use it as Id.
#Component
interface PropertyRepository extends CassandraRepository<Property, Property.PropertyKey> {
}
#Table("property_v1")
#Canonical
class Property {
#PrimaryKey
PropertyKey key
#Column("value")
String value
#PrimaryKeyClass
#Canonical
static class PropertyKey implements Serializable {
#PrimaryKeyColumn(value = "name", type = PARTITIONED)
String name
#PrimaryKeyColumn(value = "environment", type = CLUSTERED)
String environment
}
}

Spring could not create EntityManagerFactory after upgrading to Hibernate 5.x

I'm using latest springframework disto v4.2.5.RELEASE and Hibernate v5.0.7.Final when spring loads EntityManagerFactory i'm getting the below exception
Caused by: org.hibernate.HibernateException: Not all named super-types (extends) were found : [com.sample.model.Sample]
at org.hibernate.boot.model.source.internal.hbm.EntityHierarchyBuilder.buildHierarchies(EntityHierarchyBuilder.java:76)
at org.hibernate.boot.model.source.internal.hbm.HbmMetadataSourceProcessorImpl.<init>(HbmMetadataSourceProcessorImpl.java:66)
at org.hibernate.boot.model.source.internal.hbm.HbmMetadataSourceProcessorImpl.<init>(HbmMetadataSourceProcessorImpl.java:40)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess$1.<init>(MetadataBuildingProcess.java:142)
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:141)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:847)
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:874)
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:60)
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:343)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:319)
The same code was working with v4.2.5.RELEASE and Hibernate v.4.3.10.
I know Hibernate changed core metadata building in v5.x, is there anything needs to be specified in spring config of JPA/EntityManagerFactory/Hibernate Properties to make it work with Hibernate 5.x?
#Entity
#Table(name = "tbl_sample")
public class Sample extends Auditable {
private Long id;
#ManyToOne
#JoinColumn(name = "relationA", nullable = true)
private RelationA relationA;
... etc
}
#MappedSuperClass
public abstract class Auditable extends Persistable {
//audit props
}
#MappedSuperClass
public abstract class Persistable {
//common props
}
I could able to narrow down the issue after enabling trace log, there was one more class which is extending Sample Class and its mapped using hbm.xml like below
<hibernate-mapping package="com.sample.model">
<joined-subclass name="BloodSample" table="tbl_blood_sample"
extends="com.sample.model.Sample">
<key column="ID" />
<property name="sampleNo" column="sampleNo"/>
etc....
</joined-subclass>
The moment i removed this relation hbm it started working... Still wondering why its happening now which was not in older version of hibernate.
So i guess this issue is nothing to do with spring but something related hibernate. Any insight ?
I have a similar your issue.
You try to class tag instead joined-subclass tag in hbm.xml file

How do i tell EclipseLink to stop ServerSession Connection Queries

When looking at my stack trace log, i have noticed that whenever i run any queries using the entity manager or EL (JPA 2.0) provided methods em.find(), findAll() ..., there is an Injected bean from all related entites that trigger n queries depending on the relationship. I have succesfully enabled weaving with tomcat using the spring.instruments jar and i am very sure that weaving is happening and my #OneToOne, #ManyToOne lazy settings are being set and woven in time. The problem might be how i query and the ServerSession connection that executes multiple queries.
The stack trace that shows this :
[EL Fine]: sql: 2012-07-04 22:26:20.959--ServerSession(1528617164)--Connection(1657707912)--Thread(Thread[tomcat-http--9,5,main])--SELECT personID, TYPE, DATEADDED, FIRSTNAME, LASTNAME, MIDDLENAME, ACTIVE, BIRTHDAY, EMAILADDRESS, ETHNICITY, GENDER, HISPANIC, IMAGEPATH, MARITAL, NATIVELANGUAGE, PRIMARYTELEPHONE, RELIGIOUSAFFILIATION, SECONDARYTELEPHONE, version, addressID, schoolID, MAJOR, studentId FROM PERSON WHERE (personID = ?)
bind => [101]
2012-07-04 22:26:20,963 [tomcat-http--9] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.Administrator': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.Person.entityManager
2012-07-04 22:26:20,964 [tomcat-http--9] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
2012-07-04 22:26:20,964 [tomcat-http--9] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.Administrator': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.Person.entityManager
2012-07-04 22:26:20,965 [tomcat-http--9] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
[EL Fine]: sql: 2012-07-04 22:26:20.966--ServerSession(1528617164)--Connection(264950364)--Thread(Thread[tomcat-http--9,5,main])--SELECT addressID, CITY, COUNTRY, STATE_US, STREETADDRESS, STREETADDRESS2, version, ZIPCODE FROM ADDRESS WHERE (addressID = ?)
bind => [3]
2012-07-04 22:26:20,970 [tomcat-http--9] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.Address': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.Address.entityManager
2012-07-04 22:26:20,971 [tomcat-http--9] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
[EL Fine]: sql: 2012-07-04 22:26:20.972--ServerSession(1528617164)--Connection(255059556)--Thread(Thread[tomcat-http--9,5,main])--SELECT personID, TYPE, DATEADDED, FIRSTNAME, LASTNAME, MIDDLENAME, ACTIVE, BIRTHDAY, EMAILADDRESS, ETHNICITY, GENDER, HISPANIC, IMAGEPATH, MARITAL, NATIVELANGUAGE, PRIMARYTELEPHONE, RELIGIOUSAFFILIATION, SECONDARYTELEPHONE, version, addressID, schoolID, MAJOR, studentId FROM PERSON WHERE (addressID = ?)
bind => [3]
2012-07-04 22:26:20,975 [tomcat-http--9] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.Student': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.Person.entityManager
2012-07-04 22:26:20,976 [tomcat-http--9] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
2012-07-04 22:26:20,976 [tomcat-http--9] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.Student': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.Person.entityManager
2012-07-04 22:26:20,977 [tomcat-http--9] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
[EL Fine]: sql: 2012-07-04 22:26:20.98--ServerSession(1528617164)--Connection(2062869828)--Thread(Thread[tomcat-http--9,5,main])--SELECT schoolID, ACTIVE, ADMISSIONSEMAILADDRESS, ADMISSIONSPHONE, CODE, description, HELPGENERALEMAILADDRESS, NAME, PRIMARYPHONE, version, addressID FROM SCHOOL WHERE (schoolID = ?)
bind => [3]
2012-07-04 22:26:20,982 [tomcat-http--9] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.School': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.School.entityManager
2012-07-04 22:26:20,982 [tomcat-http--9] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
[EL Fine]: sql: 2012-07-04 22:26:20.983--ServerSession(1528617164)--Connection(140234280)--Thread(Thread[tomcat-http--9,5,main])--SELECT id, ACTIVE, CODE, DESCRIPTION, NAME, version, SCHOOLDEPARTMENT_schoolID FROM DEPARTMENT WHERE (SCHOOLDEPARTMENT_schoolID = ?)
bind => [3]
[EL Fine]: sql: 2012-07-04 22:26:20.986--ServerSession(1528617164)--Connection(1812702959)--Thread(Thread[tomcat-http--9,5,main])--SELECT personID, TYPE, DATEADDED, FIRSTNAME, LASTNAME, MIDDLENAME, ACTIVE, BIRTHDAY, EMAILADDRESS, ETHNICITY, GENDER, HISPANIC, IMAGEPATH, MARITAL, NATIVELANGUAGE, PRIMARYTELEPHONE, RELIGIOUSAFFILIATION, SECONDARYTELEPHONE, version, addressID, schoolID, MAJOR, studentId FROM PERSON WHERE (schoolID = ?)
bind => [3]
How to ignore cache and return right away after executing a query on an entity manager object?
#RooJavaBean
#RooToString
#RooJpaActiveRecord(identifierColumn = "addressID")
public class Address {
#Id
#TableGenerator(name = "ADDRESS_TABLE_GEN", table = "ADDRESS_SEQUENCE_TABLE", pkColumnName = "SEQ_NAME", valueColumnName = "SEQ_COUNT", pkColumnValue = "ADDR_SEQ", allocationSize = 1, initialValue = 1)
#GeneratedValue(strategy = GenerationType.TABLE, generator = "ADDRESS_TABLE_GEN")
#Column(name = "addressID")
private Long id;
#BatchFetch(BatchFetchType.JOIN)
#OneToMany(cascade = CascadeType.ALL, mappedBy = "address", fetch = FetchType.EAGER)
private Set<Person> persons = new HashSet<Person>();
Applicant entity
public class Applicant extends Person {
private String major;
#BatchFetch(BatchFetchType.JOIN)
#OneToMany(targetEntity = ApplicantSchool.class, cascade = { javax.persistence.CascadeType.PERSIST, javax.persistence.CascadeType.REMOVE }, mappedBy = "applicant", fetch = FetchType.EAGER)
private Set<ApplicantSchool> schools = new HashSet<ApplicantSchool>();
}
Stack Trace; Reverting a particular OneToOne mapping
[TomcatInstrumentableClassLoader#747917a] error aspect 'org.springframework.orm.jpa.aspectj.JpaExceptionTranslatorAspect' woven into 'org.bixin.dugsi.domain.Registration_Roo_Jpa_ActiveRecord' must be defined to the weaver (placed on the aspectpath, or defined in an aop.xml file if using LTW).
[TomcatInstrumentableClassLoader#747917a] error aspect 'org.springframework.mock.staticmock.AnnotationDrivenStaticEntityMockingControl' woven into 'org.bixin.dugsi.domain.Registration_Roo_Jpa_ActiveRecord' must be defined to the weaver (placed on the aspectpath, or defined in an aop.xml file if using LTW).
2012-07-06 17:08:34,910 ["http-bio-8080"-exec-1] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Found injected element on class [org.bixin.dugsi.domain.Registration]: PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.Registration.entityManager
2012-07-06 17:08:34,910 ["http-bio-8080"-exec-1] DEBUG org.springframework.beans.factory.annotation.InjectionMetadata - Processing injected method of bean 'org.bixin.dugsi.domain.Registration': PersistenceElement for transient javax.persistence.EntityManager org.bixin.dugsi.domain.Registration.entityManager
2012-07-06 17:08:34,911 ["http-bio-8080"-exec-1] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'entityManagerFactory'
2012-07-06 17:08:34,914 ["http-bio-8080"-exec-1] DEBUG org.springframework.beans.factory.support.DefaultListableBeanFactory - Returning cached instance of singleton bean 'org.apache.shiro.spring.security.interceptor.AuthorizationAttributeSourceAdvisor#0'
[EL Warning]: metadata: 2012-07-06 17:08:34.968--ServerSession(1433743869)--Thread(Thread["http-bio-8080"-exec-1,5,main])--Reverting the lazy setting on the OneToOne or ManyToOne attribute [person] for the entity class [class org.bixin.dugsi.domain.UserAccount] since weaving was not enabled or did not occur.
This is the field EL is referring to
#OneToOne(targetEntity = Person.class, fetch = FetchType.LAZY)
#JoinColumn
private Person person;
You are specifying FetchType.EAGER in both the relationships you've shown, so they must always be fetched when building the source objects. As mentioned, the problem seems to be reading in Person (or Applicant) which causes Address to be fetched. Chances are that the 'address' ManyToOne in Person is also marked eager. This causes Addresses to be built, and because you have a 1:M from Address->Applicant, this query must go to the database to make sure that it fetched all Applicants.
This same senario happens on all the referenced eagerly fetched entities, and is why it is a bad idea to have everything marked eager unless it is neccessary, especially OneToMany and ManyToMany relationships. I'd recommend you change them to lazy and only fetch them as required when the relationship is accessed, or use fetch join in queries or query hints to prefetch particular relationships that will be needed.

Resources