Mapping Hibernate value from another table for presentation only
I couldn't find this exact scenario via the search....
I have a scenario where I have 2 entities.
The first stores some basic info:
Table: TABLE_A ID, AccountId, FirstName,LastName
Now, I stored account ID, in the table, but i want to simply fetch the Account Name without having to add the Account entity in this first class... does hibernate have the ability to lookup a value from Account table and store it in a (for example) String accountName field in TABLE_A class? This would be just for displaying one column... Or is the ideal way to add the Entity to this class and load it?
I would strongly recommend you to create that Account
entity, even a very simple one with account ID and account name.
However if you insists not to do it, there are some alternatives you can take.
As described in "More Complex Associate Mapping", you may use a subselect to get the account name
Instead of mapping to the actual table, you may consider creating a View in DB, which includes that extra column. This should make your life in Hibernate much easier
If it is for display only instead of intended to be part of the entity (that mean, that account name is not intended to be part of the domain logic), I would recommend you to separate the concern of your presentation with your domain model design. Have an appropriate association to Account, and consider doing something like select new FooDisplayInfo(foo, foo.account.name) from Foo foo where blablabla
You can have something like:
private String accountName;
@Formula("(select acc.account_name from tb_account acc where acc.id = account_id)")
public String getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
in your main entity, now you don't need to map the association, and Hibernate will fetch account_name
everytime it fetches an instance of main entity.
By the way there are some drawbacks, Hibernate uses an nested query in your select clause to fetch accountName
, so filtering and sorting on accountName
will not perform well, are there are any good reasons not use a simple associations?
You could create the association with the Account table in the entity representing the TABLE_A table, and get the account name with a query like:
SELECT a.account.name FROM TableA a WHERE...
This will fetch only the account name, not the whole account row.
链接地址: http://www.djcxy.com/p/37098.html