Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Composite Key with Hibernate

Tags:

hibernate

In order to generate the next SQL code:

create table users (
    user_name varchar(15) not null primary key, 
    user_pass varchar(15) not null);

create table user_roles(
    username varchar(15) not null,
    role_name varchar(15) not null, 
    primary key(usernmae, rolename)
);

You can use code such as:

 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
        "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
        "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">

<hibernate-mapping>
    <class name="databaselayer.users.UserDB" table="users">
        <id name="username" type="string" column="user_name">
                <meta attribute="scope-set">public</meta>      
        </id>    
        <property name="password" type="string" column="user_pass"  not-null="true"/>
        <set name="roles" cascade="save-update" inverse="true">
                <key column="user_name"/>
                <one-to-many class="databaselayer.users.RoleDB"/>
        </set>                       
    </class>
   <class name="databaselayer.users.RoleDB" table="user_roles">
        <composite-id>
            <key-many-to-one name="username" class="databaselayer.users.UserDB" column="user_name"/>
            <key-property name="role" type="string" column="role_name"/>
        </composite-id>             
    </class>          
</hibernate-mapping>

You may need to have your classes as well as hbm mapping files in your classpath.
Next I post my Ant schema target:
Note ${basedir}/build/WEB-INF/classes contains both *.class and *.hbm.xml files.

<target name="schema" description="Generate DB schema from the O/R mapping files">
    <hibernatetool destdir="${basedir}">            
        <classpath path="${basedir}/build/WEB-INF/classes">
            <fileset dir="${basedir}/build/WEB-INF/classes">
            <include name="**/*"/>
        </fileset>              
        </classpath>
        <configuration configurationfile="${basedir}/hibernate.cfg.xml"/>
        <hbm2ddl 
            drop="true" 
            create="true"
            export="true"
            outputfilename="libamo2-ddl.sql"
            delimiter=";"
            format="true"/>       
    </hibernatetool>
</target>

Related links from Hibernate documentation

Composite ID
Components as composite Id

like image 827
Sergio del Amo Avatar asked Apr 15 '09 13:04

Sergio del Amo


People also ask

Can we use composite keys in Hibernate?

Use embeddable objects to join two primary keys into one composite key. Every JPA entity has a primary key, but some entities have more than one value as their primary key. In this case, you need to use a composite key. This Java tip introduces you to using composite keys in JPA and Hibernate.

What is the composite key in Hibernate?

A composite primary key, also called a composite key, is a combination of two or more columns to form a primary key for a table. In JPA, we have two options to define the composite keys: the @IdClass and @EmbeddedId annotations.


2 Answers

Look in the hibernate docs for the 'composite-id' element. The following may at least give you the intent -- replace your id element with:

<composite-id>
    <key-property name="username"/>
    <key-property name="role"/>
</composite-id>

Note that it's strongly recommended to instead make your ID a separate class ('component') that implements hashCode and equals properly, and that is Serializable. Otherwise you'll have only very awkward ways to lookup your object using session.get() or session.load().

like image 66
Chris Winters Avatar answered Sep 28 '22 00:09

Chris Winters


I add to the answer of Chris Winters, but using foreign keys in order to implement it. You can write:

<composite-id>
    <key-many-to-one name="username" class="com.foo.User" />
    <key-many-to-one name="role_id" class="com.foo.Role" />
</composite-id>

This will do the job and also take care of foreign keys, and will give you the flexibility to define by yourself which tables are created in the database by Hibernate.

like image 33
Jadiel de Armas Avatar answered Sep 28 '22 00:09

Jadiel de Armas