java 从Hibernate本机多连接查询转换对象

6ljaweal  于 2023-02-20  发布在  Java
关注(0)|答案(1)|浏览(81)

我有一个连接三个表的hib原生sql查询,我正尝试从结果中检索3列

public void doTestQuery() {

try (Session session = HibernateUtilities.getSessionFactory().openSession()) {
    transaction = session.beginTransaction();

    String sql = "SELECT\r\n"
            + " users.username, \r\n"
            + " user_roles.role_name, \r\n"
            + " address.address\r\n"
            + "FROM\r\n"
            + " address\r\n"
            + " INNER JOIN\r\n"
            + " users\r\n"
            + " ON \r\n"
            + "     address.iduser = users.iduser\r\n"
            + " INNER JOIN\r\n"
            + " user_roles\r\n"
            + " ON \r\n"
            + " users.iduser = user_roles.iduser";
    NativeQuery query = session.createNativeQuery(sql);

    List<Object[]> results = query.list();
    
    for (Object[] arr : results) {

System.out.println(arr[0].toString() +" "+ arr[1].toString() +" "+ arr[2].toString());
    }
    
    transaction.commit();

}

如果我用下面的代码替换System.out.println,它会给我一个错误。有没有办法从这类休眠查询中转换对象?

Users user = (Users) arr[0];
            UserRoles userRole = (UserRoles) arr[1];
            Address _address = (Address) arr[2];    
            System.out.println(user.getUsername() + userRole.getRolename() + _address.getAddress());

7lrncoxx

7lrncoxx1#

Hibernate需要特殊的别名才能从结果集中获取数据,为此,Hibernate支持原生SQL中的特殊模板。

String sql = "SELECT "
        + " {u.*},"
        + " {r.*},"
        + " {a.*} "
        + "FROM "
        + " address a "
        + " INNER JOIN "
        + " users u "
        + " ON a.iduser = u.iduser "
        + " INNER JOIN "
        + " user_roles r "
        + " ON u.iduser = r.iduser";
NativeQuery query = session.createNativeQuery(sql);
query.addEntity("u", Users.class);
query.addEntity("r", UserRoles.class);
query.addEntity("a", Address.class);

相关问题