talnicolas
talnicolas

Reputation: 14053

Hibernate - Get a row with only one value of a composite primary key?

I have a table (Oracle database) that looks like:

CREATE TABLE example
(
    idEx INTEGER,
    idAdh INTEGER,
    date DATE,
    PRIMARY KEY (idEx, idAdh)
)

I have generated the corresponding classes in Netbeans and I have two classes created for this table: Example.java and ExampleId.java, this last one containing the two values of my primary key.

Now let's say I have some records here and I would like to delete one using only one value of the primary key (idEx for example, which is unique too). So first I need to get that row, but I can't find a way to do this. Would it be possible to do something like this?

Example ex = (Example) session.get(Example.class, new ExampleId(?, idEx));

I'd need something to replace that ? that would act as a wildcard.

Or maybe this is absolutely not the way to go and in this case I'd really appreciate some advices.

Upvotes: 1

Views: 2138

Answers (2)

wrschneider
wrschneider

Reputation: 18780

There is no way to get this without an HQL/JPQL/Criteria query, for good reason.

The get method returns a single object and automatically generates a query like select * from table where key = :key.

The only way you can guarantee that this query returns exactly one row is when you specify the entire key. If you don't have the full PK object available, the query will return a list of objects, at which point get is not appropriate anymore.

Upvotes: 1

Piotr Findeisen
Piotr Findeisen

Reputation: 20770

You should be able to get the ex with a HQL query.

Upvotes: 3

Related Questions