Get user data between two date in Hibernate Java - java

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 );

Related

java.lang.Object; cannot be cast to shoppingbasket.Product

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 can't insert foreign key

I have a node db with five pieces of data:
id(int, PK)
question(varchar)
result(varchar)
left_id(int, FK)
right_id(int, FK)
and two foreign keys in the same table
left_id -> id
right_id -> id
here is my bean
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
#Column(name="id")
#NotNull
private int id;
#Column (name = "question")
private String question;
#Column ( name = "result")
private String result;
#OneToOne(fetch= FetchType.LAZY)
#JoinColumn(name="left_id", referencedColumnName="id", insertable=true, updatable=true)
private Nodes left;
#OneToOne(fetch= FetchType.LAZY)
#JoinColumn(name="right_id", referencedColumnName="id", table="node", insertable=true, updatable=true)
private Nodes right;
and here is my dao
public void insert_question(String question, int left) throws HibernateException
{
try
{
Session session = getSession();
Transaction tx = session.beginTransaction();
Nodes node = new Nodes();
Nodes leftNode = new Nodes();
//insert question
node.setQuestion(question);
// insert left_id with fk
leftNode.setId_node(left);
node.setLeftNodes(leftNode);
session.saveOrUpdate(node);
tx.commit();
session.close();
}
catch (HibernateException e)
{
e.printStackTrace();
}
}
I have a same insert method for result but without foreign key.
My new question and new result are insert my db but not my left_id.
In Eclipse, hibernate tell me
Infos: Hibernate: select nodes_.id, nodes_.question as question0_, nodes_.result as result0_ from node nodes_ where nodes_.id=?
Infos: Hibernate: insert into node (question, result, id) values (?, ?, ?)
Infos: Hibernate: insert into node (question, result, id) values (?, ?, ?)
When hibernate insert a new data, why there are no left/right_id ?
thanks
EDIT:
I changed my hbm. Before it was like that
<hibernate-mapping>
<class name="com.beans.Nodes" table="node">
<id name="id" type="int" access="field">
<column name="id" />
<generator class="assigned" />
</id>
<property name="question" type="java.lang.String">
<column name="question" />
</property>
<property name="result" type="java.lang.String">
<column name="result" />
</property>
<one-to-one name="left" class="com.beans.Nodes" access="field"></one-to-one>
<one-to-one name="right" class="com.beans.Nodes" access="field"></one-to-one>
</class>
</hibernate-mapping>
and now it's like that
<hibernate-mapping>
<class name="com.beans.Nodes" table="node">
<id name="id" type="int" access="field">
<column name="id" />
<generator class="assigned" />
</id>
<property name="question" type="java.lang.String">
<column name="question" not-null="false"/>
</property>
<property name="result" type="java.lang.String">
<column name="result" not-null="false"/>
</property>
<many-to-one name="Left"
column="left_id"
unique="true"
not-null="false"
/>
<many-to-one name="Right"
column="right_id"
unique="true"
not-null="false"
/>
</class>
</hibernate-mapping>
and it's works !

Hibernate Many To Many XML Mapping Join Table with Extra Column

I'm having a hard time to figure this thing out. I have managed to create this type of mapping using annotations, but XML configuration is giving me headache for hours. These are my POJOs (getters ans setters are omitted):
public class Stock implements Serializable {
private static final long serialVersionUID = 8724254922362918916L;
private int stockId;
private String stockCode;
private String stockName;
private Set<StockCategory> stockCategories;
}
public class Category implements Serializable {
private static final long serialVersionUID = -3719693878172387644L;
private int categoryId;
private String name;
private String desc;
private Set<StockCategory> stockCategories;
}
public final class StockCategoryId implements Serializable {
private static final long serialVersionUID = -6894097209574496516L;
private int stockId;
private int categoryId;
}
public class StockCategory implements Serializable {
private static final long serialVersionUID = 691323506089277225L;
private StockCategoryId stockCategoryId;
private Stock stock;
private Category category;
private Date createdDate;
private String createdBy;
}
And those are hibernate mapping files:
<class name="com.rmilovic.hibernate.examples.models.Stock" table="STOCK">
<id name="stockId" column="STOCK_ID" type="int">
<generator class="identity" />
</id>
<property name="stockCode" type="string">
<column name="STOCK_CODE" length="10" not-null="true" unique="true" />
</property>
<property name="stockName" type="string">
<column name="STOCK_NAME" length="10" not-null="true" unique="true" />
</property>
<set name="stockCategories" table="STOCK_CATEGORY" inverse="true"
lazy="true" fetch="select" cascade="all">
<key column="STOCK_ID" not-null="true" />
<one-to-many class="com.rmilovic.hibernate.examples.models.StockCategory" />
</set>
</class>
<class name="com.rmilovic.hibernate.examples.models.Category" table="CATEGORY">
<id name="categoryId" column="CATEGORY_ID" type="int">
<generator class="identity" />
</id>
<property name="name" type="string">
<column name="NAME" not-null="true" length="10" unique="true" />
</property>
<property name="desc" type="string">
<column name="DESC" not-null="true" />
</property>
<set name="stockCategories" table="STOCK_CATEGORY" lazy="true" inverse="true"
fetch="select" cascade="all">
<key column="CATEGORY_ID" not-null="true" />
<one-to-many class="com.rmilovic.hibernate.examples.models.StockCategory" />
</set>
</class>
<class name="com.rmilovic.hibernate.examples.models.StockCategory" table="STOCK_CATEGORY">
<composite-id name="stockCategoryId"
class="com.rmilovic.hibernate.examples.models.StockCategoryId">
<key-property name="stockId" type="int" column="STOCK_ID" />
<key-property name="categoryId" type="int" column="CATEGORY_ID" />
</composite-id>
<property name="createdDate" type="date">
<column name="CREATED_DATE" not-null="true" length="10" unique="true" />
</property>
<property name="createdBy" type="string">
<column name="CREATED_BY" not-null="true" length="10" unique="true" />
</property>
<many-to-one name="stock" column="STOCK_ID"
class="com.rmilovic.hibernate.examples.models.Stock"
insert="false" update="false" />
<many-to-one name="category" column="CATEGORY_ID"
class="com.rmilovic.hibernate.examples.models.Category"
insert="false" update="false" />
</class>
Schema seems to be good but I'm getting:
Exception in thread "main" org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing: com.rmilovic.hibernate.examples.models.Category
when I'm trying to save data.
This is the code which saves data:
final Session session = HibernateUtilities.openSession();
session.beginTransaction();
final Stock stock = new Stock("BLA", "Test");
final Category category = new Category("consumer", "consumer company");
final StockCategory stockCategory = new StockCategory(new Date(), "me");
stockCategory.setCategory(category);
stockCategory.setStock(stock);
stock.getStockCategories().add(stockCategory);
category.getStockCategories().add(stockCategory);
session.save(stock);
session.getTransaction().commit();
HibernateUtilities.closeSession();

HQL returns no results but generated SQL works perfectly on SQL Developer

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;
}
...
}

org.hibernate.PropertyValueException: not-null property references a null or transient value:

I want to save an object to my sub-class ArticleZoning whose super class Zoning contain a List of Class zoneData which also contain a class ZoneCoordinate. When I save the object of my sub-class ArticleZoning it gives an exception.
org.hibernate.PropertyValueException: not-null property references a null or transient value: com.qait.cdl.eon.commons.domain.ZoneData._com.qait.cdl.eon.commons.domain.Zonning.zoneDatasBackref
at org.hibernate.engine.Nullability.checkNullability(Nullability.java:101)
at org.hibernate.event.def.AbstractSaveEventListener.performSaveOrReplicate(AbstractSaveEventListener.java:313)
at org.hibernate.event.def.AbstractSaveEventListener.performSave(AbstractSaveEventListener.java:204)
at org.hibernate.event.def.AbstractSaveEventListener.saveWithGeneratedId(AbstractSaveEventListener.java:130)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.saveWithGeneratedOrRequestedId(DefaultSaveOrUpdateEventListener.java:210).....
Here is *Zonning hbm*Mapping file:-
<class name="Zonning" table="zoning">
<id name="id" column="id" type="long">
<generator class="native" />
</id>
<list name="zoneDatas" lazy="false" cascade="all-delete-orphan" >
<key column="zoning_id" not-null="true"/>
<list-index column="idx" base="1" />
<one-to-many class="com.qait.cdl.eon.commons.domain.ZoneData" />
</list>
<many-to-one class="com.qait.cdl.eon.commons.domain.MagazineIssue" unique="true" column="issue_id" name="issue"/>
<property name="pageNumber" column="article_on_pageNumber" type="string" not-null="true" />
<joined-subclass name="ArticleZoning" extends="Zonning" table="article_zoning">
<key column="article_id"/>
<property name="articleTitle" column="article_title" type="string" not-null="true" />
<property name="articleOrder" column="article_order" type="int" not-null="true" />
<property name="articleFileId" column="article_file_id" type="string" not-null="true" />
<property name="articleType" column="article_type">
<type name="org.hibernate.type.EnumType">
<param name="type">12</param>
<param name="enumClass">com.qait.cdl.eon.common.constants.ArticleType</param>
</type>
</property>
<property name="articleSubTitle" column="article_sub_title" type="string" not-null="true" />
<property name="articleGenre" column="article_genre">
<type name="org.hibernate.type.EnumType">
<param name="type">12</param>
<param name="enumClass">com.qait.cdl.eon.common.constants.Genre</param>
</type>
</property>
</joined-subclass>
<joined-subclass name="AdvertisementZoning" extends="Zonning" table="advertisement_zoning">
<key column="advertisement_id" />
<property name="adVendor" column="ad_vendor" type="string" not-null="true" />
<property name="vendorUrl" column="vendor_url" type="string" not-null="true" />
<property name="adProduct" column="ad_product" type="string" not-null="true" />
<list name="adKeywords" table="ad_keywords" lazy="false" cascade="all">
<key column="ad_keywords_id" />
<list-index base="0" column="idx"/>
<element column="keywords" type="string" />
</list>
</joined-subclass>
</class>
Here is ZoneData Hbm
<id name="id" column="id" type="long">
<generator class="native" />
</id>
<property name = "zoneOrder" column = "zone_order" type = "int" not-null="true"/>
<property name = "zoneFileId" column = "zone_file_id" type = "string" not-null="true"/>
<property name = "zoneShape" column = "zone_shape" type = "string" not-null="true" access="field"></property>
<many-to-one name="coordinates" column="coordinates_id" lazy="false" class="com.qait.cdl.eon.commons.domain.ZoneCoordinates"
unique="true" not-null="true" cascade="all-delete-orphan"/>
</class>
Here is ZoneCoordinate hbm
<class name="ZoneCoordinates" table="zone_coordinates">
<id name="id" column="id" type="long">
<generator class="native" />
</id>
<property name = "leftTopX" column = "left_top_x" type = "float" not-null="true" />
<property name = "leftTopY" column = "left_top_y" type = "float" not-null="true" />
<property name = "rightBottomX" column = "right_bottom_x" type = "float" not-null="true" />
<property name = "rightBottomY" column = "right_bottom_y" type = "float" not-null="true" />
</class>
Here is Zoning pojo
class Zoning{
private List<ZoneData> zoneDatas =new ArrayList<>();
private MagazineIssue issue;
private String pageNumber;
//getter and setter
}
Here is ZoneData POJO
class ZoneData{
private int zoneOrder;
private String zoneFileId ;
private ZoneCoordinates coordinates;
private final String zoneShape = "RECT";
//getter and setter
}
Here is ArticleZoning POJO
class ArticleZoning extends Zoning{
private String articleTitle;
private String articleOrder;
private ArticleType articleType;
private String articleFileId;
private String articleSubTitle;
private Genre articleGenre;
//getter and setter
}
Here is ZoneCoordinate POJO
class ZoneCoordinate{
private float leftTopX;
private float leftTopY;
private float rightBottomX;
private float rightBottomY;
//getter and setter
}
First, ArticleZoning POJO has articleOrder as String type. Your Zonning.hbm says articleOrder is of int type.
Secondly, as zoning table is unable to save, hence its foreign key is null.

Categories

Resources