EJB QL Max With Date Type : EJB Query Language « JPA « Java Tutorial






File: Message.java

import java.util.Date;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;

@Entity
public class Message {
    @Id
    private int id;
    private String message;
    @Temporal(TemporalType.DATE)
    private Date postingDate;
    @ManyToOne Conversation conversation;

    public int getId() {
        return id;
    }
    
    public void setId(int empNo) {
        this.id = empNo;
    }
    
    public String getMessage() {
        return message;
    }
    
    public void setMessage(String name) {
        this.message = name;
    }

    public Date getPostingDate() {
        return postingDate;
    }

    public void setPostingDate(Date postingDate) {
        this.postingDate = postingDate;
    }

    public Conversation getConversation() {
        return conversation;
    }

    public void setConversation(Conversation conversation) {
        this.conversation = conversation;
    }
    
    public String toString() {
        return "Message " + getId() + ": " + getMessage() + 
               " posted: " + getPostingDate();
    }
}

File: Conversation.java

import java.util.ArrayList;
import java.util.Collection;

import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToMany;

@Entity
@NamedQueries({
    @NamedQuery(name="findActiveConversations",
                query="SELECT c " +
                      "FROM Conversation c " +
                      "WHERE c.status = 'ACTIVE'"),
    @NamedQuery(name="findLastMessageDate",
                query="SELECT MAX(m.postingDate) " +
                      "FROM Conversation c JOIN c.messages m " +
                      "WHERE c = :conversation")
})

public class Conversation {
    public final static String ACTIVE   = "ACTIVE";
    public final static String INACTIVE = "INACTIVE";
    
    @Id
    private int id;
    private String status;
    
    @OneToMany(mappedBy="conversation")
    private Collection<Message> messages = new ArrayList<Message>();

    public int getId() {
        return id;
    }
    
    public void setId(int empNo) {
        this.id = empNo;
    }


    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

    
    public Collection<Message> getMessages() {
        return messages;
    }
    
    public void addMessage(Message m) {
        if (!getMessages().contains(m)) {
            getMessages().add(m);
            if (m.getConversation() != null) {
                m.getConversation().getMessages().remove(m);
            }
            m.setConversation(this);
        }
    }
    
    public String toString() {
        return "Conversation " + getId() + ": status: " + getStatus();
    }
}

File: Main.java

import java.util.Date;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.FlushModeType;
import javax.persistence.Persistence;
import javax.persistence.Query;

public class Main {
  static EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPAService");

  static EntityManager em = emf.createEntityManager();

  public static void main(String[] a) throws Exception {
    em.getTransaction().begin();

    List<Conversation> active = (List<Conversation>) em.createNamedQuery("findActiveConversations")
        .getResultList();
    Query maxAge = em.createNamedQuery("findLastMessageDate");
    maxAge.setFlushMode(FlushModeType.COMMIT);
    for (Conversation c : active) {
      maxAge.setParameter("conversation", c);
      Date lastMessageDate = (Date) maxAge.getSingleResult();
      if (lastMessageDate.before(new Date())) {
        c.setStatus("INACTIVE");
      }
    }

    em.getTransaction().commit();
    em.close();
    emf.close();

    Helper.checkData();
  }
}

File: Helper.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.Statement;

public class Helper {
  public static void checkData() throws Exception {
    Class.forName("org.hsqldb.jdbcDriver");
    Connection conn = DriverManager.getConnection("jdbc:hsqldb:data/tutorial", "sa", "");
    Statement st = conn.createStatement();

    ResultSet mrs = conn.getMetaData().getTables(null, null, null, new String[] { "TABLE" });
    while (mrs.next()) {
      String tableName = mrs.getString(3);
      System.out.println("\n\n\n\nTable Name: "+ tableName);

      ResultSet rs = st.executeQuery("select * from " + tableName);
      ResultSetMetaData metadata = rs.getMetaData();
      while (rs.next()) {
        System.out.println(" Row:");
        for (int i = 0; i < metadata.getColumnCount(); i++) {
          System.out.println("    Column Name: "+ metadata.getColumnLabel(i + 1)+ ",  ");
          System.out.println("    Column Type: "+ metadata.getColumnTypeName(i + 1)+ ":  ");
          Object value = rs.getObject(i + 1);
          System.out.println("    Column Value: "+value+"\n");
        }
      }
    }
  }
}

File: persistence.xml

<persistence xmlns="http://java.sun.com/xml/ns/persistence"
             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
             xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence" version="1.0">
  <persistence-unit name="JPAService" transaction-type="RESOURCE_LOCAL">
    <properties>
      <property name="hibernate.dialect" value="org.hibernate.dialect.HSQLDialect"/>
      <property name="hibernate.hbm2ddl.auto" value="update"/>
      <property name="hibernate.connection.driver_class" value="org.hsqldb.jdbcDriver"/>
      <property name="hibernate.connection.username" value="sa"/>
      <property name="hibernate.connection.password" value=""/>
      <property name="hibernate.connection.url" value="jdbc:hsqldb:data/tutorial"/>
    </properties>
  </persistence-unit>
</persistence>
  Download:  JPA-EJBQLMaxWithDateType.zip( 5,290 k)








22.25.EJB Query Language
22.25.1.EJB QL Get Two Properties From Entity
22.25.2.EJB QL Get Single result
22.25.3.EJB QL Get Field From Entity
22.25.4.EJB QL Get Entity From Entity
22.25.5.EJB QL Get Distinct Entity
22.25.6.Query an Entity as Query a Table
22.25.7.Return List Of Entities From Query
22.25.8.Query Flush Mode
22.25.9.EJB SQL Count Function
22.25.10.Like statement: Wild Card Escape
22.25.11.Like statement and Wild Card
22.25.12.Where Clause With SubQuery
22.25.13.Use Between To check Salary Range
22.25.14.Two Aggregate Functions
22.25.15.Three Level Field Reference
22.25.16.Using SubQuery in EJB Query Langauge
22.25.17.Size function
22.25.18.Range Check With Comparison Operator
22.25.19.Query Field Of Field
22.25.20.EJB QL Pass Entity As Parameter
22.25.21.Query with Parameters
22.25.22.EJB QL Order By Two Fields
22.25.23.Query One To Many Collection
22.25.24.Order Descending
22.25.25.Use Object Function
22.25.26.Not In function
22.25.27.EJB Query Language: Not Exist
22.25.28.EJB QL Max With Date Type
22.25.29.EJB QL Left Join One To Many Map
22.25.30.EJB QL Join Two Entities
22.25.31.EJB QL Join Three Entities
22.25.32.EJB QL Join One To One Return Two Entities
22.25.33.EJB QL Join One To One
22.25.34.EJB QL Join One To Many Map
22.25.35.EJB QL Join One to Many Left Join Fetch
22.25.36.EJB QL Join Many To Many
22.25.37.EJB QL Join Entity And Its Field
22.25.38.EJB QL is Field empty
22.25.39.EJB QL In With Subquery
22.25.40.EJB QL In Function With One To Many
22.25.41.EJB QL In Function
22.25.42.EJB QL Having Clause
22.25.43.EJB QL Exist And Subquery
22.25.44.EJB QL Create new Object In Select Statement
22.25.45.EJB QL Count Entity
22.25.46.EJB QL Count distinct
22.25.47.EJB QL Concat Function Substring
22.25.48.EJB QL Between With Date Type Value
22.25.49.Aggregate function: AVG