0

I have many years experience with SQL. I am new to Hibernate, I have worked out the basics of Hibernate. The logic below is what is required; however I changed the table names to make sure its not revealing company details. Also please note the SQL must run as one SQL statement - other applications could update the tables at the same time this one is running. The table design can't change as other applications are already in production using them.

Could someone please demonstrate how to do the update below in Hibernate? Is createNativeQuery an option??

    update
    PERSON P
    set
    P.STATUS = 'Happy'
    where
    P.PK_ID = :person_id
    and
    (
    select count(1)
    from WORK_JOBS WJ
    where WJ.RESOLVED_STATUS is null
    ) = 0
    and
    (
    select count(1)
    from EXPENSES EX
    where EX.COST > :max_exp_cost
    ) = 0
    ;

The simplified table definitions are below.

create table PERSON
(
PK_ID         NUMBER NOT NULL,
LAST_NAME     VARCHAR2(100),
FIRST_NAME    VARCHAR2(100),
PRIMARY KEY   PK_ID
)
;


create table WORK_JOBS
(
PK_ID             NUMBER NOT NULL,
SUMMARY           VARCHAR2(100),
DESCRIPTION       VARCHAR2(1000),
RESOLVED_STATUS   VARCHAR2(50),
PRIMARY KEY       PK_ID
)
;

create table EXPENSES
(
PK_ID             NUMBER NOT NULL,
SUMMARY           VARCHAR2(100),
DESCRIPTION       VARCHAR2(1000),
COST              DECIMAL(10,2),
PRIMARY KEY       PK_ID
)
;
4

2 回答 2

1

您必须使用标准选择记录。

criteria=getCurrentSession().createCriteria(PERSON.class, "person");

DetachedCriteria dCriteria=DetachedCriteria.forClass(WORK_JOBS.class, "workjobs");

DetachedCriteria dCriteria=DetachedCriteria.forClass(EXPENSES.class, "workjobs");

criteria.add(Subqueries.Exists()); 

然后你必须为每个 Person 对象设置 P.STATUS = 'Happy' 并在数据库中更新它。

于 2013-09-23T11:44:48.627 回答
0

您可以使用 HQL 更新查询来实现此目的:

   String updateQuery = "update Person p set p.status=:pstatus "
                + "where p.id=:pid and (select count(*) from WorkJobs wj "
                + "where wj.status=:wjstatus)=:wjcount and (select count(*) "
                + "from Expences e where e.cost > :ecost)=:ecount";

        BigDecimal maxCost = new BigDecimal(20.0);
        Long pid = new Long(1l);

        Query query = session.createQuery(updateQuery);

        query.setParameter("pstatus", "Happy");
        query.setParameter("pid", pid);
        query.setParameter("wjstatus", null);
        query.setParameter("wjcount", 0l);
        query.setParameter("ecost", maxCost);
        query.setParameter("ecount", 0l);

        int rowCount = query.executeUpdate();
于 2013-09-23T12:15:51.353 回答