2

I'm new to Hibernate and I'm trying to achieve the following: the class i'm working with is persistent and is stored in DB. It looks like this:

class Card {
  private int id;
  private CardPrototype prototype;  // fixed this line
  ...
};

and has all needed getters and setters and annotations for persistence. Class Card is stored in DB table like this

CREATE TABLE Card (
  id SERIAL NOT NULL,
  prototype CHAR(85) NOT NULL,
  ...
)

The class in relation is CardPrototype, it is identified by a string identifier, and it is not stored in database at all. However, I have a factory class with non-static method

CardPrototype getPrototype (final String id)

which I want to use to resolve Card.prototype field during ORM object loading. Could you please help me to achieve this with Hibernate?

powerMicha
  • 2,753
  • 1
  • 24
  • 31
jatvarthur
  • 23
  • 2

3 Answers3

1

You can use a @Type annotation and do your own loading and saving. See How to store date/time and timestamps in UTC time zone with JPA and Hibernate , especially the answer with UtcTimestampType for an example.

Community
  • 1
  • 1
Alexander Torstling
  • 18,552
  • 7
  • 62
  • 74
  • Thanks for this idea. I implemented my custom type for loading and mapping CardPrototype from String based on UserType using sample from this blog post [link](http://java.dzone.com/articles/annotating-custom-types) – jatvarthur Jul 15 '11 at 07:05
0

If you are working with annotations, please try:

class Card {
  private int id;

  @ManyToOne
  private CardPrototype prototype;  // fixed this line
  ...

};
powerMicha
  • 2,753
  • 1
  • 24
  • 31
  • 1
    Hi, thanks for fixing my typo. The problem with this is that CardPrototype should be in database, while it is not. And when using this there is an exception while Hibernate executes SQL joining non-existent table cardprototype. – jatvarthur Jul 15 '11 at 07:11
0

A simple solution would be to have a String prototypeId field in your Card class. Then use @PostLoad to retrieve the object from the factory once you have the string id

@PostLoad
public void loadCardProtoType() {
   CardPrototypeFactory factoryInstance = new CardPrototypeFactory();
   setCardPrototype(factoryInstance.getPrototype(this.prototypeId));
}

Now, when you use the Card class you will have the CardPrototype instance in it. Also you can make the prototypeId as a private field.

Satadru Biswas
  • 1,555
  • 2
  • 13
  • 23
  • Yes, this is the first idea that came to my mind, but actually, I don't want to have extra field in my class and synchronize if with prototype every time. – jatvarthur Jul 15 '11 at 07:09