映射自定义JdbcTemplate查询结果在一个对象中 [英] Map Custom JdbcTemplate query result in an Object
问题描述
我是Java新手,并尝试使用spring框架.我有个问题. 例如,我有桌子:
I new in java and try to use spring framework. I have a question. By example, I have table :
- 员工(id_employee,姓名)
- employee_product(id_employee_product,id_employee,product_name)
如果我从Employee表中选择一个雇员数据,则可以将其映射到POJO模型用户中,并在该模型中定义表结构,如下所示:
if I select an employee data from my Employee table, I can map it in a POJO model User and define the tables structure in that model, like this:
public class Employee {
private final int id_employee;
private final String nama;
public Employee(int id_employee, String nama){
this.id_employee = id_employee;
this.nama = nama;
}
public int getId() {
return id_employee;
}
public String getNama() {
return nama;
}
}
这是jdbcTemplate中的地图:
And this is the map from jdbcTemplate:
final String sql = "SELECT id_employee, nama FROM employee";
return jdbcTemplate.query(sql, (resultSet, i) -> {
return new Employee(
resultSet.getInt("id_employee"),
resultSet.getString("nama")
);
});
这是从1个表中选择数据的明显示例.
That is clear example for select data from 1 table.
我的问题是,如果我的数据是自定义查询,如何从查询映射数据?这样的我们使用联接并从该表中选择自定义字段,我是否需要为每个查询创建POJO?
My question is, how to map data from query if my data is custom query? Such us using join and select custom field from that tables, Am I need to create POJO every query?
有时候我只需要从我的员工表中选择employee.id_employee
和employee.name
字段即可.
Sometimes I need to select only employee.id_employee
, and employee.name
field from my employee table.
在另一个控制器中,我需要从我的employee
表中选择employee.id_employee
.
And in another controller I need to select employee.id_employee
from my employee
table.
在另一种情况下,我只需要选择employee.name
和employee_product.product_name
In another case, I need only select employee.name
, and employee_product.product_name
有没有一种方法可以映射数据而不为每种情况创建POJO?
Is there an alternative to map the data without creating POJO for every case?
推荐答案
创建一个结合了两个表的POJO
Create a one POJO combining two tables like this
public class Employee {
private int id_employee;
private String name;
private int id_employee_product.
private String product_name
//getter and setters
//Don't create a constructor its Entiry
}
现在通过使用BeanPropertyRowMapper
文档链接将存储库写为
Now by using a BeanPropertyRowMapper
Doc Link write your repository like
public List<Employee> fetchEmployeeProduct(){
JdbcTemplate jdbcTemplate = new JdbcTemplate("Your_DataSource");
StringBuilder query = new StringBuilder();
query.append("Your Query");
List<Employee> employeeProductList =
jdbcTemplate.query(query.toString(), new BeanPropertyRowMapper<Employee>(Employee.class));
}
确保查询中的SELECT
子句与Employee
POJO的文件名相同.
Make sure SELECT
clause in the query and Employee
POJO's filed name is same.
一旦执行查询,它将自动映射到POJO.您无需编写自定义映射器BeanPropertyRowMapper
将负责映射.
Once if you execute your query it will automatically map to POJO. You no need to write a custom mapper BeanPropertyRowMapper
will take care of mapping.
这篇关于映射自定义JdbcTemplate查询结果在一个对象中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!