How to use @Formula in Hibernate/JPA

EMM

I am trying to see how @Formula annotation works using a simple piece of code below.

I am able to print out values of description and bidAmount columns but the fields annotated with @Formula i.e. shortDescription and averageBidAmount return null.

Can anyone please help point out what is wrong with the code here?

I am using Hibernate 5.0, postgresql-9.3-1102-jdbc41 and TestNG on a Mac OSX.

    import java.math.BigDecimal;
    import java.util.List;
    import javax.persistence.Entity;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Persistence;
    import javax.transaction.UserTransaction;
    import org.testng.annotations.Test;
    import com.my.hibernate.env.TransactionManagerTest;

    public class DerivedPropertyDemo extends TransactionManagerTest {

      @Test
      public void storeLoadMessage() throws Exception {
        EntityManagerFactory emf = Persistence.createEntityManagerFactory("HelloWorldPU");
        try {
          {
            UserTransaction tx = TM.getUserTransaction();
            tx.begin();
            EntityManager em = emf.createEntityManager();

            DerivedProperty derivedProperty1 = new DerivedProperty();
            derivedProperty1.description = "Description is freaking good!!!";
            derivedProperty1.bidAmount = BigDecimal.valueOf(100D);

            DerivedProperty derivedProperty2 = new DerivedProperty();
            derivedProperty2.description = "Description is freaking bad!!!";
            derivedProperty2.bidAmount = BigDecimal.valueOf(200D);

            DerivedProperty derivedProperty3 = new DerivedProperty();
            derivedProperty3.description = "Description is freaking neutral!!!";
            derivedProperty3.bidAmount = BigDecimal.valueOf(300D);

            em.persist(derivedProperty1);
            em.persist(derivedProperty2);
            em.persist(derivedProperty3);

            tx.commit();

            for (DerivedProperty dp : getDerivedProperty(em)) {
              System.out.println("============================");
              System.out.println(dp.description);
              System.out.println(dp.bidAmount);
              System.out.println(dp.getShortDescription());
              System.out.println(dp.getAverageBidAmount());
              System.out.println("#############################");
            }
            em.close();
          }
        } finally {
          TM.rollback();
          emf.close();
        }
      }


     public List<DerivedProperty> getDerivedProperty(EntityManager em) {
      List<DerivedProperty> resultList = em.createQuery("from " + DerivedProperty.class.getSimpleName()).getResultList();
      return resultList;
  }
}

My Entity class is:

@Entity
class DerivedProperty {

  @Id
  @GeneratedValue
  protected Long id;

  protected String description;

  protected BigDecimal bidAmount;

  @org.hibernate.annotations.Formula("substr(description, 1, 12)")
  protected String shortDescription;

  @org.hibernate.annotations.Formula("(select avg(b.bidAmount) from DerivedProperty b where b.bidAmount = 200)")
  protected BigDecimal averageBidAmount;

  public String getShortDescription() {
    return shortDescription;
  }

  public BigDecimal getAverageBidAmount() {
    return averageBidAmount;
  }
}

EDIT

I am following the book Java Persistence with Hibernate 2nd Ed.

enter image description here

Thanks

Dragan Bozanovic

Your DerivedProperty instances are returned from the persistence context (only their ids are used from the result set returned from the query). That's why formulas haven't been evaluated.

Persistence context is not cleared if you don't close the entity manager. Try adding em.clear() after you commit the first transaction to force clearing the persistence context.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to use OneToOne with Hibernate Formula

From Dev

How to use a calculated name in a formula

From Dev

How to use the outcome of a formula as the value for Vlookup or another IF formula

From Dev

how to use @NameLookUp formula in lotus notes in Java

From Dev

How to use entity field in Hibernate @Formula

From Dev

How to convert a formula into MathML for use in a web page

From Dev

How to use a special formula in Magento cart

From Dev

How to use index to assign address and formula to arrays?

From Dev

How to use formula as character vector in curve()

From Dev

How to use a filter inside an array formula?

From Dev

How to use IFERROR inside an array formula?

From Dev

How to use different formula in case of en error?

From Dev

How to use INDIRECT with a SUMIF formula for a date range

From Dev

How to use a an address formula as the limits of the COUNTIF range

From Dev

How to use RANDBETWEEN() x times in a single formula?

From Dev

How to use multiple array in one countif formula

From Dev

How to use a logical function in a formula as text

From Dev

How to use a cell in Excel that has a formula as a condition?

From Dev

how to use variable containing strings in formula vba

From Dev

How do I use an IN statement in SSRS Formula

From Dev

How to use a sheet name that is referenced in a cell in a formula?

From Dev

How to use IsLeaf in mondrian mdx formula?

From Dev

How to use variable string in index formula in VBA?

From Dev

How to use activecell.formula in for loop VBA

From Dev

HandsonTable - How to use the "IF" Formula from RuleJS

From Dev

how to use a string as formula for mathematical calculations in php?

From Dev

How do I use a nested IF(AND) in an Excel array formula?

From Dev

How to use dcast.data.table with formula as string

From Dev

How can I use the OFFSET() formula with a range of values?

Related Related

  1. 1

    How to use OneToOne with Hibernate Formula

  2. 2

    How to use a calculated name in a formula

  3. 3

    How to use the outcome of a formula as the value for Vlookup or another IF formula

  4. 4

    how to use @NameLookUp formula in lotus notes in Java

  5. 5

    How to use entity field in Hibernate @Formula

  6. 6

    How to convert a formula into MathML for use in a web page

  7. 7

    How to use a special formula in Magento cart

  8. 8

    How to use index to assign address and formula to arrays?

  9. 9

    How to use formula as character vector in curve()

  10. 10

    How to use a filter inside an array formula?

  11. 11

    How to use IFERROR inside an array formula?

  12. 12

    How to use different formula in case of en error?

  13. 13

    How to use INDIRECT with a SUMIF formula for a date range

  14. 14

    How to use a an address formula as the limits of the COUNTIF range

  15. 15

    How to use RANDBETWEEN() x times in a single formula?

  16. 16

    How to use multiple array in one countif formula

  17. 17

    How to use a logical function in a formula as text

  18. 18

    How to use a cell in Excel that has a formula as a condition?

  19. 19

    how to use variable containing strings in formula vba

  20. 20

    How do I use an IN statement in SSRS Formula

  21. 21

    How to use a sheet name that is referenced in a cell in a formula?

  22. 22

    How to use IsLeaf in mondrian mdx formula?

  23. 23

    How to use variable string in index formula in VBA?

  24. 24

    How to use activecell.formula in for loop VBA

  25. 25

    HandsonTable - How to use the "IF" Formula from RuleJS

  26. 26

    how to use a string as formula for mathematical calculations in php?

  27. 27

    How do I use a nested IF(AND) in an Excel array formula?

  28. 28

    How to use dcast.data.table with formula as string

  29. 29

    How can I use the OFFSET() formula with a range of values?

HotTag

Archive