Landei
Landei

Reputation: 54584

JPA2: How to map only certain table rows to an entity?

I have a table I cannot change with approximately this structure

ID, name, purpose, rubbish...
1, foo, PRICING, ...
2, bar, INVENTORY, ...
3, bar, PRICING, ...

What is the preferred way to map only the lines with purpose=PRICING to an Entity? Is there a way to do this with JPA annotations or do I need a view?

Upvotes: 3

Views: 705

Answers (3)

adrianboimvaser
adrianboimvaser

Reputation: 2633

You might use SINGLE_TABLE inheritance strategy, and use "purpose" as discriminator column like this:

@Entity
@Table(name="THE_TABLE")
@Inheritance(strategy=SINGLE_TABLE)
@DiscriminatorColumn(name="purpose", discriminatorType=STRING)
@DiscriminatorValue("PRICING")
public class Pricing{ ... }

Upvotes: 4

Karthik Ramachandran
Karthik Ramachandran

Reputation: 12175

If I understand your question correctly, you're trying to only select rows where purpose=Pricing.

There are to basic steps: (1) create an entity, (2) create a query. The entity would use annotations and be similar to this :

 @Entity 
 public class Foo
  { 
    String name;
    String inventory; 
    ....
  }     

Then you simply construct and execute a query :

.....
    @PersistenceContext
EntityManager entityManager;

 .....
 public List<Foo> getAllWithPricing()
 {
     return entityManager.createQuery("select o from Foo o where o.purpose='PRICING'", Foo.class).getResultList()

 } 

Upvotes: 0

darioo
darioo

Reputation: 47193

I don't believe pure JPA supports this.

If you're using Hibernate, you can use filters. Nice examples can be found here.

This is one example when using vendor specific extensions are real nice, but they lock you to one implementation. It's possible other implementations (OpenJPA, EclipseLink...) also support this, but I haven't looked at them yet.

Upvotes: 0

Related Questions