Reputation: 14044
Is it possible to do a one-to-one mapping to a property, not using primary keys? Basically, what i want to do is to have a property in my "Parent" class, which only holds one reference to one of its children, based on some rule. For example, it could be "last added child". I know this is fairly simple to do with queries, but is it possible to have "intelligent" properties? So you dont have to write anything besides .load(Parent.class, pk) and then work with the instance from there on.
Same question applies for one-to-many relationships, would it be possible to apply rules for that as well? And finally, would it be possible to integrate these rules with paramenters to the getmethod?
So you could have a getChildren(from, to) ish method :)
Upvotes: 1
Views: 1454
Reputation: 12741
I would try using the formula attribute. This will allow you to define more complex mappings by using SQL, columns, or other expressions. I'll have to look into this more when I get home but here are some examples\articles to get you started. Apparently the source code also has examples at org.hibernate.test.onetooneformula
Many-to-One Formula Forum Post
O'Reilly Hibernate 3 Formulas Article
Upvotes: 1
Reputation: 2234
Hibernate entities are Java objects. Nothing stops you from writing logic into these objects. Actually it's a good thing if you do. You could have something like this:
@Entity
public class Parent {
...
@OneToMany
private Set<Child> children;
...
public Set<Child> getChildren() {
if (children == null) {
children = new HashSet<Child>();
}
return children;
}
public Child getLastAddedChild() {
for(Child child: getChildren()) {
... logic ...
}
return lastAddedChild;
}
}
Note that this implementation is not optimized, it's just an example. But you can do all sorts of things, like having a @Transient field for holding the last added child (using lazy initialization in the getLastAddedChild() method), or maybe hide your collection and use a method to add children to your object, etc.
As I said, hibernate entities are Objects. In a good OO desing, real objects have behavior associated with it. I would advise you to do some research on DDD (Domain Driven Design).
Upvotes: 0