JPA/Hibernate - Create a table with foreign key only

How can create an entity table using Hibernate that will foreign keys in it a primary key. Consider it to a joining table (with few other attributes) between two tables having many to many relationship between them.

Any sample code?


Any real reason not to use a PK? If the entity has other attributes I would say you are better off with one.

If you really dont want one you can use JPA's @EmbeddedId using a compound key

    private UserSessionId id

            @AttributeOverride(name = "userId", column = @Column(name = "user_id", nullable = false)),
            @AttributeOverride(name = "sessionId", column = @Column(name = "session_id", nullable = false)) })
    public UserSessionId getId() {

    public void setId(UserSessionId id) { = id;

Then you can define a separate entity UserSessionId that contains both FK's, at least this is how Hibernate Tools generates compound key relationships

If there are no extra fields involved in the join (ie. foreign keys only). You can use the following technique, no java domain object is required, hibernate will figure it all out for you.

You can still have other columns in your table such as creation_date, but their values will need to be updated at the database level.

There are very good examples of composed PK in the JSR document, take a look in JSR 317 in link for persistence-2_0-final-spec.pdf, 2.4 Primary Keys and Entity Identity section have great examples.

Need Your Help

Dropdownlist(ddlState) value loss when acess in Javascript after AsyncPostBackTrigger in update panel

c# .net

I have ddlCountry dropdownlist and ddlState dropdownlist. ddlState is in update panel. On selection of country I have populated its states using the selectedindexchanged event of ddlCountry. I have...