Yes this is possible and it works whether or not you've specified a foreign key constraint.
All you have to do is specify the relationships either in your mapping files or by way of annotations.
Here's an SQL example to create the tables (
with no foreign key constraint!)...
Code:
create table guest (
id bigint not null primary key,
name varchar(50) not null
)
create table contact (
id bigint not null primary key,
name varchar(50) not null,
guestId bigint
)
...here's the mapping examples...
Code:
<hibernate-mapping package="test.model">
<class name="Guest" table="guest">
<id
column="id"
name="Id"
type="java.lang.Long"
>
<generator class="vm" />
</id>
<property
column="name"
length="20"
name="Name"
not-null="true"
type="string"
/>
<set inverse="true" name="ContactSet">
<key column="guestId" />
<one-to-many class="Guest" />
</set>
</class>
</hibernate-mapping>
Code:
<hibernate-mapping package="test.model">
<class name="Contact" table="contact">
<id
column="id"
name="Id"
type="java.lang.Long"
>
<generator class="vm" />
</id>
<property
column="name"
length="45"
name="Name"
not-null="true"
type="string"
/>
<many-to-one
class="Guest"
name="Guest"
not-null="true"
>
<column name="guestId" />
</many-to-one>
</class>
</hibernate-mapping>
...with the relevant Guest and Contact classes...
Code:
package test.model;
import java.io.Serializable;
/**
* @hibernate.class
* table="guest"
*/
public class Guest implements Serializable {
private Long id;
private String name;
private java.util.Set contactSet;
public Guest() { .. }
public Long getId () { .. }
public void setId (Long id) { .. }
public String getName () { .. }
public void setName (String name) { ... }
public java.util.Set getContactSet () { .. }
public void setContactSet (java.util.Set contactSet) { ... }
public void addToContactSet (Object obj) { ... }
public boolean equals (Object obj) { ... }
public int hashCode () { ... }
public String toString () { ... }
}
Code:
package test.model;
import java.io.Serializable;
/**
* @hibernate.class
* table="contact"
*/
public class Contact implements Serializable {
private java.lang.Long id;
private String name;
private Guest guest;
public Contact() { ... }
public Long getId () { ... }
public void setId(Long id) { ... }
public String getName() { ... }
public void setName(String name) { ... }
public Guest getGuest() { ... }
public void setGuest(Guest guest) { ... }
public boolean equals (Object obj) { ... }
public int hashCode () { ... }
public String toString () { ... }
}
...and your query could look like this...
Code:
List<Guest> guestList = session.createQuery(
"select g from Guest g" +
"left join g.ContactSet c" +
"where g.Id = :guestId"
).setParameter("guestId", guestId).list();
If you're interested in JPA annotations,
have a look here for an example with a Professor who has many Departments.
Hope this helps