英文:
Casting objects from Hibernate native multiple join query
问题
以下是翻译的部分:
我有一个使用Hibernate原生SQL查询连接三个表的代码,并尝试从结果中检索3列。
如果我将System.out.println替换为下面的代码,它会出现错误。是否有一种方法可以从这种类型的Hibernate查询中强制转换对象?
Users user = (Users) arr[0];
UserRoles userRole = (UserRoles) arr[1];
Address _address = (Address) arr[2];
System.out.println(user.getUsername() + userRole.getRolename() + _address.getAddress());
在这段代码中,您正在尝试将查询结果中的Object数组元素转换为具体的Java对象类型(Users、UserRoles、Address)。如果出现错误,可能是因为您需要进行适当的类型转换或者查询结果不返回您期望的对象类型。要确保类型转换成功,需要检查查询结果的类型和查询的字段是否匹配。
英文:
I have a hibernate native sql query joining three tables, and I'm trying to retrive 3 columns from the result
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();
}
If I replace the System.out.println with this code below, it gives me an error. Is there a way to cast objects from this kind of hibernate queries?
Users user = (Users) arr[0];
UserRoles userRole = (UserRoles) arr[1];
Address _address = (Address) arr[2];
System.out.println(user.getUsername() + userRole.getRolename() + _address.getAddress());
答案1
得分: 1
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);
英文:
Hibernate requires special aliases to be able to fetch the data from a result set. For this purpose, Hibernate supports a special template in native 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);
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论