抱歉,这可能是一个简单的问题,但我在Google上找不到任何内容。我正在用csvData解析超过100000行/对象。我想先检查属性的 ALL 值是否有效,然后再将其写入数据库。像@Size
或@Length
这样的注释无济于事...
举个例子:
实体:
@Entity
@Data
public class Transaction {
@Size(max = 30)
private String timestamp;
}
解析csv,并将对象记录在列表中。
List<Transaction> transaction = new ArrayList<>();
// list will be filled
try {
databaseConnector.saveAllTransactions(transaction, transactionRepository);
} catch (ConstraintViolationException exc) {
System.out.println(exc.getMessage());
}
第5个对象之后出现的错误。
Hibernate: insert into transaction (amount, customer_customer_id, discount, receipt_no, receipt_pos_no, timestamp, unit_price) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into transaction (amount, customer_customer_id, discount, receipt_no, receipt_pos_no, timestamp, unit_price) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into transaction (amount, customer_customer_id, discount, receipt_no, receipt_pos_no, timestamp, unit_price) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into transaction (amount, customer_customer_id, discount, receipt_no, receipt_pos_no, timestamp, unit_price) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into transaction (amount, customer_customer_id, discount, receipt_no, receipt_pos_no, timestamp, unit_price) values (?, ?, ?, ?, ?, ?, ?)
Validation failed for classes [com.stuff.project.entity.Transaction] during persist time for groups [javax.validation.groups.Default, ]
List of constraint violations:[
ConstraintViolationImpl{interpolatedMessage='muss zwischen 0 und 30 liegen', propertyPath=timestamp, rootBeanClass=class com.stuff.project.entity.Transaction, messageTemplate='{javax.validation.constraints.Size.message}'}
]
只有您知道该方法的外观。
public boolean saveAllTransactions(List<Transaction> transactions, TransactionRepository transactionRepository) {
transactionRepository.saveAll(transactions);
return true;
}
我唯一能想到的就是遍历整个对象列表,并为每个对象检查其长度的属性,例如:
transactions.forEach(e -> e.getTimestamp().length != 30); ....
这似乎并不十分友好...
答案 0 :(得分:2)
首先:性能不应该是您的主要关注点。您有一个包含N个条目的列表,并且当您要检查N个条目中每个条目的字符串长度时,嘿:您必须迭代N个条目,并查看每个条目。当然,从理论上讲,您可以并行执行此操作,如果可以使用“足够”的数据,则可以使事情更快,但需要消耗更多的CPU能力。
真实问题:您开始实施“额外验证”,而不是依靠注释。换句话说:您正在“围绕”框架工作。那很少是一个好主意。
假设我们正在谈论通用Java(bean)批注,那么规范的答案将是做两件事:
Transaction
对象的列表的类