-->
These old forums are deprecated now and set to read-only. We are waiting for you on our new forums!
More modern, Discourse-based and with GitHub/Google/Twitter authentication built-in.

All times are UTC - 5 hours [ DST ]



Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 7 posts ] 
Author Message
 Post subject: query Objects by Date, Day, Month, Year
PostPosted: Mon Jun 06, 2005 7:26 am 
Newbie

Joined: Mon Jun 06, 2005 7:10 am
Posts: 4
I have Situazion very close to the attached mappings from caveatemptor.

I cant figure out how i would query a User by the created attribute.

I.e. i would like to query all Users that were created in the year 2004.
How would this look like using Expression, Restrictions, ..?

thx for any Hints!
--------------------------------------------------------------------------------
Hibernate version: hibernate-3.0 Final

Mapping documents:

Code:
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping SYSTEM
         "http://hibernate.sourceforge.net/hibernate-mapping-2.0.dtd" >
<!--

Mapping file for the User class of CaveatEmptor.

A User is a versioned entity, with some special properties.
One is the username, it is immutable and unique. The
defaultBillingDetails property points to one of the
BillingDetails in the collection of all BillingDetails.

We never load any BillingDetails when a User is retrieved.

@author Christian Bauer <christian@hibernate.org>

-->
<hibernate-mapping package="org.hibernate.auction.model">

<class name="User"
      table="USERS"
      lazy="true">

   <id name="id"
      type="long"
      column="USER_ID"
      unsaved-value="null"
      access="org.hibernate.auction.persistence.DirectSetAccessor">
      <generator class="native"/>
   </id>

   <!-- A versioned entity. -->
   <version name="version"
          column="VERSION"
          access="net.sf.hibernate.property.DirectPropertyAccessor"/>

   <property   name="firstname"
            type="string"
            column="FIRSTNAME"
            length="255"
            not-null="true"/>

   <property   name="lastname"
            type="string"
            column="LASTNAME"
            length="255"
            not-null="true"/>

   <!-- We don't change the username, so map it with update="false".
       This is an immutable property, it is also unique. -->
   <property   name="username"
            type="string"
            column="USERNAME"
            length="16"
            not-null="true"
            unique="true"
            update="false"
            access="org.hibernate.auction.persistence.DirectSetAccessor">
   </property>

   <!-- Password is a keyword in some databases, so we quote it. -->
   <property   name="password"
            type="string"
            column="`PASSWORD`"
            length="12"
            not-null="true"/>

   <property   name="email"
            type="string"
            column="EMAIL"
            length="255"
            not-null="true"/>

   <property   name="ranking"
            type="int"
            column="RANKING"
            not-null="true"/>

   <property   name="admin"
            type="boolean"
            column="IS_ADMIN"
            not-null="true"/>

   <!-- We can't change the creation time, so map it with update="false". -->
   <property   name="created"
            column="CREATED"
            type="java.util.Date"
            update="false"
            not-null="true"
            access="org.hibernate.auction.persistence.DirectSetAccessor"/>

   <!-- The default billing strategy, may be null if no BillingDetails exist. -->
   <many-to-one name="defaultBillingDetails"
             class="BillingDetails"
             column="DEFAULT_BILLING_DETAILS_ID"
             not-null="false"
             outer-join="false"
             foreign-key="FK1_DEFAULT_BILLING_DETAILS_ID"/>

   <!-- Mapping for the component class Address. -->
   <component name="address" class="Address">

      <property   name="street"
               type="string"
               column="STREET"
               length="255"/>

      <property   name="zipcode"
               type="string"
               column="ZIPCODE"
               length="16"/>

      <property   name="city"
               type="string"
               column="CITY"
               length="255"/>
   </component>

   <!-- Mapping for Item association. -->
   <set    name="items"
         cascade="none"
         lazy="true"
         inverse="true"
         access="org.hibernate.auction.persistence.DirectSetAccessor">
      <key>
         <column name="SELLER_ID" not-null="true"/>
      </key>
      <one-to-many class="Item"/>
   </set>

   <!-- Mapping for BillingDetails association. -->
   <set    name="billingDetails"
         cascade="all-delete-orphan"
         lazy="true"
         inverse="true"
         access="org.hibernate.auction.persistence.DirectSetAccessor">
      <key>
         <column name="USER_ID" not-null="true"/>
      </key>
      <one-to-many class="BillingDetails"/>
   </set>

</class>

</hibernate-mapping>


Pojo

Code:
package org.hibernate.auction.model;

import org.hibernate.auction.exceptions.BusinessException;

import java.io.Serializable;
import java.util.*;

/**
* A user of the CaveatEmptor auction application.
* <p>
* This class represents the user entity of CaveatEmptor business.
* The associations are: a <tt>Set</tt> of <tt>Item</tt>s the user
* is selling, a <tt>Set</tt> of <tt>Bid</tt>s the user has made,
* and an <tt>Address</tt> component. Also a <tt>Set</tt> of
* <tt>BuyNow</tt>s, that is, immediate buys made for an item.
* <p>
* The <tt>billingDetails</tt> are used to calculate and bill the
* user for his activities on our system. The <tt>username</tt>
* and <tt>password</tt> are used as login credentials. The
* <tt>ranking</tt> is a number that is increased by each successful
* transaction, but may also be manually increased (or decreased) by
* the system administrators.
*
*
* @author Christian Bauer <christian@hibernate.org>
*/
public class User implements Serializable, Comparable {

   private Long id = null;
   private int version;
   private String firstname;
   private String lastname;
   private String username;
   private String password;
   private String email;
   private int ranking = 0;
   private Date created = new Date();
   private Address address;
   private Set items = new HashSet();
   private Set billingDetails = new HashSet();
   private BillingDetails defaultBillingDetails;
   private boolean admin = false;

   /**
    * No-arg constructor for JavaBean tools.
    */
   User() {}

   /**
    * Full constructor.
    */
   public User(String firstname, String lastname, String username,
            String password, String email,
            Address address, Set items,
            Set billingDetails) {
      this.firstname = firstname;
      this.lastname = lastname;
      this.username = username;
      this.password = password;
      this.email = email;
      this.address = address;
      this.items = items;
      this.billingDetails = billingDetails;
   }

   /**
    * Simple constructor.
    */
   public User(String firstname, String lastname,
               String username, String password, String email) {
      this.firstname = firstname;
      this.lastname = lastname;
      this.username = username;
      this.password = password;
      this.email = email;
   }

   // ********************** Accessor Methods ********************** //

   public Long getId() { return id; }

   public String getFirstname() { return firstname; }
   public void setFirstname(String firstname) { this.firstname = firstname; }

   public String getLastname() { return lastname; }
   public void setLastname(String lastname) { this.lastname = lastname; }

   public String getUsername() { return username; }

   public String getPassword() { return password; }
   public void setPassword(String password) { this.password = password; }

   public String getEmail() { return email; }
   public void setEmail(String email) { this.email = email; }

   public int getRanking() { return ranking; }
   public void setRanking(int ranking) { this.ranking = ranking; }

   public Address getAddress() { return address; }
   public void setAddress(Address address) { this.address = address; }

   public Set getItems() { return items; }
   public void addItem(Item item) {
      if (item == null)
         throw new IllegalArgumentException("Can't add a null Item.");
      this.getItems().add(item);
   }

   public Set getBillingDetails() { return billingDetails; }
   /**
     * Adds a <tt>BillingDetails</tt> to the set.
     * <p>
     * This method checks if there is only one billing method
     * in the set, then makes this the default.
     *
     * @param billingDetails
     */
    public void addBillingDetails(BillingDetails billingDetails) {
       if (billingDetails == null)
          throw new IllegalArgumentException("Can't add a null BillingDetails.");
       this.getBillingDetails().add(billingDetails);

       if (getBillingDetails().size() == 1) {
          setDefaultBillingDetails(billingDetails);
       }
   }
   /**
    * Removes a <tt>BillingDetails</tt> from the set.
    * <p>
    * This method checks if the removed is the default element,
    * and will throw a BusinessException if there is more than one
    * left to chose from. This might actually not be the best way
    * to handle this situation.
    *
    * @param billingDetails
    * @throws BusinessException
    */
   public void removeBillingDetails(BillingDetails billingDetails)
      throws BusinessException {
      if (billingDetails == null)
         throw new IllegalArgumentException("Can't add a null BillingDetails.");

      if (getBillingDetails().size() >= 2) {
         getBillingDetails().remove(billingDetails);
         setDefaultBillingDetails((BillingDetails)getBillingDetails().iterator().next());
      } else {
         throw new BusinessException("Please set new default BillingDetails first");
      }
   }

   public BillingDetails getDefaultBillingDetails() { return defaultBillingDetails; }
   public void setDefaultBillingDetails(BillingDetails defaultBillingDetails) {
      this.defaultBillingDetails = defaultBillingDetails;
   }

   public Date getCreated() { return created; }

   public boolean isAdmin() { return admin; }
   public void setAdmin(boolean admin) { this.admin = admin; }

   // ********************** Common Methods ********************** //

   public boolean equals(Object o) {
      if (this == o) return true;
      if (!(o instanceof User)) return false;
      final User user = (User) o;
      if (!username.equals(user.username)) return false;
      return true;
   }

   public int hashCode() {
      return username.hashCode();
   }

   public String toString() {
      return  "User ('" + getId() + "'), " +
            "Username: '" + getUsername() + "'";
   }

   public int compareTo(Object o) {
      if (o instanceof User)
         return this.getCreated().compareTo( ((User)o).getCreated() );
      return 0;
   }

   // ********************** Business Methods ********************** //

   public void increaseRanking() {
      setRanking(getRanking() + 1);
   }

}


Name and version of the database you are using:
MySQL-4.1


Top
 Profile  
 
 Post subject: Re: query Objects by Date, Day, Month, Year
PostPosted: Mon Jun 06, 2005 8:16 am 
Newbie

Joined: Mon Jun 06, 2005 7:10 am
Posts: 4
odysseus wrote:
I have Situazion very close to the attached mappings from caveatemptor.
...


Sorry, das ich jetzt auf Englisch ins deutsche Forum poste, was für ein Blackout ;)

Auf jeden Fall suche ich eine Möglichkeit ein persistiertes Objekt anhand seines Date Attributs das in der Datenbank als Datetime gemappt ist aus der Datenbank abzufragen.

Danke im voraus.


Top
 Profile  
 
 Post subject:
PostPosted: Tue Jun 07, 2005 4:39 am 
Regular
Regular

Joined: Sun Aug 01, 2004 6:49 pm
Posts: 76
Bitte Kapitel 16 der Anleitung und die entsprechenden APIs lesen:

http://www.hibernate.org/hib_docs/v3/re ... rycriteria
http://www.hibernate.org/hib_docs/v3/api/

Tip: Expression.lt und Expression.gt angucken.


Top
 Profile  
 
 Post subject:
PostPosted: Tue Jun 07, 2005 8:14 am 
Newbie

Joined: Mon Jun 06, 2005 7:10 am
Posts: 4
Danke für den Tipp, die grundsätzliche Funktionsweise von Expression (bzw. Restriction) ist mir klar.

Im Falle eines Datums muss ich dann wohl folgendes machen:

Date datum = ...;
Quote:
Restrictions.like("created", datum);


Die Abfrage gibt mir dann alle Objekte deren Datum exakt (millisekundengenau) übereinstimmt.

Das ist natürlich nicht mein Ziel.

Um nun alle Objekte anhand einer Jahreszahl (2005) zu selektieren, muss ich also 2 Restrictions kombinieren ? (less than 2006 and greater than 2004)

Melde mich wieder wenn ich das getestet habe.
Danke für die Hilfe.


Top
 Profile  
 
 Post subject:
PostPosted: Tue Jun 07, 2005 8:27 am 
Regular
Regular

Joined: Sun Aug 01, 2004 6:49 pm
Posts: 76
Beispiel:

Code:
Criteria criteria = hibernateSession.createCriteria(Foo.class)
.addOrder(Order.asc("begin"));

criteria.add(Expression.ge("begin", from));
criteria.add(Expression.lt("begin", to));

return criteria.list();



from = Datum
to = Datum

HTH ;-)
Thomas


Top
 Profile  
 
 Post subject:
PostPosted: Tue Jun 07, 2005 4:47 pm 
Newbie

Joined: Mon Jun 06, 2005 7:10 am
Posts: 4
Danke für die Hilfe, hat alles geklappt.

mein Codebeispiel sieht so aus:

Code:
Calendar lCalendar = Calendar.getInstance();
lCalendar.set(2000, 0, 1);//Calendar.YEAR, Calendar.MONTH, Calendar.DATE
Date lDate = lCalendar.getTime();

lWettbewerbeCollection = lSession.createCriteria(Wettbewerb.class).add(Restrictions.ge("erstellungsdatum",lDate)).list();


Top
 Profile  
 
 Post subject:
PostPosted: Tue Jun 07, 2005 4:55 pm 
Hibernate Team
Hibernate Team

Joined: Mon Aug 25, 2003 9:11 pm
Posts: 4592
Location: Switzerland
In den meisten DBMS funktioniert uebrigens der BETWEEN operator auch mit Zeit Typen.


Top
 Profile  
 
Display posts from previous:  Sort by  
Forum locked This topic is locked, you cannot edit posts or make further replies.  [ 7 posts ] 

All times are UTC - 5 hours [ DST ]


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum

Search for:
© Copyright 2014, Red Hat Inc. All rights reserved. JBoss and Hibernate are registered trademarks and servicemarks of Red Hat, Inc.