You are viewing a plain text version of this content. The canonical link for it is here.
Posted to users@openjpa.apache.org by Gilberto C Andrade <gi...@secad.to.gov.br> on 2008/01/02 18:33:53 UTC

NPE on ManyToOne while using insertable = false, updatable = false

Hi,

openjpa 1.0.1, jdk 1.5
Produto:
> @Entity
> @Table(name = "produto")
> public class Produto implements Serializable {
>     @Id
>     @GeneratedValue(strategy=GenerationType.TABLE, generator="ProdutoGerador")
>     @TableGenerator(name="ProdutoGerador", table="ID_GERADOR", pkColumnName="PK",
>         valueColumnName="AID", pkColumnValue="produto_id_gerador", allocationSize=1, initialValue=1)
>     @Column(name="cd_produto", columnDefinition="INTEGER")
>     private Integer cdProduto;

Item:
> @Entity
> @Table(name = "item")
> public class Item implements Serializable {
>     @Transient
>     protected final Log log = LogFactory.getLog(getClass());
>     @Id
>     @GeneratedValue(strategy=GenerationType.TABLE, generator="ItemGerador")
>     @TableGenerator(name="ItemGerador", table="ID_GERADOR", pkColumnName="PK",
>         valueColumnName="AID", pkColumnValue="item_id_gerador", allocationSize=1, initialValue=1)
>     @Column(name="cd_item", columnDefinition="INTEGER")
>     private Integer cdItem;
.
.
.
>     
>     @Column(name = "cd_produto")    
>     private Integer cdProduto;
>     
>     @ManyToOne
>     @JoinColumn(name = "cd_produto", referencedColumnName="cd_produto", insertable = false, updatable = false)    
>     private Produto produto;//read only

OBS.: Originally this was mapped the following way, using hibernate's tag:
>       <many-to-one
>             name="produto"
>             class="org.appfuse.model.estoque.Produto"
>             cascade="none"
>             outer-join="true"
>             update="false"
>             insert="false"
>             access="property"
>             column="cd_produto"
>         />



Test:
>     @Test
>     public void persistRemoveItemTest() {
>         log.debug("\npersistRemoveItemTest - Criação de uma instância da classe Item\n");
>         String nomeItem = "Calça";
>         Integer cdItem = null;
>         BigDecimal precoVenda = new BigDecimal(0.0F);
>         BigDecimal precoCusto = new BigDecimal(0.0F);
>         UnidadeMedida uM = em.find(UnidadeMedida.class, "MT");
>         Float estoqueAtual = 0.0F;
>         Float estoqueMinimo = 0.0F;
>         Float nivelDeReposicao = 0.0F;
>         Boolean flDescontinuado = false;
>         Produto p = em.find(Produto.class, 1);
>        
>         Item i = new Item(nomeItem,precoVenda, precoCusto, uM.getCdUnidadeMedida(), estoqueAtual, estoqueMinimo, nivelDeReposicao, flDescontinuado, p.getCdProduto());
>         assertNull("cdItem antes do método persist:",i.getCdItem());
>         em.getTransaction().begin();
>         em.persist(i);
>         em.getTransaction().commit();
>         log.debug("Objeto pós gravação: \n"+i);
>         cdItem = i.getCdItem();
>         i = null;
>        
>         assertNotNull("cdItem pós persist:",cdItem);
>         
>         Item i2 = em.find(Item.class, cdItem);
>         log.debug("Objeto carregado: \n"+i2);
>         assertNotNull("Não pode ser nulo:",i2.getProduto());<==================== Here is the problem!
>     }

As you can see I'm testing the lazy load of the Produto class. But i2
instance comes with null produto.

Is there anything wrong with my mapping?

Thanks,

Gilberto

Re: NPE on ManyToOne while using insertable = false, updatable = false

Posted by Gilberto C Andrade <gi...@secad.to.gov.br>.
> Hi Gilberto,
> 
> I think you might have encountered an issue with caching.
> 
> When you persist the Item entity, the reference to Produto is null (I
> didn't see anywhere that you set it). So when you retrieve it, openjpa
> doesn't go to the database but simply returns what is in the (second
> level) cache. In the cache, the object that was stored is retrieved.
> 
Can I disable that behavior(second level cache) on some operations?

> JPA spec (at the JPA 1.0 level) that the application manage both sides
> of relationships. In the code below, can you add a statement that sets
> the Produto field in Item before commit?
Yes! Now it works.
Thanks,

Gilberto
www.secad.to.gov.br


Re: NPE on ManyToOne while using insertable = false, updatable = false

Posted by Craig L Russell <Cr...@Sun.COM>.
Hi Gilberto,

I think you might have encountered an issue with caching.

When you persist the Item entity, the reference to Produto is null (I  
didn't see anywhere that you set it). So when you retrieve it,  
openjpa doesn't go to the database but simply returns what is in the  
(second level) cache. In the cache, the object that was stored is  
retrieved.

JPA spec (at the JPA 1.0 level) that the application manage both  
sides of relationships. In the code below, can you add a statement  
that sets the Produto field in Item before commit?

On Jan 2, 2008, at 9:33 AM, Gilberto C Andrade wrote:

> Hi,
>
> openjpa 1.0.1, jdk 1.5
> Produto:
>> @Entity
>> @Table(name = "produto")
>> public class Produto implements Serializable {
>>     @Id
>>     @GeneratedValue(strategy=GenerationType.TABLE,  
>> generator="ProdutoGerador")
>>     @TableGenerator(name="ProdutoGerador", table="ID_GERADOR",  
>> pkColumnName="PK",
>>         valueColumnName="AID", pkColumnValue="produto_id_gerador",  
>> allocationSize=1, initialValue=1)
>>     @Column(name="cd_produto", columnDefinition="INTEGER")
>>     private Integer cdProduto;
>
> Item:
>> @Entity
>> @Table(name = "item")
>> public class Item implements Serializable {
>>     @Transient
>>     protected final Log log = LogFactory.getLog(getClass());
>>     @Id
>>     @GeneratedValue(strategy=GenerationType.TABLE,  
>> generator="ItemGerador")
>>     @TableGenerator(name="ItemGerador", table="ID_GERADOR",  
>> pkColumnName="PK",
>>         valueColumnName="AID", pkColumnValue="item_id_gerador",  
>> allocationSize=1, initialValue=1)
>>     @Column(name="cd_item", columnDefinition="INTEGER")
>>     private Integer cdItem;
> .
> .
> .
>>
>>     @Column(name = "cd_produto")
>>     private Integer cdProduto;
>>
>>     @ManyToOne
>>     @JoinColumn(name = "cd_produto",  
>> referencedColumnName="cd_produto", insertable = false, updatable =  
>> false)
>>     private Produto produto;//read only
>
> OBS.: Originally this was mapped the following way, using  
> hibernate's tag:
>>       <many-to-one
>>             name="produto"
>>             class="org.appfuse.model.estoque.Produto"
>>             cascade="none"
>>             outer-join="true"
>>             update="false"
>>             insert="false"
>>             access="property"
>>             column="cd_produto"
>>         />
>
>
>
> Test:
>>     @Test
>>     public void persistRemoveItemTest() {
>>         log.debug("\npersistRemoveItemTest - Criação de uma  
>> instância da classe Item\n");
>>         String nomeItem = "Calça";
>>         Integer cdItem = null;
>>         BigDecimal precoVenda = new BigDecimal(0.0F);
>>         BigDecimal precoCusto = new BigDecimal(0.0F);
>>         UnidadeMedida uM = em.find(UnidadeMedida.class, "MT");
>>         Float estoqueAtual = 0.0F;
>>         Float estoqueMinimo = 0.0F;
>>         Float nivelDeReposicao = 0.0F;
>>         Boolean flDescontinuado = false;
>>         Produto p = em.find(Produto.class, 1);
>>
>>         Item i = new Item(nomeItem,precoVenda, precoCusto,  
>> uM.getCdUnidadeMedida(), estoqueAtual, estoqueMinimo,  
>> nivelDeReposicao, flDescontinuado, p.getCdProduto());

i.setProduto(p); // <== here's the solution

Craig

>>         assertNull("cdItem antes do método persist:",i.getCdItem());
>>         em.getTransaction().begin();
>>         em.persist(i);
>>         em.getTransaction().commit();
>>         log.debug("Objeto pós gravação: \n"+i);
>>         cdItem = i.getCdItem();
>>         i = null;
>>
>>         assertNotNull("cdItem pós persist:",cdItem);
>>
>>         Item i2 = em.find(Item.class, cdItem);
>>         log.debug("Objeto carregado: \n"+i2);
>>         assertNotNull("Não pode ser nulo:",i2.getProduto 
>> ());<==================== Here is the problem!
>>     }
>
> As you can see I'm testing the lazy load of the Produto class. But i2
> instance comes with null produto.
>
> Is there anything wrong with my mapping?
>
> Thanks,
>
> Gilberto

Craig Russell
Architect, Sun Java Enterprise System http://java.sun.com/products/jdo
408 276-5638 mailto:Craig.Russell@sun.com
P.S. A good JDO? O, Gasp!


Re: NPE on ManyToOne while using insertable = false, updatable = false

Posted by Pinaki Poddar <pp...@apache.org>.
Hello Gilberto,
  I agree that there can be valid reasons to model it the way you have
mentioned. But having two fields in Item that (implicitly) mean the same
thing (i.e. a reference to Prudto instance and an Integer field value which
is Prudto's primary key) is generally a risky choice. The application has to
maintain the integrity by always ensuring that they mean the same thing. For
example, coding error can assign values for the two fields in the same Item
instance that is not the primary key value and that can lead to
inconsistencies that can be hard to track. 
    
  I can also see why you are expecting the reference being non-null when you
have set the Integer field -- because from the mapping annotation one may
infer (though not always correctly -- because imagine a case where the
intention of the design is Item to have a Pruoto and a cdPrudto that are not
related).

  The bottomline seems to be someone somewhere has to tell the provider that
cdPrudto is the same as the primary key of prudto in an Item instance.
Otherwise, it is not obvious what logic will determine that they mean the
same thing.

  
-- 
View this message in context: http://www.nabble.com/NPE-on-ManyToOne-while-using-insertable-%3D-false%2C-updatable-%3D-false-tp14582403p14592052.html
Sent from the OpenJPA Users mailing list archive at Nabble.com.


Re: NPE on ManyToOne while using insertable = false, updatable = false

Posted by Gilberto Caeatano de Andrade <gi...@gmail.com>.
Pinaki, first thanks for you attention!

Second, we are converting an old hibernate project and that one used 
this design.
> OpenJPA (or for that matter anyone other than the designer) has no way to
> know that  
> private Integer cdProduto;
> refers to the primary key of the field
> private Produto produto;//read only
>   
So, what does these tags:

    @ManyToOne
    @JoinColumn(name = "cd_produto", referencedColumnName="cd_produto", insertable = false, updatable = false) 

means?

In that case it will save just the Item table, but not the nested 
Produto table.
> You have tell that to OpenJPA.
>
> So what you can do (if the design insist on a arguably erroneous domain
> model for all the wrong reasons)
I don't think it is "erroneous domain model"! In IT we may find several 
use cases and different situations. And this project isn't different.

>  to maintain referential integrity is:
>
> public Item(....,Produto p) {
>   this.cdProduto = p.getCdProduto();
>   this.produto = p;
> }
>
>   
I thought I could make the app work with some adjusts using openjpa!
Gilberto


Re: NPE on ManyToOne while using insertable = false, updatable = false

Posted by Pinaki Poddar <pp...@apache.org>.
OpenJPA (or for that matter anyone other than the designer) has no way to
know that  
private Integer cdProduto;
refers to the primary key of the field
private Produto produto;//read only

You have tell that to OpenJPA.

So what you can do (if the design insist on a arguably erroneous domain
model for all the wrong reasons) to maintain referential integrity is:

public Item(....,Produto p) {
  this.cdProduto = p.getCdProduto();
  this.produto = p;
}

-- 
View this message in context: http://www.nabble.com/NPE-on-ManyToOne-while-using-insertable-%3D-false%2C-updatable-%3D-false-tp14582403p14586279.html
Sent from the OpenJPA Users mailing list archive at Nabble.com.


Re: NPE on ManyToOne while using insertable = false, updatable = false

Posted by Gilberto C Andrade <gi...@secad.to.gov.br>.
Pinaki Poddar wrote:
> Item refers to Product via field 'produto' then why do you need a separate
> Integer field 'cdProduto'?

Sorry, I should have mentioned that the produto field is used only as
lookup! So, the idea is that on crud operations, we only use primitive
types.

> The item constructor is taking p.getCdProduto() as last argument, so I am
> assuming that the constructor is setting
> item.cdProduto field but not item.produto. 

Correct, it is a decision's design!

> 
> And nobody else is either so item.getProduto() is returning null.
No! As you could see in the Item i2 = em.find(Item.class, cdItem);
statement, shouldn't openjpa returns the item.produto object populate
through a new query (or eager) on db, when I try to access it?


> 
> What you can do is:
> a) remove cdProduto field from Item
> b) pass Produto to Item constructor
> c) In Item constructor set this.producto = produto;
>  
>>     @Column(name = "cd_produto")    
>>     private Integer cdProduto;
>>     
>>     @ManyToOne
>>     @JoinColumn(name = "cd_produto", referencedColumnName="cd_produto",
>> insertable = false, updatable = false)    
>>     private Produto produto;//read only
> 
> 
> 
> Gilberto C Andrade wrote:
>> Hi,
>>
>> openjpa 1.0.1, jdk 1.5
>> Produto:
>>> @Entity
>>> @Table(name = "produto")
>>> public class Produto implements Serializable {
>>>     @Id
>>>     @GeneratedValue(strategy=GenerationType.TABLE,
>>> generator="ProdutoGerador")
>>>     @TableGenerator(name="ProdutoGerador", table="ID_GERADOR",
>>> pkColumnName="PK",
>>>         valueColumnName="AID", pkColumnValue="produto_id_gerador",
>>> allocationSize=1, initialValue=1)
>>>     @Column(name="cd_produto", columnDefinition="INTEGER")
>>>     private Integer cdProduto;
>> Item:
>>> @Entity
>>> @Table(name = "item")
>>> public class Item implements Serializable {
>>>     @Transient
>>>     protected final Log log = LogFactory.getLog(getClass());
>>>     @Id
>>>     @GeneratedValue(strategy=GenerationType.TABLE,
>>> generator="ItemGerador")
>>>     @TableGenerator(name="ItemGerador", table="ID_GERADOR",
>>> pkColumnName="PK",
>>>         valueColumnName="AID", pkColumnValue="item_id_gerador",
>>> allocationSize=1, initialValue=1)
>>>     @Column(name="cd_item", columnDefinition="INTEGER")
>>>     private Integer cdItem;
>> .
>> .
>> .
>>>     
>>>     @Column(name = "cd_produto")    
>>>     private Integer cdProduto;
>>>     
>>>     @ManyToOne
>>>     @JoinColumn(name = "cd_produto", referencedColumnName="cd_produto",
>>> insertable = false, updatable = false)    
>>>     private Produto produto;//read only
>> OBS.: Originally this was mapped the following way, using hibernate's tag:
>>>       <many-to-one
>>>             name="produto"
>>>             class="org.appfuse.model.estoque.Produto"
>>>             cascade="none"
>>>             outer-join="true"
>>>             update="false"
>>>             insert="false"
>>>             access="property"
>>>             column="cd_produto"
>>>         />
>>
>>
>> Test:
>>>     @Test
>>>     public void persistRemoveItemTest() {
>>>         log.debug("\npersistRemoveItemTest - Criação de uma instância da
>>> classe Item\n");
>>>         String nomeItem = "Calça";
>>>         Integer cdItem = null;
>>>         BigDecimal precoVenda = new BigDecimal(0.0F);
>>>         BigDecimal precoCusto = new BigDecimal(0.0F);
>>>         UnidadeMedida uM = em.find(UnidadeMedida.class, "MT");
>>>         Float estoqueAtual = 0.0F;
>>>         Float estoqueMinimo = 0.0F;
>>>         Float nivelDeReposicao = 0.0F;
>>>         Boolean flDescontinuado = false;
>>>         Produto p = em.find(Produto.class, 1);
>>>        
>>>         Item i = new Item(nomeItem,precoVenda, precoCusto,
>>> uM.getCdUnidadeMedida(), estoqueAtual, estoqueMinimo, nivelDeReposicao,
>>> flDescontinuado, p.getCdProduto());
>>>         assertNull("cdItem antes do método persist:",i.getCdItem());
>>>         em.getTransaction().begin();
>>>         em.persist(i);
>>>         em.getTransaction().commit();
>>>         log.debug("Objeto pós gravação: \n"+i);
>>>         cdItem = i.getCdItem();
>>>         i = null;
>>>        
>>>         assertNotNull("cdItem pós persist:",cdItem);
>>>         
>>>         Item i2 = em.find(Item.class, cdItem);
>>>         log.debug("Objeto carregado: \n"+i2);
>>>         assertNotNull("Não pode ser
>>> nulo:",i2.getProduto());<==================== Here is the problem!
>>>     }
>> As you can see I'm testing the lazy load of the Produto class. But i2
>> instance comes with null produto.
>>
>> Is there anything wrong with my mapping?
>>
>> Thanks,
>>
>> Gilberto
>>
>>
> 


Re: NPE on ManyToOne while using insertable = false, updatable = false

Posted by Pinaki Poddar <pp...@apache.org>.
Item refers to Product via field 'produto' then why do you need a separate
Integer field 'cdProduto'?
The item constructor is taking p.getCdProduto() as last argument, so I am
assuming that the constructor is setting
item.cdProduto field but not item.produto. 

And nobody else is either so item.getProduto() is returning null.

What you can do is:
a) remove cdProduto field from Item
b) pass Produto to Item constructor
c) In Item constructor set this.producto = produto;
 
>     @Column(name = "cd_produto")    
>     private Integer cdProduto;
>     
>     @ManyToOne
>     @JoinColumn(name = "cd_produto", referencedColumnName="cd_produto",
> insertable = false, updatable = false)    
>     private Produto produto;//read only



Gilberto C Andrade wrote:
> 
> Hi,
> 
> openjpa 1.0.1, jdk 1.5
> Produto:
>> @Entity
>> @Table(name = "produto")
>> public class Produto implements Serializable {
>>     @Id
>>     @GeneratedValue(strategy=GenerationType.TABLE,
>> generator="ProdutoGerador")
>>     @TableGenerator(name="ProdutoGerador", table="ID_GERADOR",
>> pkColumnName="PK",
>>         valueColumnName="AID", pkColumnValue="produto_id_gerador",
>> allocationSize=1, initialValue=1)
>>     @Column(name="cd_produto", columnDefinition="INTEGER")
>>     private Integer cdProduto;
> 
> Item:
>> @Entity
>> @Table(name = "item")
>> public class Item implements Serializable {
>>     @Transient
>>     protected final Log log = LogFactory.getLog(getClass());
>>     @Id
>>     @GeneratedValue(strategy=GenerationType.TABLE,
>> generator="ItemGerador")
>>     @TableGenerator(name="ItemGerador", table="ID_GERADOR",
>> pkColumnName="PK",
>>         valueColumnName="AID", pkColumnValue="item_id_gerador",
>> allocationSize=1, initialValue=1)
>>     @Column(name="cd_item", columnDefinition="INTEGER")
>>     private Integer cdItem;
> .
> .
> .
>>     
>>     @Column(name = "cd_produto")    
>>     private Integer cdProduto;
>>     
>>     @ManyToOne
>>     @JoinColumn(name = "cd_produto", referencedColumnName="cd_produto",
>> insertable = false, updatable = false)    
>>     private Produto produto;//read only
> 
> OBS.: Originally this was mapped the following way, using hibernate's tag:
>>       <many-to-one
>>             name="produto"
>>             class="org.appfuse.model.estoque.Produto"
>>             cascade="none"
>>             outer-join="true"
>>             update="false"
>>             insert="false"
>>             access="property"
>>             column="cd_produto"
>>         />
> 
> 
> 
> Test:
>>     @Test
>>     public void persistRemoveItemTest() {
>>         log.debug("\npersistRemoveItemTest - Criação de uma instância da
>> classe Item\n");
>>         String nomeItem = "Calça";
>>         Integer cdItem = null;
>>         BigDecimal precoVenda = new BigDecimal(0.0F);
>>         BigDecimal precoCusto = new BigDecimal(0.0F);
>>         UnidadeMedida uM = em.find(UnidadeMedida.class, "MT");
>>         Float estoqueAtual = 0.0F;
>>         Float estoqueMinimo = 0.0F;
>>         Float nivelDeReposicao = 0.0F;
>>         Boolean flDescontinuado = false;
>>         Produto p = em.find(Produto.class, 1);
>>        
>>         Item i = new Item(nomeItem,precoVenda, precoCusto,
>> uM.getCdUnidadeMedida(), estoqueAtual, estoqueMinimo, nivelDeReposicao,
>> flDescontinuado, p.getCdProduto());
>>         assertNull("cdItem antes do método persist:",i.getCdItem());
>>         em.getTransaction().begin();
>>         em.persist(i);
>>         em.getTransaction().commit();
>>         log.debug("Objeto pós gravação: \n"+i);
>>         cdItem = i.getCdItem();
>>         i = null;
>>        
>>         assertNotNull("cdItem pós persist:",cdItem);
>>         
>>         Item i2 = em.find(Item.class, cdItem);
>>         log.debug("Objeto carregado: \n"+i2);
>>         assertNotNull("Não pode ser
>> nulo:",i2.getProduto());<==================== Here is the problem!
>>     }
> 
> As you can see I'm testing the lazy load of the Produto class. But i2
> instance comes with null produto.
> 
> Is there anything wrong with my mapping?
> 
> Thanks,
> 
> Gilberto
> 
> 

-- 
View this message in context: http://www.nabble.com/NPE-on-ManyToOne-while-using-insertable-%3D-false%2C-updatable-%3D-false-tp14582403p14585575.html
Sent from the OpenJPA Users mailing list archive at Nabble.com.