- iOS/Objective-C 元类和类别
- objective-c - -1001 错误,当 NSURLSession 通过 httpproxy 和/etc/hosts
- java - 使用网络类获取 url 地址
- ios - 推送通知中不播放声音
我有三个实体类,我编写了包含两个表连接的查询。
表:费用类别
@Entity
@Table(name = "ExpensesCategories")
public class ExpensesCategories {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "category_id", unique = true)
private int categoryId;
@NotNull
private String categoryName;
@NotNull
private String categoryCodeInBankStats;
public int getCategoryId() {
return categoryId;
}
public void setCategoryId(int categoryId) {
this.categoryId = categoryId;
}
public String getCategoryName() {
return categoryName;
}
public void setCategoryName(String categoryName) {
this.categoryName = categoryName;
}
public String getCategoryCodeInBankStats() {
return categoryCodeInBankStats;
}
public void setCategoryCodeInBankStats(String categoryCodeInBankStats) {
this.categoryCodeInBankStats = categoryCodeInBankStats;
}
}
表:交易
@Entity
@Table(name = "TransactionHistory")
public class TransactionHistory {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private int id;
@Temporal(TemporalType.DATE)
private Date dateOfTransaction;
private String transactionType;
private String refNo;
private Date valueDate;
private double withdrawalAmount;
private double depositAmount;
private double closingBalance;
@ManyToOne
@JoinColumn(name="userDetailsId", referencedColumnName="user_id")
private UserDetails userDetails;
@ManyToOne
@JoinColumn(name="expenseCategoriesId", referencedColumnName="category_id")
private ExpensesCategories expenseCategories;
public TransactionHistory(int userId, Date dateOfTransaction, String transactionType, String refNo, Date valueDate,
double withdrawalAmount, double depositAmount, double closingBalance) {
this.dateOfTransaction = dateOfTransaction;
this.transactionType = transactionType;
this.refNo = refNo;
this.valueDate = valueDate;
this.withdrawalAmount = withdrawalAmount;
this.depositAmount = depositAmount;
this.closingBalance = closingBalance;
}
public TransactionHistory() {
}
public Date getDateOfTransaction() {
return dateOfTransaction;
}
public void setDateOfTransaction(Date date) {
this.dateOfTransaction = date;
}
public String getTransactionType() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
public String getRefNo() {
return refNo;
}
public void setRefNo(String refNo) {
this.refNo = refNo;
}
public Date getValueDate() {
return valueDate;
}
public void setValueDate(Date valueDate) {
this.valueDate = valueDate;
}
public double getWithdrawalAmount() {
return withdrawalAmount;
}
public void setWithdrawalAmount(double withdrawalAmount) {
this.withdrawalAmount = withdrawalAmount;
}
public double getDepositAmount() {
return depositAmount;
}
public void setDepositAmount(double depositAmount) {
this.depositAmount = depositAmount;
}
public double getClosingBalance() {
return closingBalance;
}
public void setClosingBalance(double closingBalance) {
this.closingBalance = closingBalance;
}
public UserDetails getUserDetails() {
return userDetails;
}
public void setUserDetails(UserDetails userDetails) {
this.userDetails = userDetails;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public ExpensesCategories getExpenseCategories() {
return expenseCategories;
}
public void setExpenseCategories(ExpensesCategories expenseCategories) {
this.expenseCategories = expenseCategories;
}
}
表:用户详细信息
@Entity
@Table(name = "Employee")
public class UserDetails {
@Id
@Column(name = "user_id", unique = true)
private int id;
@NotNull
private String firstname;
@NotNull
private String lastname;
@Column(unique = true)
@NotNull
private String emailaddress;
@NotNull
private String role;
public UserDetails(String firstname, String lastname, String emailaddress, String role) {
this.firstname = firstname;
this.lastname = lastname;
this.emailaddress = emailaddress;
this.role = role;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public UserDetails() {
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getEmailaddress() {
return emailaddress;
}
public void setEmailaddress(String emailaddress) {
this.emailaddress = emailaddress;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
@Override
public String toString() {
return "Employee [id=" + id + ", firstname=" + firstname + ", lastname=" + lastname + ", emailaddress="
+ emailaddress + ", role=" + role + "]";
}
我在 transaction
实体中编写了这样的查询。
@Query( nativeQuery=true, value="SELECT a.expense_categories_id, a.Total_withdrawal_Amount, b.category_code_in_bank_stats, b.category_name FROM (SELECT expense_categories_id , SUM(withdrawal_amount) AS Total_withdrawal_Amount FROM transaction_history GROUP BY expense_categories_id) a join expenses_categories b on a.expense_categories_id = b.category_id
")
List<Object[]> getCategorizedExpenses();
我的 Json
响应如下:
[
[
1,
21,
"UPI",
"UPI Payments"
],
[
2,
3733.59,
"POS",
"Shopping"
]
]
但我也想要带有列名的 json 响应:
[
[
expense_categories_id: 1,
Total_withdrawal_Amount: 21,
category_code_in_bank_stats: "UPI",
category_name: "UPI Payments"
],
[
expense_categories_id: 2,
Total_withdrawal_Amount: 3733.59,
category_code_in_bank_stats: "POS",
category_name: "Shopping"
]
]
请帮帮我..
最佳答案
您需要将结果直接映射到 POJO 类并添加一些 json 配置:
1)定义pojo
public ResultClass implements Serializable{
@JsonProperty("expense_categories_id")
private Integer expenseCategoriesId;
...
public ResultClass(Integer expenseCategoriesId ... // rest params){
this.expenseCategoriesId = expenseCategoriesId;
...
}
}
2)定义映射:
@SqlResultSetMapping(
name="myMapping",
classes={
@ConstructorResult(
targetClass=ResultClass.class,
columns={
@ColumnResult(name="expenseCategoriesId"),
@ColumnResult(name="totalWithdrawalAmount")
// further mappings ...
}
)
}
)
3)定义原生查询
@NamedNativeQuery(name="TransactionHistory.myQuery"
, query="SELECT new mypackage.ResultClass(a.expense_categories_id as expeneCategoriesId ... ) from ...")
4) 在 CrudRepository
中定义此方法,不使用 @Query
注释:
public List<ResultClass> myQuery();
Teh @SqlResultSetMapping 和 @NamedNativeQuery
需要在您的映射实体之一上定义。
关于java - 获取列名以及 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47631154/
这个问题已经有答案了: When to use single quotes, double quotes, and backticks in MySQL (13 个答案) 已关闭 3 年前。 我正在尝
我需要一个返回某些列值的选择查询。我想要的列以“U_S”开头。 Select * from em 我需要转换上面的查询。 '*' 必须是以下结果(但带有逗号): select COLUMN_NAME
在JPA中设置一对多关系时如何设置外键的列名? 我想将“items_id”的名称更改为“item_id” @OneToMany private List items; 我尝试了以下注释但没有成功: @
我有一个jqGrid列定义如下 name : 'idmycolumn', index : 'idmycolumn', width : 80,
我是否可以编写一个带参数的存储过程,即 mysql 查询,存储过程返回查询的列名? 例如我调用程序: 调用选择器('select * from users') 过程返回列名。使用 informatio
嗨,我刚刚开始学习 sql,我希望使用 concat 将列合并为一个列,但没能做到。我可以在没有 concat 的情况下运行代码,但是当我使用 concat 时,它会给我一个错误代码。谁能告诉我我做错
我们正在使用 java jdk 1.7.0_45,postgresql jdbc 连接器 postgresql-9.3-1100.jdbc41.jar。 这是我们问题的概要,下面粘贴了尽可能多的代码。
import pandas as pd import numpy as np rng = pd.date_range('1/1/2011', periods=6, freq='H') df = pd.
借助 PHP 的 mysqli 扩展,我可以使用 fetch_field() 方法通过 orgname 和 获取列和表的原始(无别名)名称结果中的 orgtable。 PDO 提供了方法getColu
我在 php 中使用 PDO,因此无法使用准备好的语句转义表名或列名。以下是我自己实现它的万无一失的方法吗: $tn = str_replace('`', '', $_REQUEST['tn']);
我想使用 apply 来跨越矩阵的行,并且我想在我的函数中使用当前行的行名。好像不能用rownames , colnames , dimnames或 names直接在函数内部。我知道我可以根据 thi
在编写管理数据的应用程序时,允许最终用户创建或删除最好表示为列的数据类别通常很有用。例如,我正在开发字典构建应用程序;用户可能会决定他们想要向数据添加“备用拼写”字段或其他内容,这可以很容易地表示为另
在我的数据框中,许多列名称以“.y”结尾,如示例所示: dat <- data.frame(x1=sample(c(0:1)), id=sample(10), av1.y = sample(10) ,
在 SQL Server 中,我希望看到 Table_Name 以及数据库中与该 Table_Name 关联的所有列。所以输出应该是这样的: TABLE_NAME COLUMN_N
在我的数据框中,许多列名称以“.y”结尾,如示例所示: dat <- data.frame(x1=sample(c(0:1)), id=sample(10), av1.y = sample(10) ,
在一种情况下,我们动态创建 sql 到 create动态临时表。 table_name 没有问题,因为它是由我们决定的,但是列名是由我们无法控制的来源提供的。 通常我们会使用以下查询检查列名: sel
我有一个数据框,我们可以通过代理 df = pd.DataFrame({'a':[1,0,0], 'b':[0,1,0], 'c':[1,0,0], 'd':[2,3,4]}) 还有一个类别系列 ca
我需要编写一个用户定义的函数,当应用于数据框时,它将返回列位置、列名称、模式和每个变量的类。我能够创建一个返回模式和类的,但是当我包含位置/名称时,我总是收到错误。我一直在这样做, myFunctio
我刚开始使用 QueryDSL 并遇到了问题。是否可以使用列名进行 orderBy?我为 orderBy 动态路径生成找到了这个: Generic querydsl orderBy dynamic p
操作 DataGridView 单元格时,您通常会执行以下操作: MyGrid.CurrentRow.Cells["EmployeeFirstName"].Value = "John"; 这一切都很好
我是一名优秀的程序员,十分优秀!