Java 将 ResultSet 映射到 Pojo 对象
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21462099/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Mapping ResultSet to Pojo Objects
提问by iCurious
Well that's really embarrassing I have made a standard pojo class and its dao class for data retrieval purpose. I am having a difficulty to understand a basic procedure to how to handle a customized query data to Pojo class.
好吧,这真的很尴尬,我为数据检索目的制作了一个标准的 pojo 类及其 dao 类。我很难理解如何处理 Pojo 类的自定义查询数据的基本过程。
let's say my User class is
假设我的 User 类是
public class User{
private int userId;
private String username;
private int addressId;
}
public class Address{
private int addressId;
private String zip;
}
public class UserDAO{
public void getUserDetails(){
String getSql = select u.userId, u.username, a.zipcode from user u, address a where u.addressId = a.addressId;
//no pojo class is now specific to the resultset returned. so we can't map result to pojo object
}
}
now how I should model this with my pojo class as if using String to manage this then concept of object oriented vanishes, also complexity would increase in the future as well. kindly guide!
现在我应该如何使用我的 pojo 类对此进行建模,就像使用 String 来管理它一样,然后面向对象的概念消失了,未来的复杂性也会增加。请指导!
Update for Further Explanation
更新进一步解释
We know that we can map same table objects with same pojo class, but when the query is customized and there is a data returned which doesn't map to any specific class then what would be the procedure? i.e. should we make another class? or should we throw that data in a String variable? kindly give some example as well.
我们知道我们可以用相同的 pojo 类映射相同的表对象,但是当查询被自定义并且返回的数据没有映射到任何特定的类时,那么程序是什么?即我们应该做另一个类吗?或者我们应该把这些数据扔到一个字符串变量中?请举一些例子。
采纳答案by Divers
For this purpose you can use one of implementation of JPA. But as you want to do it manually I will give you small example.
为此,您可以使用JPA的实现之一。但是当你想手动完成时,我会给你一个小例子。
UPD:
更新:
public class User {
private int userId;
private String username;
private Address address; // USE POJO not ID
}
public class Address{
private int addressId;
private String zip;
List<User> users;
}
public User getUserById(Connection con, long userId) {
PreparedStatement stmt;
String query = "select u.user_id, u.user_name, a.id, a.zip from user u, address a where a.address_id = u.id and u.id = ?";
User user = new User();
Address address = new Address;
try {
stmt = con.prepareStatement(query);
stmt.setLong(1, userId);
ResultSet rs = stmt.executeQuery();
address.setId(rs.getInt("id"));
address.setZip(rs.getString("zip");
user.setId(rs.getInt("id"));
user.setUsername(rs.getString("user_name"));
user.setAddressId(rs.getInt("address_id"));
user.setAddress(address); // look here
} catch (SQLException e) {
if (con != null) {
try {
System.err.print("Transaction is being rolled back");
con.rollback();
} catch (SQLException excep) {
}
}
} finally {
if (stmt != null) {
stmt.close();
}
}
return user;
}
You shouldn't do new POJO for that query, you should write normal query. And remember - your object model is main, tables in DB is just a way to save data of your application.
你不应该为那个查询做新的 POJO,你应该写普通的查询。请记住 - 您的对象模型是主要的,数据库中的表只是保存应用程序数据的一种方式。
回答by lance-java
There's many ORMframeworks that can do this including Hibernate, myBatis, JPAand spring-JDBC
有许多ORM框架可以做到这一点,包括Hibernate、myBatis、JPA和spring-JDBC
spring-jdbc and myBatis give you granular control over the SQL whereas with JPA and Hibernate you are usually abstracted away from the SQL.
spring-jdbc 和 myBatis 为您提供对 SQL 的精细控制,而使用 JPA 和 Hibernate,您通常从 SQL 中抽象出来。
I suggest you do some reading and figure out which one you like before rolling your own solution.
我建议您在推出自己的解决方案之前先阅读并弄清楚您喜欢哪一个。
回答by schsu01
Your question:
你的问题:
We know that we can map same table objects with same pojo class,
but when the query is customized and there is a data returned
which doesn't map to any specific class then what would be the procedure?
If you have 100 kinds of SQL which returns different combination of columns, could it be to create 100 different POJOs? The answer is "NO, stop using POJO".
如果你有 100 种返回不同列组合的 SQL,是否可以创建 100 个不同的 POJO?答案是“不,停止使用 POJO”。
This library qoodis designed to solve this problem, you can try it.
这个库qood就是为了解决这个问题而设计的,你可以试试。
回答by J Slick
We know that we can map same table objects with same pojo class, but when the query is customized and there is a data returned which doesn't map to any specific class then what would be the procedure? i.e. should we make another class?
我们知道我们可以用相同的 pojo 类映射相同的表对象,但是当查询被自定义并且返回的数据没有映射到任何特定的类时,那么程序是什么?即我们应该做另一个类吗?
JPA dynamic instantiation allows you to define a query with a POJO whose constructor specifies only the fields and types you want from the database.
JPA 动态实例化允许您使用 POJO 定义查询,该 POJO 的构造函数仅指定您希望从数据库中获取的字段和类型。
This will perform a JPA selection which will return a List.
If you need to change the query later and the columns are unchanged, your POJO will still work.
If you change the columns, then also change the POJO accordingly.
这将执行一个 JPA 选择,它将返回一个列表。
如果您稍后需要更改查询并且列保持不变,您的 POJO 仍然可以工作。
如果更改列,则也要相应地更改 POJO。
NOTE:
笔记:
You must specify fully qualified package and constructor arguments.
您必须指定完全限定的包和构造函数参数。
Type User must be a JPA-mapped or JPA-annotated entity class.
类型 User 必须是 JPA-mapped 或 JPA-annotated 实体类。
The entityManager is in JPA EntityManagerFactory.
entityManager 在 JPA EntityManagerFactory 中。
TypedQuery<User> q;
String sql = "select new com.stuff.User(
int u.userId, String u.username, String a.zipcode)
from User u, Address a where u.addressId = a.addressId";
List<User> list = entityManager.createQuery(sql).getResultList();
for(User u : list) {
doStuff(u);
}
Dynamic instantiation is also handy when you want to select specified columns, but avoid those columns with large data, such as BLOB types.
For example, maybe you want a list of proxy POJO's which represent the fully populated thing, but are themselves not fully populated.
You present the proxy list, and when the user selects one, then you do another query to get the fully populated object.
当您想要选择指定的列时,动态实例化也很方便,但要避免那些包含大量数据的列,例如 BLOB 类型。
例如,也许您想要一个代理 POJO 列表,它们代表完全填充的事物,但它们本身并未完全填充。
您提供代理列表,当用户选择一个时,您会执行另一个查询以获取完全填充的对象。
Your mileage may vary.
你的旅费可能会改变。