[resolvido] id composto e relacionamentos

Olá pessoal,

Tenho o seguinte problema:
Criei classes espelhando uma base que não posso modificar, esta base usa em suas tabelas chaves compostas (oracle).
Sem relacionamentos as classes/entidades funcionam perfeitamente, porém, quando eu crio um relacionamento daí começam os erros.

Fiz da seguinte forma:


@Table(name="PLANO_CONTAS", schema="NBS")
@Entity
@IdClass(PlanoContaPK.class)
public class PlanoConta implements Serializable{

	private static final long serialVersionUID = 1L;

	@Id
	@Column(name="cod_grupo_pc",insertable=false,updatable=false)
	private Long cod_grupo_pc;
	
	@Id
	@Column(name="cod_contabil",insertable=false,updatable=false)
	private String cod_contabil;
	
	@Id
	@Column(name="cod_centro_custo",insertable=false,updatable=false)
	private Long cod_centro_custo;
	
	private CentroCusto centroCusto;
	
	@ManyToOne
	@JoinColumns(
		{
			@JoinColumn(name="cod_grupo_pc", referencedColumnName="cod_grupo_pc", insertable=false, updatable=false),  
			@JoinColumn(name="cod_centro_custo", referencedColumnName="cod_centro_custo", insertable=false, updatable=false)
		}
	)
	@Columns( // colunas que representa o atributo
			columns = {
				@Column(name="cod_grupo_pc"),
				@Column(name="cod_centro_custo"),
			}
	)
	public CentroCusto getCentroCusto() {
		return centroCusto;
	}


... getters and setters ...

}

CentroCusto tem muitos PlanoConta


@Table(name="CENTRO_CUSTO", schema="NBS")
@Entity
@IdClass(CentroCustoPK.class)
public class CentroCusto implements Serializable{

	private static final long serialVersionUID = 1L;

	@Id
	@Column(insertable=false,updatable=false)
	private Long cod_centro_custo;
	
	@Id
	@Column(insertable=false,updatable=false)
	private Long cod_grupo_pc;

	private Collection<PlanoConta> planoConta;

        @OneToMany(mappedBy="centroCusto")
	public Collection<PlanoConta> getPlanoConta() {
		return planoConta;
	}
	public void setPlanoConta(Collection<PlanoConta> planoConta) {
		this.planoConta = planoConta;
	}

... getters and setters ...

}

O erro:


...

DEBUG [Thread-1] (Configuration.java:1167) - processing extends queue
DEBUG [Thread-1] (Configuration.java:1171) - processing collection mappings
DEBUG [Thread-1] (Configuration.java:1182) - processing native query and ResultSetMapping mappings
DEBUG [Thread-1] (Configuration.java:1190) - processing association property references
DEBUG [Thread-1] (Configuration.java:1212) - processing foreign key constraints
 INFO [Thread-1] (AnnotationConfiguration.java:369) - Hibernate Validator not found: ignoring
 INFO [Thread-1] (DefaultSingletonBeanRegistry.java:421) - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@754fc: defining beans [defaultMultipartConfig,asmBasedTypeCreator,defaultRestDefaults,defaultMethodNotAllowedHandler,JSR303ValidatorFactory,defaultTypeFinder,defaultAcceptHeaderToFormat,encodingHandlerFactory,paranamerNameProvider,XStreamXMLDeserializer,defaultInterceptorHandlerFactory,hibernateProxyInitializer,pathAnnotationRoutesParser,noRoutesConfiguration,objenesisProxifier,validatorFactoryCreator,messageInterpolatorFactory,defaultTypeNameExtractor,defaultRouter,defaultInterceptorRegistry,defaultRoutes,defaultResourceTranslator,defaultResourceNotFoundHandler,defaultDeserializers,defaultConverters,stereotypeHandler,converterHandler,interceptorStereotypeHandler,deserializesHandler,stereotypedBeansRegistrar,defaultSpringLocator,XStreamJSONSerialization,interceptorListPriorToExecutionExtractor,emptyElementsRemoval,applicationConfiguration,parametersInstantiatorInterceptor,forwardToDefaultViewInterceptor,XStreamXMLSerialization,defaultRepresentationResult,defaultLogicResult,defaultHttpResult,defaultValidator,deserializingInterceptor,jsonDeserializer,exceptionHandlerInterceptor,jstlLocalization,servlet3MultipartInterceptor,downloadInterceptor,resourceLookupInterceptor,ognlParametersProvider,defaultExceptionMapper,defaultFormatResolver,defaultPageResult,emptyResult,outjectResult,defaultStatus,executeMethodInterceptor,instantiateInterceptor,JSR303Validator,defaultPathResolver,defaultRestHeadersHandler,defaultValidationViewsFactory,defaultRefererResult,defaultMethodInfo,defaultResult,replicatorOutjector,flashInterceptor,HTMLSerialization,bigDecimalConverter,bigIntegerConverter,booleanConverter,byteConverter,characterConverter,doubleConverter,enumConverter,floatConverter,integerConverter,localeBasedCalendarConverter,localeBasedDateConverter,longConverter,primitiveBooleanConverter,primitiveByteConverter,primitiveCharConverter,primitiveDoubleConverter,primitiveFloatConverter,primitiveIntConverter,primitiveLongConverter,primitiveShortConverter,shortConverter,uploadedFileConverter,VRaptorRequestProvider,httpServletRequestProvider,httpServletResponseProvider,httpSessionProvider,defaultRequestExecution,defaultInterceptorStack,planoContaController,planoContaDAO,criadorDeSession,criadorDeSessionFactoryScoped,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.aop.config.internalAutoProxyCreator,cacheBasedTypeCreator]; root of factory hierarchy
11/04/2011 12:41:26 org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter vraptor
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'criadorDeSessionFactoryScoped': Invocation of init method failed; nested exception is org.hibernate.MappingException: Could not determine type for: java.util.Collection, at table: CENTRO_CUSTO, for columns: [org.hibernate.mapping.Column(planoConta)]
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:133)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.applyBeanPostProcessorsBeforeInitialization(AbstractAutowireCapableBeanFactory.java:394)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1394)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:512)
	at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:450)
	at org.springframework.beans.factory.support.AbstractBeanFactory$1.getObject(AbstractBeanFactory.java:290)
	at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222)
	at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:287)
	at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:189)
	at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:557)
	at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:842)
	at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:416)
	at br.com.caelum.vraptor.ioc.spring.SpringBasedContainer.start(SpringBasedContainer.java:68)
	at br.com.caelum.vraptor.ioc.spring.SpringProvider.start(SpringProvider.java:82)
	at br.com.caelum.vraptor.VRaptor.init(VRaptor.java:110)
	at br.com.caelum.vraptor.VRaptor.init(VRaptor.java:103)
	at org.apache.catalina.core.ApplicationFilterConfig.initFilter(ApplicationFilterConfig.java:273)
	at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:254)
	at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:372)
	at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:98)
	at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4461)
	at org.apache.catalina.core.StandardContext$2.call(StandardContext.java:5133)
	at org.apache.catalina.core.StandardContext$2.call(StandardContext.java:5128)
	at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
	at java.util.concurrent.FutureTask.run(FutureTask.java:138)
	at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
	at java.lang.Thread.run(Thread.java:619)
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.Collection, at table: CENTRO_CUSTO, for columns: [org.hibernate.mapping.Column(planoConta)]
	at org.hibernate.mapping.SimpleValue.getType(SimpleValue.java:292)
	at org.hibernate.mapping.SimpleValue.isValid(SimpleValue.java:276)
	at org.hibernate.mapping.Property.isValid(Property.java:207)
	at org.hibernate.mapping.PersistentClass.validate(PersistentClass.java:458)
	at org.hibernate.mapping.RootClass.validate(RootClass.java:215)
	at org.hibernate.cfg.Configuration.validate(Configuration.java:1149)
	at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1334)
	at org.hibernate.cfg.AnnotationConfiguration.buildSessionFactory(AnnotationConfiguration.java:867)
	at br.com.brabus.epico.infra.CriadorDeSessionFactoryScoped.abre(CriadorDeSessionFactoryScoped.java:23)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
	at java.lang.reflect.Method.invoke(Method.java:597)
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleElement.invoke(InitDestroyAnnotationBeanPostProcessor.java:340)
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor$LifecycleMetadata.invokeInitMethods(InitDestroyAnnotationBeanPostProcessor.java:293)
	at org.springframework.beans.factory.annotation.InitDestroyAnnotationBeanPostProcessor.postProcessBeforeInitialization(InitDestroyAnnotationBeanPostProcessor.java:130)
	... 27 more

...

Não coloquei as classes CentroCustoPK e PlanoContaPK aqui, pra não encher o tópico, elas possuem os mesmos atributos @Id das quais pertencem.

Aparentemente o hibernate não consegue estabelecer relacionamento pois na tabela CENTRO_CUSTO não há uma coluna planoConta, e, não posso mudar nada na base, e mesmo que pudesse não ajudaria.

Could not determine type for: java.util.Collection, at table: CENTRO_CUSTO, for columns: [org.hibernate.mapping.Column(planoConta)]  

Teria uma outra maneira de relacionar estas entidades ?

[]s
Jsign

Não poste títulos de tópicos usando só letras maiúsculas. Não tem pq tentar chamar mais atenção que os demais (sem falar que se todos pegarem essa mania, vai ficar horrível de ler a lista de tópicos).

ViniGodoy, !!! Não foi minha intenção.

Bom, Para quem tiver o mesmo problema, consegui da seguinte forma:

CentroCusto


@Table(name="CENTRO_CUSTO", schema="NBS")
@Entity
@IdClass(CentroCustoPK.class)
public class CentroCusto implements Serializable{

	private static final long serialVersionUID = 1L;

	@Id
	@Column(insertable=false,updatable=false)
	private Long cod_centro_custo;
	
	@Id
	@Column(insertable=false,updatable=false)
	private Long cod_grupo_pc;

        @OneToMany(mappedBy="centroCusto")
	private Collection<PlanoConta> planoConta;
	
	public Collection<PlanoConta> getPlanoConta() {
		return planoConta;
	}
	public void setPlanoConta(Collection<PlanoConta> planoConta) {
		this.planoConta = planoConta;
	}

... ... ... ... 

PlanoConta


@Table(name="PLANO_CONTAS", schema="NBS")
@Entity
@IdClass(PlanoContaPK.class)
public class PlanoConta implements Serializable{

        private static final long serialVersionUID = 1L;

	@Id
	@Column(name="cod_grupo_pc",insertable=false,updatable=false)
	private Long cod_grupo_pc;
	
	@Id
	@Column(name="cod_contabil",insertable=false,updatable=false)
	private String cod_contabil;
	
	@Id
	@Column(name="cod_centro_custo",insertable=false,updatable=false)
	private Long cod_centro_custo;

        private CentroCusto centroCusto;
	
	@ManyToOne
	@JoinColumns({
		@JoinColumn(name="cod_grupo_pc", unique = false, nullable = false,  insertable = false, updatable = false),  
		@JoinColumn(name="cod_centro_custo", unique = false, nullable = false,  insertable = false, updatable = false)
	})
	public CentroCusto getCentroCusto() {
		return centroCusto;
	}
	public void setCentroCusto(CentroCusto centroCusto) {
		this.centroCusto = centroCusto;
	}

... ... ... ...

}

Segui a mesma linha do plentz em http://www.guj.com.br/java/39452-hibernate-mapeamento-de-fk

[]s Jsign

Pessoal,

Criadas as entidades em ambas as bases, como relacionar usando as annotations, @Many@One@…, entidades de bases distintas ?

[]s

Olá pessoal,

Parece que não tem como, como no ex: http://www.devmedia.com.br/forum/viewtopic.asp?id=27253

De qualquer forma gostaria de ter uma certeza maior, alguem sabe me dizer se isto é possível ?