简体   繁体   中英

Hibernate to execute multiple native sql statements

How can I execute Multiple SQL statements in a single sql query using hibernate native sql.

String sql = "SELECT * FROM user; SELECT * FROM product;";
UserVO valueObject = new UserVO();
databaseObject.select(sql, valueObject);

Database Object

public List select(String sql, Object valueObject) throws Exception {
    Session session = Entitlement.getSessionFactory().openSession();
    session.beginTransaction();
    List list = session.createSQLQuery(sql).setProperties(valueObject).list();
    session.close();
    return list;
}

Use union to form a query which has same returning data (Select EMPLOYEEID as id, EMPLOYEE_NAME as name, "EMPOYEE" as type) UNION (SELECT PRODUCTID as id, Product_NAME as name, "PRODUCT" as type)

form an Entity to hold it

class EntityDetail {
    String id;
    String name;
    String type;
}

I have added an additional column value type to simply identify from which table row is coming from. And yes you will need to form a proper Entity with all valid annotations the above Entity is just for example.

just a lateral approach.

public List<List<Object[]>> execute(String sqls, Object valueObject) throws Exception {
    String[] queries = sqls.split(";");
    List<List<Object[]>> result = new ArrayList<>();

    for(int i=0; i<queries.length; i++) {
        result.add(this.select(queries[i], valueObject));
    }
    return result;
}

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