Joda Money Amount Divided into 2 Columns Using Spring JPA Data

I am trying to use the JODA money class with Jadira types to handle matching with Hibernate 4.

It works fine (except that I have too many currency fields).

But I need to put together a summary query to summarize some of the results.

This is a type declaration.

@Columns(columns = { @Column(name = "total_currency", length=10), @Column(name = "total") }) @Type(type = "org.jadira.usertype.moneyandcurrency.joda.PersistentMoneyAmountAndCurrency") private Money total; 

And I'm trying to define a query, for example:

 @Query(value="select sum(oi.total) from OrderItem oi where oi.order = ?1") Double calculateSubtotal(Order order); 

Is there a way to combine the query with the "Money" field using JPQL?

Thanks.

+5
source share
1 answer

There are two ways, but they are limited, and I doubt that you will really like them :( The main limitation is that in Hibernate HQL you cannot refer to methods if they are not displayable properties - the end of the story. Hibernate does not support method invocation

On the other hand, you can match one column as many times as you want, if you remember that only one match can be updated. With that in mind, the first step is that you need to make Hibernate aware of joda Money . Obviously, you cannot just comment on it. There are two ways to do this:

  • You can use XML to actually annotate the Money class as the @Embeddable class. The hibernate XML configuration can be used to configure what is a private source. From what I see in the Money joda - time setting.

  • The second solution. Probably the one I would use. Include the Money class in Wrapper, which is declared as @Embeddable. With this built-in wrapper, you can define several mappings for existing database columns. When you set the value to WRAPER, this value will be pressed for the soda time that is inside.

Once you do this, you can open through the shell any attribute of the Money class that you want and make any aggregation you want.

 @Embeddable public class MoneyWrapper { @Columns(columns = { @Column(name = "total_currency", length=10), @Column(name = "total") }) @Type(type = "org.jadira.usertype.moneyandcurrency.joda.PersistentMoneyAmountAndCurrency") Money totalmoney; @Column(name = "total",updateable=false,insterable=false); BigDecimal total to agregate; @Column(name = "total_currency",updateable=false,insterable=false); BigDecimal totalCurrency; } 

As a result of this mapping, you can make a request like:

@Query (value = "select select sum (oi.total.totalCurrency) from OrderItem oi, where oi.order =? 1")

+3
source

Source: https://habr.com/ru/post/1208885/


All Articles