You are viewing a plain text version of this content. The canonical link for it is here.
Posted to users@openjpa.apache.org by Frank Schwarz <fs...@gmx.net> on 2008/08/07 14:18:14 UTC

bidirectional one-to-many relationship with join-table

Is it possible to define a bidirectional one-to-many relationship using 
a join-table?

I know that JPA1 says quite clear for one-to-many relationships: if 
bidirectional than join-column, and if unidirectional than join-table.

Does OpenJPA support bidirectionality with a join-table (as it supports 
unidirectionality with a join-column)?

Kind regards,
Frank

RE: bidirectional one-to-many relationship with join-table

Posted by Pinaki Poddar <pp...@apache.org>.
> Does OpenJPA assume that DB collation is always case insensitive? 

Many properties of database can be configured using following syntax.  
  <property name="openjpa.jdbc.DBDictionary"
value="sqlserver(schemaCase=preserve)"/> 

Each known database has a corresponding mnemonics such as 'sqlserver' --
which is realized by ....openjpa.jdbc.SQLServerDictionary. The properties of
these class (such as schemaCase) can be further configured.

If you want to dig further, take a look at a class
PersistenceMappingDefaults or its superclasses. They control how database
schema elements (such as foreign key or a join table) are named. One can
selectively change/tune those policies by overriding selective methods of
these classes as a last resort

There had been many important changes in OpenJPA 2.0 in the way names to
database schema elements are assigned. I hope the ones who have expert
understanding of this new development will be able to help out further. 
 


-----
Pinaki 
-- 
View this message in context: http://openjpa.208410.n2.nabble.com/bidirectional-one-to-many-relationship-with-join-table-tp678479p5154163.html
Sent from the OpenJPA Users mailing list archive at Nabble.com.

RE: bidirectional one-to-many relationship with join-table

Posted by Howard Mak <hm...@antennasoftware.com>.
1.	Auto-create of tables is disabled.  I have <property
name="openjpa.jdbc.SynchronizeMappings" value="validate"/>

2.	Yes, there is an existing schema.  Following was manually
created on my SQLServer:

	CREATE TABLE person_addresses (
		person_ssn BIGINT references person,
		phone      VARCHAR(255) references address);

3.	The problem w/ suggested edit is that I cannot change the table
columns [to follow JPA conventions].  Instead, I need to make JPA fit
the existing schema. :(

4.	Is applying @SecondaryTable(name="person_addresses") on Address
entity a suitable workaround (... seems to avoid the exception I've been
getting)?  Any problems other than the performance hit [incurred by
extra join] when selecting Address?


SIDENOTE:

5.	I've also noticed that on case sensitive SQLServer collations
(e.g., "Latin1_General_BIN"), I get the following exception on
EntityManagerFactory.createEntityManager():

		Exception in thread "main"
<openjpa-2.0.0-beta-r422266:903062M fatal user error>
org.apache.openjpa.persistence.ArgumentException: "model.Address.person"
declares column "ADDRESS_PHONE", but this column does not exist in table
"dbo.person_addresses".

	Does OpenJPA assume that DB collation is always case
insensitive?

Thanks for your help!

- Howard

-----Original Message-----
From: Pinaki Poddar [mailto:ppoddar@apache.org] 
Sent: Monday, June 07, 2010 11:28 PM
To: users@openjpa.apache.org
Subject: RE: bidirectional one-to-many relationship with join-table


Hi,
  1. what is the settings for openjpa.jdbc.SynchronizeMappings property?
  2. is there an existing schema?
  
I ran your example as it is to define the schema on a MySQL databse.
It ended up with three columns on PERSON_ADDRESSES join table
   CREATE TABLE person_addresses (
      ADDRESS_PHONE VARCHAR(255), 
      PERSON_SSN BIGINT, 
      phone VARCHAR(255))

Quite possibly a bug.

Editing line 03 of your mapping spec 

01: @JoinTable(name="person_addresses",
02:      joinColumns = @JoinColumn(name="person_ssn",
referencedColumnName="ssn"),
03:       inverseJoinColumns = @JoinColumn(name="phone",
referencedColumnName="phone")) 

Edit line 03 to
   inverseJoinColumns = @JoinColumn(name="address_phone",
referencedColumnName="phone")) 

Got rid of the third column on the join table.
But obviously naming of join table's columns has a problem that requires
further investigation. 
But see if the suggested edit helps. 

-----
Pinaki 
-- 
View this message in context:
http://openjpa.208410.n2.nabble.com/bidirectional-one-to-many-relationsh
ip-with-join-table-tp678479p5152078.html
Sent from the OpenJPA Users mailing list archive at Nabble.com.

This email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. Please note that any views or opinions presented in this email are solely those of the author and do not necessarily represent those of the company. Finally, the recipient should check this email and any attachments for the presence of viruses. The company accepts no liability for any damage caused by any virus transmitted by this email. If you have received this email in error please delete it and notify the system administrator at administrator@antennasoftware.com

RE: bidirectional one-to-many relationship with join-table

Posted by Pinaki Poddar <pp...@apache.org>.
Hi,
  1. what is the settings for openjpa.jdbc.SynchronizeMappings property?
  2. is there an existing schema?
  
I ran your example as it is to define the schema on a MySQL databse.
It ended up with three columns on PERSON_ADDRESSES join table
   CREATE TABLE person_addresses (
      ADDRESS_PHONE VARCHAR(255), 
      PERSON_SSN BIGINT, 
      phone VARCHAR(255))

Quite possibly a bug.

Editing line 03 of your mapping spec 

01: @JoinTable(name="person_addresses",
02:      joinColumns = @JoinColumn(name="person_ssn",
referencedColumnName="ssn"),
03:       inverseJoinColumns = @JoinColumn(name="phone",
referencedColumnName="phone")) 

Edit line 03 to
   inverseJoinColumns = @JoinColumn(name="address_phone",
referencedColumnName="phone")) 

Got rid of the third column on the join table.
But obviously naming of join table's columns has a problem that requires
further investigation. 
But see if the suggested edit helps. 

-----
Pinaki 
-- 
View this message in context: http://openjpa.208410.n2.nabble.com/bidirectional-one-to-many-relationship-with-join-table-tp678479p5152078.html
Sent from the OpenJPA Users mailing list archive at Nabble.com.

RE: bidirectional one-to-many relationship with join-table

Posted by Howard Mak <hm...@antennasoftware.com>.
Thanks.

@Entity
@Table(name="person")
public class Person { 
   @Id
   private long ssn;
   
   @OneToMany(cascade=CascadeType.ALL) 
   @JoinTable(name="person_addresses", 
       joinColumns        = @JoinColumn(name="person_ssn",
referencedColumnName="ssn"), 
       inverseJoinColumns = @JoinColumn(name="phone",
referencedColumnName="phone")) 
    private Set<Address> addresses = new HashSet<Address>();

@Entity
@Table(name="address")
public class Address { 
   @Id 
   private String phone; 

   @ManyToOne(fetch=FetchType.LAZY)
   @JoinColumn(table="person_addresses", referencedColumnName="ssn") 
   private Person person;
}

results in

Exception in thread "main" <openjpa-2.0.0-beta-r422266:903062M fatal
user error> org.apache.openjpa.persistence.ArgumentException:
"model.Address.person" declares column "ADDRESS_PHONE", but this column
does not exist in table "dbo.person_addresses".
	at
org.apache.openjpa.jdbc.meta.MappingInfo.mergeColumn(MappingInfo.java:69
2)
	at
org.apache.openjpa.jdbc.meta.MappingInfo.createJoins(MappingInfo.java:13
04)
	at
org.apache.openjpa.jdbc.meta.MappingInfo.createForeignKey(MappingInfo.ja
va:1084)
	at
org.apache.openjpa.jdbc.meta.FieldMappingInfo.getJoin(FieldMappingInfo.j
ava:213)
	at
org.apache.openjpa.jdbc.meta.FieldMappingInfo.getJoin(FieldMappingInfo.j
ava:182)
	at
org.apache.openjpa.jdbc.meta.FieldMapping.mapJoin(FieldMapping.java:585)
	at
org.apache.openjpa.jdbc.meta.strats.RelationFieldStrategy.map(RelationFi
eldStrategy.java:162)
	at
org.apache.openjpa.jdbc.meta.FieldMapping.setStrategy(FieldMapping.java:
146)
	at
org.apache.openjpa.jdbc.meta.RuntimeStrategyInstaller.installStrategy(Ru
ntimeStrategyInstaller.java:78)
	at
org.apache.openjpa.jdbc.meta.FieldMapping.resolveMapping(FieldMapping.ja
va:496)
	at
org.apache.openjpa.jdbc.meta.FieldMapping.resolve(FieldMapping.java:461)
	at
org.apache.openjpa.jdbc.meta.ClassMapping.resolveMapping(ClassMapping.ja
va:853)
	at
org.apache.openjpa.meta.ClassMetaData.resolve(ClassMetaData.java:1711)
	at
org.apache.openjpa.meta.MetaDataRepository.processBuffer(MetaDataReposit
ory.java:786)
	at
org.apache.openjpa.meta.MetaDataRepository.resolveMapping(MetaDataReposi
tory.java:747)
	at
org.apache.openjpa.meta.MetaDataRepository.resolve(MetaDataRepository.ja
va:631)
	at
org.apache.openjpa.meta.MetaDataRepository.getMetaDataInternal(MetaDataR
epository.java:385)
	at
org.apache.openjpa.meta.MetaDataRepository.getMetaData(MetaDataRepositor
y.java:358)
	at
org.apache.openjpa.jdbc.meta.MappingRepository.getMapping(MappingReposit
ory.java:355)
	at
org.apache.openjpa.jdbc.meta.MappingTool.getMapping(MappingTool.java:679
)
	at
org.apache.openjpa.jdbc.meta.MappingTool.validate(MappingTool.java:737)
	at
org.apache.openjpa.jdbc.meta.MappingTool.run(MappingTool.java:653)
	at
org.apache.openjpa.jdbc.kernel.JDBCBrokerFactory.synchronizeMappings(JDB
CBrokerFactory.java:149)
	at
org.apache.openjpa.jdbc.kernel.JDBCBrokerFactory.synchronizeMappings(JDB
CBrokerFactory.java:159)
	at
org.apache.openjpa.jdbc.kernel.JDBCBrokerFactory.newBrokerImpl(JDBCBroke
rFactory.java:117)
	at
org.apache.openjpa.kernel.AbstractBrokerFactory.newBroker(AbstractBroker
Factory.java:194)
	at
org.apache.openjpa.kernel.DelegatingBrokerFactory.newBroker(DelegatingBr
okerFactory.java:152)
	at
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityMana
ger(EntityManagerFactoryImpl.java:200)
	at
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityMana
ger(EntityManagerFactoryImpl.java:151)
	at
org.apache.openjpa.persistence.EntityManagerFactoryImpl.createEntityMana
ger(EntityManagerFactoryImpl.java:57)

but if I add @SecondaryTable
    @SecondaryTable(name="person_addresses",
pkJoinColumns=@PrimaryKeyJoinColumn(name="phone"))
    public class Address { 
    }

The exception goes away.  This is with Open JPA 2.0.0.  Is this a bug?

- Howard 

-----Original Message-----
From: Pinaki Poddar [mailto:ppoddar@apache.org] 
Sent: Monday, June 07, 2010 3:21 PM
To: users@openjpa.apache.org
Subject: Re: bidirectional one-to-many relationship with join-table


See @JoinColumn annotation

-----
Pinaki 
-- 
View this message in context:
http://openjpa.208410.n2.nabble.com/bidirectional-one-to-many-relationsh
ip-with-join-table-tp678479p5150661.html
Sent from the OpenJPA Users mailing list archive at Nabble.com.

This email and any files transmitted with it are confidential and intended solely for the use of the individual or entity to whom they are addressed. Please note that any views or opinions presented in this email are solely those of the author and do not necessarily represent those of the company. Finally, the recipient should check this email and any attachments for the presence of viruses. The company accepts no liability for any damage caused by any virus transmitted by this email. If you have received this email in error please delete it and notify the system administrator at administrator@antennasoftware.com

Re: bidirectional one-to-many relationship with join-table

Posted by Pinaki Poddar <pp...@apache.org>.
See @JoinColumn annotation

-----
Pinaki 
-- 
View this message in context: http://openjpa.208410.n2.nabble.com/bidirectional-one-to-many-relationship-with-join-table-tp678479p5150661.html
Sent from the OpenJPA Users mailing list archive at Nabble.com.

Re: bidirectional one-to-many relationship with join-table

Posted by Howard-5 <hm...@antennasoftware.com>.
Hi,

I have a legacy join table that does not following JPA naming conventions. 
Anyone know what annotations should be use if the join table does not use
the default column names?  e.g.,


Pinaki Poddar wrote:
> 
> CREATE TABLE PERSON_ADDRESSES (
>   ADDRESS_PHONE ...
>   PERSON_SSN ...
> ) 
> 

is instead

CREATE TABLE PERSON_ADDRESSES (
  XYZ_PHONE ...
  PERSON_SSN ...
)

Thanks.
-- 
View this message in context: http://openjpa.208410.n2.nabble.com/bidirectional-one-to-many-relationship-with-join-table-tp678479p5149822.html
Sent from the OpenJPA Users mailing list archive at Nabble.com.

Re: bidirectional one-to-many relationship with join-table

Posted by Pinaki Poddar <pp...@apache.org>.
Hi Frank,
  >  Please note that I was referring to the join-table, not the
"entity"-tables. 
  Sorry to have missed that. Noted now.
  SVN commit 684822 adds conditions to convert an UPDATE to DELETE for the
JoinTable.
  Please verify, if possible, whether this change works for you.

-- 
View this message in context: http://n2.nabble.com/bidirectional-one-to-many-relationship-with-join-table-tp678479p686463.html
Sent from the OpenJPA Users mailing list archive at Nabble.com.


Re: bidirectional one-to-many relationship with join-table

Posted by Frank Schwarz <fs...@gmx.net>.

Pinaki Poddar wrote:
> 
> Hi, 
> 
> Address address = person.getAddresses().iterator().next(); 
> person.getAddresses().remove(address); 
> address.setPerson(null);
> 
> Generally speaking, in JPA world, nulling a relation or removing an
> element from a collection do not imply that the corresponding database
> record is deleted. To delete records from database, em.remove() needs to
> be invoked.
> 
> However, delete-orphan behavior that your example code implies is
> supported by OpenJPA with @Dependent/@ElementDependent annotation on a
> relation. 
> 

Please note that I was referring to the join-table, not the "entity"-tables.
I consider nullifying one side of the join-table not to be efficient for
dissolving a relationship. It will probably do no harm, but the join-table
will gradually be messed up with these "half-null"-tupels. 

If you enforce integrity so that the Address_Phone id has to be unique in
the join-table (otherwise it would be a many-to-many relationship type), you
will never be able to establish new Person-Address connection with that
particular address object.

-- Frank



-- 
View this message in context: http://n2.nabble.com/bidirectional-one-to-many-relationship-with-join-table-tp678479p685702.html
Sent from the OpenJPA Users mailing list archive at Nabble.com.


Re: bidirectional one-to-many relationship with join-table

Posted by Pinaki Poddar <pp...@apache.org>.
Hi,
  Please see my latest JIRA comments to this issue.

-- 
View this message in context: http://n2.nabble.com/bidirectional-one-to-many-relationship-with-join-table-tp678479p685035.html
Sent from the OpenJPA Users mailing list archive at Nabble.com.


Re: bidirectional one-to-many relationship with join-table

Posted by Frank Schwarz <fs...@gmx.net>.
Pinaki, I have put a comment on your bug report:
https://issues.apache.org/jira/browse/OPENJPA-692

It seems that the JSR317 expert group is going to standardize this kind of
mapping (see chapter 9.1.22 of JPA2.0 early draft). I am rather pleased to
see that the expert group finally gave up its didactic attitude and now sees
uni-/bi-directionality and join-table/join-column as orthogonal aspects of
the one-to-many-relationship type.

-- Frank
-- 
View this message in context: http://n2.nabble.com/bidirectional-one-to-many-relationship-with-join-table-tp678479p683820.html
Sent from the OpenJPA Users mailing list archive at Nabble.com.


Re: bidirectional one-to-many relationship with join-table

Posted by Pinaki Poddar <pp...@apache.org>.
Hi Frank,
  Yes, I can reproduce the error during update with this mapping.
  Let me analyze further before responding further.


-- 
View this message in context: http://n2.nabble.com/bidirectional-one-to-many-relationship-with-join-table-tp678479p683125.html
Sent from the OpenJPA Users mailing list archive at Nabble.com.


Re: bidirectional one-to-many relationship with join-table

Posted by Frank Schwarz <fs...@gmx.net>.
Pinaki, thank you for this comprehensive answer.

The new mapping now looks like this (in case I have overlooked something):

@Entity
public class Person {

	@Id
	@GeneratedValue(strategy=GenerationType.SEQUENCE)
	private long id;

	@OneToMany(cascade=CascadeType.ALL)
	@JoinTable(name="PERSON_ADDRESS",
                  joinColumns=@JoinColumn(name="PERSON_ID",
referencedColumnName="ID"),
                  inverseJoinColumns=@JoinColumn(name="ADDRESS_ID",
referencedColumnName="ID"))
 	private Set&lt;Address&gt; addresses = new HashSet&lt;Address&gt;();
}

@Entity
public class Address {

	@Id
	@GeneratedValue(strategy=GenerationType.SEQUENCE) 
	private long id;

	@ManyToOne
	@JoinColumn(table="PERSON_ADDRESS", referencedColumnName="ID")
	private Person person;
}


To cut a long story short: The schema looks good, but it is not working
either.



It seems to me that converting the bidirectional relationship to two
unidirectional ones (that happen to map to the same tables/columns) poses a
problem for OpenJPA (version 1.1.0):

Persisting new persons with addresses leads to duplicate entries in the
lookup-table
"address.setPerson(null)" causes an
org.apache.openjpa.util.OptimisticException: Optimistic locking errors were
detected when flushing to the data store.  The following objects may have
been concurrently modified in another transaction ...

with SQL: UPDATE TEST.PERSON_ADDRESS SET PERSON_ID = ? WHERE ADDRESS_ID = ?
[params=(null) null, (long) 2]
Deleting persons with addresses also leads to OptimisticExceptions (probably
due to duplicate delete statements for the join-table) 


I would create a bug report/enhancement request, if you would indicate me,
which of the tested mappings should work with OpenJPA.


-- Frank
-- 
View this message in context: http://n2.nabble.com/bidirectional-one-to-many-relationship-with-join-table-tp678479p682369.html
Sent from the OpenJPA Users mailing list archive at Nabble.com.

Re: bidirectional one-to-many relationship with join-table

Posted by Pinaki Poddar <pp...@apache.org>.
Hi,
  Please try the following mapping for a bi-directional one-to-many relation
with a join table.
 
public class Person {
  @Id
  private long ssn;
	
  @OneToMany(cascade=CascadeType.ALL)
  @JoinTable(name="PERSON_ADDRESSES",
      joinColumns           = @JoinColumn(name="PERSON_SSN",     
referencedColumnName="SSN"),
      inverseJoinColumns = @JoinColumn(name="ADDRESS_PHONE",
referencedColumnName="PHONE"))
   private Set<Address> addresses = new HashSet<Address>();

public class Address {
  @Id
  private String phone;
	
  @ManyToOne
  @JoinColumn(table="PERSON_ADDRESSES", referencedColumnName="SSN")
  private Person person;


The above mapping manifests to following database schema in MySQL

CREATE TABLE ADDRESS (
  phone varchar(255) NOT NULL,
  PRIMARY KEY  (phone)
)

CREATE TABLE PERSON (
  `ssn` bigint(20) NOT NULL,
  PRIMARY KEY  (`ssn`)
) 

and a Join Table
CREATE TABLE PERSON_ADDRESSES (
  ADDRESS_PHONE varchar(255) default NULL,
  PERSON_SSN       bigint(20) default NULL,
  KEY I_PRSNSSS_ADDRESS_PHONE (ADDRESS_PHONE),
  KEY I_PRSNSSS_PERSON             (PERSON_SSN)
) 

Let us know if this works for you and you can perform CRUD operations on
this schema.

-- 
View this message in context: http://n2.nabble.com/bidirectional-one-to-many-relationship-with-join-table-tp678479p681198.html
Sent from the OpenJPA Users mailing list archive at Nabble.com.


Re: bidirectional one-to-many relationship with join-table

Posted by Frank Schwarz <fs...@gmx.net>.

Pinaki Poddar wrote:
> 
> http://openjpa.apache.org/docs/latest/manual/manual.html#jpa_overview_mapping_assoccoll
> 

I tried that - with little success however.

Say, the object model looks like that: Person <-->* Address. The target
database layout may look like: PERSON(ID, ...), ADDRESS(ID, ...),
PERSON_ADDRESS(PERSON_ID, ADDRESS_ID).

first try:
@Entity
public class Person {
	@OneToMany(mappedBy="person", cascade=CascadeType.ALL)
	private Set<Address> addresses = new HashSet<Address>();
}
@Entity
public class Address {
	@ManyToOne
	@JoinTable(name="PERSON_ADDRESS",
joinColumns=@JoinColumn(name="ADDRESS_ID"))
	private Person person;
}
The schema looks fine. 

Loading the address collections produces incorrect SQL statement: "SELECT
t1.id, t1.city, t1.street FROM PERSON_ADDRESS t0, Address t1 WHERE
t0.PERSON_ID = ? [params=(long) 1]"

second try:
@Entity
public class Person {
	@OneToMany(mappedBy="person", cascade=CascadeType.ALL)
	@JoinTable(name="PERSON_ADDRESS",
inverseJoinColumns=@JoinColumn(name="ADDRESS_ID"))
	private Set<Address> addresses = new HashSet<Address>();
}
@Entity
public class Address {
	@ManyToOne
	private Person person;
}
org.apache.openjpa.util.MetaDataException: You have supplied columns for
"model.Person.addresses<element:class model.Address>", but this mapping
cannot have columns in this context.

third try:
@Entity
public class Person {
	@OneToMany(mappedBy="person", cascade=CascadeType.ALL)
	@JoinTable(name="PERSON_ADDRESS",
joinColumns=@joinColumn(name="ADDRESS_ID"))
	private Set<Address> addresses = new HashSet<Address>();
}
@Entity
public class Address {
	@ManyToOne
	private Person person;
}
The schema is wrong: no join table but a join column in the Address table.

4th try:
@Entity
public class Person {
	@OneToMany(mappedBy="person", cascade=CascadeType.ALL)
	@JoinTable(name="PERSON_ADDRESS")
	private Set<Address> addresses = new HashSet<Address>();
}
@Entity
public class Address {
	@ManyToOne
	private Person person;
}
The schema is wrong: no join table but a join column in the Address table.

5th try (secondary table):
@Entity
public class Person {
	@OneToMany(mappedBy="person", cascade=CascadeType.ALL)
	private Set<Address> addresses = new HashSet<Address>();
}
@Entity
@SecondaryTable(name="PERSON_ADDRESS",
pkJoinColumns=@PrimaryKeyJoinColumn(name="ADDRESS_ID"))
public class Address {
	@ManyToOne
	@JoinColumn(table="PERSON_ADDRESS")
	private Person person;
}
The schema is OK, however loading the address-collection still leads to the
incorrect SQL statement.

I am out of ideas.

-- Frank

-- 
View this message in context: http://n2.nabble.com/bidirectional-one-to-many-relationship-with-join-table-tp678479p679024.html
Sent from the OpenJPA Users mailing list archive at Nabble.com.


Re: bidirectional one-to-many relationship with join-table

Posted by Pinaki Poddar <pp...@apache.org>.
Hi,
> Does OpenJPA support bidirectionality with a join-table

Yes. Please refer [1]

[1]
http://openjpa.apache.org/docs/latest/manual/manual.html#jpa_overview_mapping_assoccoll

-- 
View this message in context: http://n2.nabble.com/bidirectional-one-to-many-relationship-with-join-table-tp678479p678742.html
Sent from the OpenJPA Users mailing list archive at Nabble.com.