It is odd that you are getting this behavior for SEQUENCE generated values,
but this would be expected for IDENTITY generated values. The issue is that
for IDENTITY the id is assigned by the database on the insert, so it not
available on the persist call. You must first call flush() to ensure that
the id has been assigned.
In general with JPA persist does not ensure the id is assigned, it only must
be assigned on flush, so if you wish to write generic code, you would need
to flush. However if you use TABLE generated values you can be sure that it
will be assigned on persist.
see,
http://en.wikibooks.org/wiki/Java_Persistence/Identity_and_Sequencing#Common_Problems_2
What database are you using? My guess is that you have either set IDENTITY
or are using SEQUENCE on a database that does not support it, so IDENTITY
ends up getting used.
Also in your model I think your OneToOne should probably be using a
@PrimaryKeyJoinColumn not a @JoinColumn.
Leandro J. Komosinski wrote:
>
> Hi,
>
> I think that I found a Toplink bug or I'm missing something about JPA:
>
> Let classes A and B have an one-to-one required association:
>
> @Entity
> public class A {
> @Id
> @GeneratedValue(strategy=SEQUENCE)
> Long id;
>
> @OneToOne(cascade=CascadeType.ALL)
> @JoinColumn (nullable=false)
> B b;
> }
>
> @Entity
> public class B {
> @Id
> Long id;
> }
>
> It's impossible for a B object to have the same id value of A
> object.
>
> The following session bean's method doesn't run:
>
> public void test() {
> A a = new A();
> B b = new B();
>
> // a.id is null ok
>
> em.persist(a);
>
> // a.id still is null Is this correct?
>
> b.setId(a.getId()); // this will set b.id = null;
> }
>
> If I change A's strategy to AUTO the method runs ok. The point is
> precisely this: if i change strategy i must change the logic of my code.
> Is this correct?
>
> Thanks,
>
> Leandro
>
> --
>
> |:| Prof. Leandro J. Komosinski
> |:| Depto de Informática e Estatística
> |:| Centro Tecnológico
> |:| Universidade Federal de Santa Catarina
> |:| -.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.-.
> |:| leandro_at_inf.ufsc.br
> |:| http://www.inf.ufsc.br/~leandro
> |:| fone: (48) 3721 7508
>
>
>
>
>
-----
---
http://wiki.eclipse.org/User:James.sutherland.oracle.com James Sutherland
http://www.eclipse.org/eclipselink/
EclipseLink , http://www.oracle.com/technology/products/ias/toplink/
TopLink
Wiki: http://en.wikibooks.org/wiki/Java_Persistence Java Persistence ,
http://wiki.eclipse.org/EclipseLink EclipseLink ,
http://wiki.oracle.com/page/TopLink TopLink
Forums: http://forums.oracle.com/forums/forum.jspa?forumID=48 TopLink ,
http://www.nabble.com/EclipseLink-f26430.html EclipseLink
--
View this message in context: http://www.nabble.com/diferences-between-GeneratedType.AUTO-and-GeneratedType.SEQUENCE-tp15510717p15560822.html
Sent from the java.net - glassfish persistence mailing list archive at Nabble.com.