开发者

Hibernate create object in relation through factory

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?


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.


If you are working with annotations, please try:

class Card {
  private int id;

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

};


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜