Where por @Id usando InheritanceType.JOINED

Olá pessoal.

Estou tentando fazer o seguinte:


@Entity(name = "obj_item_stat")
@Table(schema = Config.SCHEMA_JC3)
@Inheritance(strategy = InheritanceType.JOINED)
@DiscriminatorColumn(name = "cat_code", discriminatorType = DiscriminatorType.STRING, length = 6)
@IdClass(AbstractObjectItemStatusId.class)
public abstract class AbstractObjectItemStatus extends AbstractObjectItemAssociationReported<AbstractObjectItemStatusId> implements Serializable {

	private static final long serialVersionUID = 1L;
	
	@Id
	@ManyToOne
	@JoinColumn(name = "obj_item_id")
	@JsonSerialize(using = JsonRelationSerializer.class)
	@JsonDeserialize(using = JsonObjectItemRelationResolver.class)
	private ObjectItem objItem;

	@Id
	@NotNull
	@Digits(integer = 20, fraction = 0)
	@Column(name = "obj_item_stat_ix")
	@JsonSerialize(using = ToStringSerializer.class)
	private BigInteger ix;

        ...
}

@Entity(name = "pers_stat")
@Table(schema = Config.SCHEMA_JC3)
@DiscriminatorValue("PE")
@PrimaryKeyJoinColumns({ @PrimaryKeyJoinColumn(name = "pers_stat_id", referencedColumnName = "obj_item_id"),
		@PrimaryKeyJoinColumn(name = "obj_item_stat_ix", referencedColumnName = "obj_item_stat_ix") })
public class PersonStatus extends AbstractObjectItemStatus implements Serializable
{
       ...
}

Porém quando eu executo um jpql mais ou menos assim:

SELECT o FROM PersonStatus o WHERE o.objItem = :objIt

Me retorna o seguinte erro:

Caused by: org.postgresql.util.PSQLException: ERROR: column personstat0_.obj_item_id does not exist
  Posição: 290
	at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2102) ~[postgresql-9.0-801.jdbc4.jar:na]
	at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1835) ~[postgresql-9.0-801.jdbc4.jar:na]
	at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:257) ~[postgresql-9.0-801.jdbc4.jar:na]
	at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:500) ~[postgresql-9.0-801.jdbc4.jar:na]
	at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:388) ~[postgresql-9.0-801.jdbc4.jar:na]
	at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:273) ~[postgresql-9.0-801.jdbc4.jar:na]
	at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:76) ~[c3p0-0.9.1.jar:0.9.1]
	at org.hibernate.jdbc.AbstractBatcher.getResultSet(AbstractBatcher.java:208) ~[hibernate3.jar:3.6.10.Final]
	at org.hibernate.loader.Loader.getResultSet(Loader.java:1953) ~[hibernate3.jar:3.6.10.Final]
	at org.hibernate.loader.Loader.doQuery(Loader.java:802) ~[hibernate3.jar:3.6.10.Final]
	at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:274) ~[hibernate3.jar:3.6.10.Final]
	at org.hibernate.loader.Loader.doList(Loader.java:2542) ~[hibernate3.jar:3.6.10.Final]
	... 42 common frames omitted

O sql gerado é:

    select
        count((personstat0_.obj_item_stat_ix,
        personstat0_.pers_stat_id)) as col_0_0_ 
    from
        jc3.pers_stat personstat0_ 
    inner join
        jc3.obj_item_stat personstat0_1_ 
            on personstat0_.obj_item_stat_ix=personstat0_1_.obj_item_stat_ix 
            and personstat0_.pers_stat_id=personstat0_1_.obj_item_id 
    where
        personstat0_.obj_item_id=? limit ?

O Hibernate esta tentando usar o campo obj_item_id na tabela pers_stat o que esta errado. Mas eu ja disse pra ele neste trecho de código ja mencionado acima que é para ele alterar o nome da coluna.

@PrimaryKeyJoinColumns({ @PrimaryKeyJoinColumn(name = "pers_stat_id", referencedColumnName = "obj_item_id"),
		@PrimaryKeyJoinColumn(name = "obj_item_stat_ix", referencedColumnName = "obj_item_stat_ix") })
public class PersonStatus extends AbstractObjectItemStatus implements Serializable

Por que isso não funciona?

Este hibernate esta me dando uma dor de cabeça!

Poste as tabelas e as colunas das mesmas.

CREATE TABLE jc3.obj_item_stat
(
  obj_item_id numeric(20,0) NOT NULL, -- The unique value, or set of characters, assigned to represent a specific OBJECT-ITEM and to distinguish it from all other OBJECT-ITEMs.
  obj_item_stat_ix numeric(20,0) NOT NULL, -- The unique value, or set of characters, assigned to represent a specific OBJECT-ITEM-STATUS for a specific OBJECT-ITEM and to distinguish it from all other OBJECT-ITEM-STATUSs for that OBJECT-ITEM.
  cat_code character varying(6) NOT NULL, -- The specific value that represents the class of OBJECT-ITEM-STATUS. It serves as a discriminator that partitions OBJECT-ITEM-STATUS into subtypes.
  rptd_id numeric(20,0) NOT NULL, -- The unique value, or set of characters, assigned to represent a specific REPORTING-DATA and to distinguish it from all other REPORTING-DATAs.
  booby_trap_prsnc_code character varying(6), -- The specific value that indicates whether a specific OBJECT-ITEM has been booby-trapped.
  emsn_ctrl_code character varying(6), -- The specific value that represents the emission control status of a specific OBJECT-ITEM.
  creator_id numeric(20,0) NOT NULL, -- A value assigned to the row to identify the organisation which created that row. This is referenced by an application level business rule to an OBJ_ITEM entry with a cat_code = OR and to a corresponding ORG subtype entry.
  update_seqnr numeric(15,0) NOT NULL, -- An absolute sequence numeric, assigned to represent the validity (in terms of seniority) of a certain data item.
  CONSTRAINT xpkobj_item_stat PRIMARY KEY (obj_item_id , obj_item_stat_ix ),
  CONSTRAINT has4 FOREIGN KEY (obj_item_id)
      REFERENCES jc3.obj_item (obj_item_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT provides_applic_info25 FOREIGN KEY (rptd_id)
      REFERENCES jc3.rptd (rptd_id) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE NO ACTION,
  CONSTRAINT ds146_obj_item_stat_cat_code2 CHECK (cat_code::text = ANY (ARRAY['CF'::character varying, 'FA'::character varying, 'GF'::character varying, 'MA'::character varying, 'NKN'::character varying, 'OR'::character varying, 'PE'::character varying]::text[])),
  CONSTRAINT ds385_obj_item_stat_booby_tra2 CHECK (booby_trap_prsnc_code::text = ANY (ARRAY['NO'::character varying, 'UNK'::character varying, 'YES'::character varying]::text[])),
  CONSTRAINT ds4158_oi_stat_emsn_ctrl_code2 CHECK (emsn_ctrl_code::text = ANY (ARRAY['EMCON1'::character varying, 'EMCON2'::character varying, 'EMCON3'::character varying]::text[]))
)

CREATE TABLE jc3.pers_stat
(
  pers_stat_id numeric(20,0) NOT NULL, -- The person-id of the PERSON that is the subject of a specific PERSON-STATUS (a role name for object-item-id).
  obj_item_stat_ix numeric(20,0) NOT NULL, -- The unique value, or set of characters, assigned to represent a specific OBJECT-ITEM-STATUS for a specific OBJECT-ITEM and to distinguish it from all other OBJECT-ITEM-STATUSs for that OBJECT-ITEM.
  duty_stat_code character varying(6), -- The specific value that represents the availability of a specific PERSON for duty at a military or civilian post of employment.
  physcl_stat_code character varying(6), -- The specific value that represents the general physical status of a specific PERSON.
  physcl_stat_qual_code character varying(6), -- The specific value that qualifies the health conditions of a specific PERSON at a specific point in time.
  rad_dose_qty numeric(6,0), -- The numeric value that represents the total radiation dose to which a person has been exposed. The unit of measure is centiGray (cGy).
  reserve_ind_code character varying(6), -- The specific value that represents whether a specific PERSON has been placed in reserve.
  creator_id numeric(20,0) NOT NULL, -- A value assigned to the row to identify the organisation which created that row. This is referenced by an application level business rule to an OBJ_ITEM entry with a cat_code = OR and to a corresponding ORG subtype entry.
  update_seqnr numeric(15,0) NOT NULL, -- An absolute sequence numeric, assigned to represent the validity (in terms of seniority) of a certain data item.
  CONSTRAINT xpkpers_stat PRIMARY KEY (pers_stat_id , obj_item_stat_ix ),
  CONSTRAINT is_an_obj_item_stat3 FOREIGN KEY (pers_stat_id, obj_item_stat_ix)
      REFERENCES jc3.obj_item_stat (obj_item_id, obj_item_stat_ix) MATCH SIMPLE
      ON UPDATE NO ACTION ON DELETE CASCADE,
  CONSTRAINT ds102_pers_stat_duty_stat_cod2 CHECK (duty_stat_code::text = ANY (ARRAY['ABS'::character varying, 'ADU'::character varying, 'AKIA'::character varying, 'ARR'::character varying, 'DEC'::character varying, 'DESRTD'::character varying, 'HSP'::character varying, 'HST'::character varying, 'MIS'::character varying, 'NKN'::character varying, 'OLV'::character varying, 'POW'::character varying]::text[])),
  CONSTRAINT ds106_pers_stat_physical_stat2 CHECK (physcl_stat_code::text = ANY (ARRAY['FT'::character varying, 'IN'::character varying, 'IW'::character varying, 'NKN'::character varying, 'SI'::character varying]::text[])),
  CONSTRAINT ds266_pers_stat_res_ind_code2 CHECK (reserve_ind_code::text = ANY (ARRAY['NO'::character varying, 'YES'::character varying]::text[])),
  CONSTRAINT ds379_pers_stat_phy_stat_qual2 CHECK (physcl_stat_qual_code::text = ANY (ARRAY['ILLCNT'::character varying, 'ILLNCN'::character varying, 'ILLUNK'::character varying, 'INJRD'::character varying, 'NKN'::character varying, 'PRGNT'::character varying, 'WNDD'::character varying]::text[]))
)

Camarada, era só fazer

Tabela1
Id - PK
Coluna1
Coluna2

Esse monte de código fica quase indecifrável.
Mesmo assim, perceba que na tabela jc3.pers_stat não existe uma coluna com o nome obj_item_id e é esse o motivo do erro.
Isso me leva a crer que esse amontoado de anotações que você colocou aí é que estção te trazendo problemas e não o Hibernate em si. Ele está apenas obedecendo o que você o instruiu. Lembre-se computadores são burros, você é dotado de um polegar opositor e um encéfalo desenvolvido.
Ou seja, precisa corrigir o mapeamento, senão não vai funcionar.

[quote=drsmachado]Camarada, era só fazer

Tabela1
Id - PK
Coluna1
Coluna2

Esse monte de código fica quase indecifrável.
Mesmo assim, perceba que na tabela jc3.pers_stat não existe uma coluna com o nome obj_item_id e é esse o motivo do erro.
Isso me leva a crer que esse amontoado de anotações que você colocou aí é que estção te trazendo problemas e não o Hibernate em si. Ele está apenas obedecendo o que você o instruiu. Lembre-se computadores são burros, você é dotado de um polegar opositor e um encéfalo desenvolvido.
Ou seja, precisa corrigir o mapeamento, senão não vai funcionar.[/quote]

Com toda sua esperteza me diz como eu corrijo o mapeamento?

[]s

Para isso existe a documentação do Hibernate, não?
Enfim, o caminho eu já apontei, basta que você meta a mão na massa e faça. Se ocorrerem erros, precisa ler os erros e o contexto no qual eles ocorrem. Caso, mesmo assim, haja dúvidas, volte e pergunte.

[quote=drsmachado]Para isso existe a documentação do Hibernate, não?
Enfim, o caminho eu já apontei, basta que você meta a mão na massa e faça. Se ocorrerem erros, precisa ler os erros e o contexto no qual eles ocorrem. Caso, mesmo assim, haja dúvidas, volte e pergunte.[/quote]

Dizer que o mapeamento esta errado é fácil, qualquer um sabe, quero ver dizer onde estar errado.

Infelizmente você tão pouco de hibernate e jpa quanto eu… e também não sabe onde esta o erro!

[quote=brunohansen][quote=drsmachado]Para isso existe a documentação do Hibernate, não?
Enfim, o caminho eu já apontei, basta que você meta a mão na massa e faça. Se ocorrerem erros, precisa ler os erros e o contexto no qual eles ocorrem. Caso, mesmo assim, haja dúvidas, volte e pergunte.[/quote]

Dizer que o mapeamento esta errado é fácil, qualquer um sabe, quero ver dizer onde estar errado.

Infelizmente você tão pouco de hibernate e jpa quanto eu… e também não sabe onde esta o erro![/quote]
Psicologia infantil comigo não funciona.
Não tenho nada a provar para ti, você não é meu chefe e não está me pagando por isto.
Se quiser que eu resolva o problema (entenda faça isto para você) pague o valor que eu cobro por minha hora de desenvolvimento, aí então, terá o direito de cobrar.

E não, não sei mesmo nada de hibernate/JPA, eu prefiro EclipseLink. E eu sei, ao menos, ler e interpretar as mensagens de exception, já você…

Aliás, se estivesse mais preocupado em resolver o problema e com menos preguiça de pensar e tentar, teria entendido que o fato da coluna referenciada no erro (obj_item_id) não fazer parte da tabela jc3.pers_stat e, mesmo assim, o hibernate a estar procurando ali, é o ponto que deve ser explorado para que consiga corrigir o problema.

Uma dica de grátis, para um preguiçoso: Onde você define tabela e coluna, no mapeamento???
Se acertar, ganha como presente a resolução do problema.