简体   繁体   中英

How could i create such query in hibernate

Here is my query:

SELECT auc_id,name,MAX(amount) FROM `auc`
INNER JOIN bid
where bid.auc_id = auc.id
GROUP BY (auc_id)

Mappig:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="DAO.Bid" table="bid" lazy="false">

   <id column="id" name="id" type="java.lang.Integer"> 
   <generator class="identity"/>
  </id>
  <property column="amount" name="amount" type="java.lang.Integer" />
  <property column="type" name="type" type="java.lang.Integer" />
  <many-to-one name="owner_id" column="owner_id" class="DAO.Users" not-null="false" cascade="all"/>
  <many-to-one name="auc_id" column="auc_id" class="DAO.Auction" not-null="false" cascade="all"/>
  </class>
</hibernate-mapping>

Auction class mapping:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
  <class name="DAO.Auction" table="auc" lazy="false">

  <id column="Id" name="id" type="java.lang.Integer"> 
   <generator class="identity"/>
  </id>
  <property column="name" name="name" type="java.lang.String" />
  </class>
</hibernate-mapping>

I need to create the same query with hibernate.I need to get name form auc table, fields auction_id and max value of field amount from each auction.

Query as it is now : SELECT b FROM DAO.Bid b INNER JOIN b.auc_id But it throws error thet first colomn of Auc table is unmapped in class Bid.Its true because this field is inside class Auction.But what can i do wit hit?

HQL is NOT SQL. Joins in HQL largely leverage on your relationships to be properly mapped, instead of doing joining explicitly by column names every time.

Assume you have your models like this:

class Auction {
    Integer id;
    String name;
}

class Bid {
    Integer id;
    Auction auction;
    BigDecimal amount;
}

it should looks like

select auction.id, auction.name, max(amount) -- you may need to use max(auction.id), 
                                             -- max(auction.name) for some DB
from Bid
group by auction.id

(the auction.id and auction.name is an implicit inner join which means bid.auction.id )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM