I have a class auction like
public class Auction extends LightEntity implements IsSerializable
{
private long AuctionId;
private Date StartTime;
private Date EndTime;
}
i need to perform write an hql using restriction which chooses all auction whose end time has not yet completed.
my xml mapping file for the auction class is
<hibernate-mapping>
<class name="com.BiddingSystem.Models.Auction" table="AUCTION">
<id name="AuctionId" type="long">
<column name="AUCTIONID" />
<generator class="native" />
</id>
<property name="StartTime" type="java.util.Date">
<column name="STARTTIME" />
</property>
<property name="EndTime" type="java.util.Date">
<column name="ENDTIME" />
</property>
..
.
.
.
>
First of all, you should definitely respect the Java naming conventions : variables and fields start with a lower-case letter in Java (auctionId, startTime, endTime).
Now your question :
either you compute the current time, and pass it as a parameter to your query :
Date now = new Date();
Query q = session.createQuery("select a from Auction a where a.endTime > :now");
q.setTimeStamp("now", now);
return q.list();
or you use expressions supported by HQL :
Query q = session.createQuery("select a from Auction a where a.endTime > current_timestamp()");
return q.list();
Related
i have an hibernate entity called user.I want to get the list of users who are between two dates a date interval. Example, I have a date D1 and I want to know the people hired between my hiDate and my depDate.
Here is the mapping of the hibernate file of my user entity
<class name="com.bam.model.User" table="USER">
<composite-id class="com.bam.model.UserId" name="id">
<key-property name="idUser" type="java.lang.String">
<column name="ID_USER" not-null="true" precision="0" scale="30" sql-type="varchar"/>
</key-property>
<key-property name="idCompany" type="java.lang.String">
<column name="ID_COMPANY" not-null="true" precision="0" scale="30" sql-type="varchar"/>
</key-property>
</composite-id>
<property name="gender" type="java.lang.String">
<column name="GENDER" not-null="false" precision="0" scale="4" sql-type="varchar"/>
</property>
<property name="firstname" type="java.lang.String">
<column name="FIRSTNAME" not-null="false" precision="0" scale="100" sql-type="varchar"/>
</property>
<property name="lastname" type="java.lang.String">
<column name="LASTNAME" not-null="false" precision="0" scale="100" sql-type="varchar"/>
</property>
</class>
Here is also the class of my user entity.
#XmlRootElement(name = "user")
public class User implements Serializable {
#XmlElement(name = "id")
private UserId id;
#XmlElement(name = "gender")
private String gender;
#XmlElement(name = "firstName")
private String firstname;
#XmlElement(name = "lastName")
private String lastname;
}
The query that I will write with the hql language is this one :
Query query = session.createQuery("SELECT * FROM USER us oh WHERE DATE_FORMAT(us.HI_DATE,'%dd-%mm-%YYYY') <= :from_date <= DATE_FORMAT(us.DEP_DATE'%dd-%mm-%YYYY') ");
query.setParameter( "from_date ", from_date );
but it doesn't work, any idea ?
you can try this.
Do you need to format the dates?
Query query = session.createQuery("FROM USER us WHERE :from_date between us.hiDate and us.depDate");
query.setParameter( "from_date ", from_date );
I am trying to retrieve a list of products with they're associated offers. After iterating through the result of the query I want to be able to use the getters/setters from the products class but I know it's not working because the query is not returning an instance of Product.
function to grab the products:
public List<Product> getProducts() {
factory = (new Configuration()).configure().buildSessionFactory();
Session session = factory.getCurrentSession();
session.beginTransaction();
List<Product> products = new ArrayList<Product>();
Query query = session.createQuery("from Product p INNER JOIN p.offers");
//The castList is declared and explained at the bottom of listing
List<Product> list = query.list();
Iterator<Product> iter = list.iterator();
while (iter.hasNext()) {
Product product = iter.next();
System.out.println(product);
}
}
Hibernate mapping for Offer:
<hibernate-mapping>
<class name="shoppingbasket.Offer" table="offers">
<id name="offerID" type="integer" access="field">
<column name="OfferID" />
<generator class="assigned" />
</id>
<property name="offerDescription" type="java.lang.String" access="field">
<column name="OfferDescription" length="60" not-null="true"/>
</property>
<property name="shortDescription" type="java.lang.String" access="field">
<column name="ShortDescription" length="10" not-null="false"/>
</property>
<property name="TFTPOTGroup" type="java.lang.Integer" access="field">
<column name="TFTPOTGroup" length="4" not-null="false" default="null"/>
</property>
<property name="discountPercentage" type="java.lang.Double" access="field">
<column name="DiscountPercentage" not-null="false" default="null"/>
</property>
</class>
Hibernate mapping for Product:
<hibernate-mapping>
<class name="shoppingbasket.Product" table="products">
<id name="productID" type="integer" access="field">
<column name="ProductID" />
<generator class="assigned" />
</id>
<property name="offerID" type="java.lang.Integer" access="field">
<column name="OfferID" />
</property>
<property name="productName" type="java.lang.String" access="field">
<column name="ProductName" length="40" not-null="true"/>
</property>
<property name="unitPrice" type="java.math.BigDecimal" access="field">
<column name="UnitPrice"/>
</property>
<one-to-one name="offers" class="shoppingbasket.Offer" />
</class>
Product class:
public class Product implements java.io.Serializable {
private Integer productID;
private Integer offerID;
private String productName;
private BigDecimal unitPrice;
private Offer offer;
public Integer getProductID() {
return productID;
}
public void setProductID(Integer productID) {
this.productID = productID;
}
public Integer getOfferID() {
return this.offerID;
}
public void setOfferID(Integer offerID) {
this.offerID = offerID;
}
public Offer getOffers() {
return offer;
}
public void setOffers(Offer offer) {
this.offer = offer;
}
//more getters/setters
}
Offer class:
public class Offer
{
private Integer offerID;
private String offerDescription;
private String shortDescription;
private Integer TFTPOTGroup;
private Double discountPercentage;
public Integer getOfferID() {
return offerID;
}
public void setOfferID(Integer offerID) {
this.offerID = offerID;
}
//more getters/setters
}
Any help would be hugely appreciated
#Potential Unnecessary Projections Data:
Since you're not specifying SELECT clause in the query and putting explicit joins, hibernate will return 2 objects per row (Product, Offers), wherein Product object might already be populated with the Offer data due to underlying mapping associations.
Try adding select clause to the query and see if it casts correctly
Add SELECT p FROM ... to the query
I am trying to save to two tables in SQL server using Hibernate:
ORDER and ORDER_ITEM
I get an error:
Attribute "type" must be declared for element type "column".
Initial SessionFactory creation failed.org.hibernate.InvalidMappingException: Unable to read XML.
This produces a NullPointerException
If I understand correctly, this means that when I try to save to the order_item table, the getter for the foreign key is empty, but how would I set it if is designed to 'Autoincrement', I thought that hibernate would handle this in it's transaction.
Below are my POJO's and Hibernate mappings. I have omitted the getters and setters from this copy/paste, but they are present in my actual code
I am also successful in saving just to the ORDER table if I remove the set
Order.java:
public class Order {
public Order(){
super();
}
private int orderId;
private Set<LineItem> items;
private String strPhone;
private String strEmail;
private String strFirstName;
private String strLastName;
private String strParentFirstName;
private String strParentLastName;
private String strOrganizationName;
private String strOrganizationType;
private String strComment;
}
order.hbm.xml:
<hibernate-mapping>
<class name="dbobjects.Order" table="orders">
<id name="orderId" type="integer" column="order_id">
<generator class="increment"/>
</id>
<property name="strPhone" type="string" column="phone_number"/>
<property name="strFirstName" type="string" column="first_name"/>
<property name="strLastName" type="string" column="last_name"/>
<property name="strParentFirstName" type="string" column="parent_first_name"/>
<property name="strParentLastName" type="string" column="parent_last_name"/>
<property name="strOrganizationName" type="string" column="organization_name"/>
<property name="strOrganizationType" type="string" column="organization_type"/>
<property name="strComment" type="string" column="comments"/>
<set name="items" table="order_item" fetch="select" cascade="all">
<key>
<column name="orderId" type="java.lang.Integer"/>
</key>
<one-to-many class="dbobjects.LineItem"/>
</set>
</class>
LineItem.java:
public class LineItem {
public LineItem(){
super();
}
private int orderItemId;//this will be the primary key
private int orderId;//this is the foreign key to the order
private String age;
private String gender;
private String type;
private String itemSize;
private int itemQuantity;
}
lineItem.hbm.xml:
<id column="order_item_id" name="orderItemId" type="integer">
<generator class="increment"/>
</id>
<property column="age" name="age" type="string"/>
<property column="gender" name="gender" type="string"/>
<property column="quantity" name="itemQuantity" type="integer"/>
<property column="size" name="itemSize" type="string"/>
<property column="clothing_type" name="clothingType" type="string"/>
<many-to-one name="orderId" class="dbobjects.Order" fetch="select" column="order_id" type="java.lang.Integer"/>
This is where the error is thrown when I Instanciate the session:
**session = HibernateUtil.getSessionFactory().openSession();**←
try{
session.beginTransaction();
session.save(order);
session.getTransaction().commit();
So the question is: How do I handle this situation with 'autoincrement' primary key that is not accessible to another table as a foreign key
So, There were a few problems:
In order to submit a 'child' to the database, I needed to show who is the parent.
This means that my LineItem Class needed a
Order order;
property instead of a simple
private String orderID;
this was accomplished after the Order object was ready to be submitted to the DB but before the actual call:
for (LineItem item : order.getItems()) {
item.setOrder(order);
}
I also changed my DTD's from !DOCTYPE hibernate-configuration SYSTEM classpath://org/hibernate/hibernate-mapping-3.0.dtd"
to
!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"
Just add "type" attribute like this :
<column name="orderId" type="java.lang.Integer"/>
Try to replace :
<many-to-one name="orderId" column="order_id" class="dbobjects.Order" cascade="all">
<column name="orderId" type="java.lang.Integer"/>
</many-to-one>
by
<many-to-one name="orderId" column="order_id" class="dbobjects.Order" cascade="all"/>
So I have this query
private static final String GET_LOCK_HISTORY1 = "select lh from UserLockHistoryEntity lh ";
which is executed using this code
List<UserLockHistoryEntity> result = getQuery(GET_LOCK_HISTORY1).list();
This returns an empty array. On the console I get the generated SQL which is
select
userlockhi0_.USER_LOCK_HISTORY_ID as USER_LOC1_15_,
userlockhi0_.LOCK_TYPE as LOCK_TYP2_15_,
userlockhi0_.TIMESTAMP as TIMESTAM3_15_,
userlockhi0_.LOCKED_USER_ID as LOCKED_U4_15_,
userlockhi0_.COMPANY_ID as COMPANY_5_15_,
userlockhi0_.PARTNER_ID as PARTNER_6_15_,
userlockhi0_.IP_ORIGIN as IP_ORIGI7_15_,
userlockhi0_.LOCKED_BY_USER as LOCKED_B8_15_,
userlockhi0_.LOCKED_BY_TYPE as LOCKED_B9_15_,
userlockhi0_.LOCK_REASON as LOCK_RE10_15_
from
ONCPRTDEV.USER_LOCK_HISTORY userlockhi0_
and I paste it on SQL developer which returns me 8 rows (all table records)
Bellow it's my mapping file
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated Jan 22, 2014 3:07:58 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="pt.vdf.onc.core.business.entity.user.UserLockHistoryEntity" table="USER_LOCK_HISTORY">
<id name="id" type="java.lang.Long">
<column name="USER_LOCK_HISTORY_ID" />
<generator class="assigned" />
</id>
<property name="lockType">
<column name="LOCK_TYPE" />
<type name="org.hibernate.type.EnumType">
<param name="enumClass">pt.vdf.onc.core.common.type.user.UserLockType</param>
</type>
</property>
<property name="timestamp" type="java.lang.String">
<column name="TIMESTAMP" />
</property>
<property name="userId" type="java.lang.Long">
<column name="LOCKED_USER_ID" />
</property>
<property name="companyId" type="java.lang.Long">
<column name="COMPANY_ID" />
</property>
<property name="partnerId" type="java.lang.Long">
<column name="PARTNER_ID" />
</property>
<property name="ipOrigin" type="java.lang.String">
<column name="IP_ORIGIN" />
</property>
<property name="lockedByUser" type="java.lang.Long">
<column name="LOCKED_BY_USER" />
</property>
<property name="lockedByType">
<column name="LOCKED_BY_TYPE" />
<type name="org.hibernate.type.EnumType">
<param name="enumClass">pt.vdf.onc.core.common.type.user.UserLockByType</param>
</type>
</property>
<property name="lockedReason">
<column name="LOCK_REASON" />
<type name="org.hibernate.type.EnumType">
<param name="enumClass">pt.vdf.onc.core.common.type.user.UserLockReason</param>
</type>
</property>
</class>
</hibernate-mapping>
and entity
public class UserLockHistoryEntity implements java.io.Serializable {
private Long id;
private UserLockType lockType;
private String timestamp;
private Long userId;
private Long companyId;
private Long partnerId;
private String ipOrigin;
private Long lockedByUser;
private UserLockByType lockedByType;
private UserLockReason lockedReason;
//getters and setters here (removed them for simplicity)
}
Table definition:
USER_LOCK_HISTORY_ID NUMBER(38,0)
LOCK_TYPE NUMBER(38,0)
TIMESTAMP DATE
LOCKED_USER_ID NUMBER(38,0)
COMPANY_ID NUMBER(38,0)
PARTNER_ID NUMBER(38,0)
IP_ORIGIN VARCHAR2(30 BYTE)
LOCKED_BY_USER VARCHAR2(50 BYTE)
LOCK_REASON NUMBER(38,0)
LOCKED_BY_TYPE NUMBER
And some rows as an example:
809 0 14.01.22 5003953 1003739 0 127.0.0.1 5003953 2 0
810 0 14.01.22 5003953 1003739 0 127.0.0.1 5003953 2 0
811 0 14.01.22 2054497 621936 0 127.0.0.1 2054497 2 0
Why am I getting an empty result List when the query works perfectly on SQL Developer? Thanks for your help
For
List<UserLockHistoryEntity> result = getQuery(GET_LOCK_HISTORY1).list();
The valid query is
select lh from UserLockHistoryEntity lh
For query
select lh.id from UserLockHistoryEntity lh
The valid result is:
List<Long> result = getQuery(GET_LOCK_HISTORY1).list();
How is your pojo annotated? Is the id field annotated as an id?
public class UserLockHistoryEntity implements java.io.Serializable {
private Long id;
...
#Id
#Column(name = "USER_LOCK_HISTORY_ID", unique = true, nullable = false)
public Long getId() {
return this.id;
}
...
}
I have a very specific scenario as follow.
public class Person
{
Long id;
Collection<PersonRelation> personRelationCollection = new LinkedHashSet<PersonRelation>();
/**
has respective getter and setter
**/
}
public class PersonRelation
{
Long id;
Long parentPersonId; // here I don't want parentPersonId of type Person
Long childPersonId; // here also I don't want childPersonId of type Person
String relationType;
/**
has respective getter setter
**/
}
In my mapping files I have following
<class name="Person" table="PERSON">
<id name="id" column="IDENTIFIER">
<generator class="native"/>
</id>
<set
name="personRelationCollection"
table="PERSON_RELATION"
cascade="all"
>
<key column="PARENT_PERSON_ID"/>
<one-to-many class="PersonRelation"/>
</set>
</class>
and
<class name="PersonRelation" table="PERSON_RELATION">
<id name="id" column="IDENTIFIER">
<generator class="native"/>
</id>
<!-- following many-to-one mapping doesn't work-->
<!-- I need help here to satisfy my requirement -->
<many-to-one
name="parentPersonId"
column="PARENT_PERSON_ID"
class="Person"
not-null="true"/>
<Property name="childPersonId" column="CHILD_PERSON_ID"/>
<property name="relationType" column="RELATION_TYPE"/>
</class>
In this example, as in PersonRelation class, attribute parentPersonId is Long and not type of Person, I'm getting
org.hibernate.MappingException: Association references unmapped class PersonRelation
$
Please help.
Forget about references by id. In Hibernate you work with objects, not tables.
I guess your code could be written like this:
#Entity
#Table(name="your_table")
public class Item{
private Long id;
private Item parentItem;
private List<Item> children;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public Long getId(){
}
#ManyToOne()//Your options
public Item getParentItem(){
}
#OneToMane(mappedBy="parentItem")
public List<Item> getChildren(){
}
//Setters omitted
}
finally i found answer my own. Very small thing we have to do as follow.
<class name="PersonRelation" table="PERSON_RELATION">
<id name="id" column="IDENTIFIER">
<generator class="native"/>
</id>
<!-- here remove many-to-one mapping ---- it's not needed-->
<!-- treet participantPersonId as a simple property and everything will work -->
<Property name="parentPersonId" column="PARENT_PERSON_ID" type="Long"/>
<Property name="childPersonId" column="CHILD_PERSON_ID"/>
<property name="relationType" column="RELATION_TYPE"/>
</class>
This works perfectly fine. :)
Here, when you insert Person object, then it will not inset PersonRelation object too. You have to explicitly insert PersonRelation object. Perhaps, when we retrieve Person object, then it will gives you collection of PersonRelation. Here no need to retrieve PersonRelation collection explicitly.