我试图使用SpEL模板从实体生成文件名。 我有两个看起来类似的实体:
@Entity
public class Invoice implements Serializable {
private String invoicenumber;
private Customer customer;
@Column(name = "invoicenumber", nullable = false, length = 20)
public String getInvoicenumber() {
return this.invoicenumber;
}
@ManyToOne(fetch = FetchType.LAZY)
@JoinColumn(name = "fk_customer", nullable = false)
public Customer getCustomer() {
return this.customer;
}
}
@Entity
public class Customer implements Serializable {
private String firstname;
private String lastname;
@Column(name = "firstname", nullable = false, length = 20)
public String getFirstname() {
return this.firstname;
}
@Column(name = "lastname", nullable = false, length = 20)
public String getLastname() {
return this.lastname;
}
}
与此类似的SpEL模板:
String template = "invoicenumber + '-' + customer.firstname + ' ' + customer.lastname";
然后我使用SpEL从模板生成带有发票对象的文件名
public String generateFilename(String filenameTemplate, Object dataObject) {
ExpressionParser parser = new SpelExpressionParser();
Expression expression = parser.parseExpression(filenameTemplate);
return expression.getValue(dataObject, String.class);
}
此测试有效:
String testTemplate = "invoicenumber + '-' + customer.firstname + ' ' + customer.lastname";
Invoice invoice = new Invoice();
invoice.setInvoicenumber("BF2016-06-ABCDEF");
invoice.setCustomer(new Customer());
invoice.getCustomer().setFirstname("Hans");
invoice.getCustomer().setLastname("Hansen");
assertEquals("BF2016-06-ABCDEF-Hans Hansen", generator.generateFilename(testTemplate, invoice));
此测试没有:
Invoice invoice = invoiceRepository.findOne(4);
String template = "invoicenumber + '-' + customer.firstname + ' ' + customer.lastname";
String filename = filenameGenerator.generateFilename(template, invoice);
assertEquals("12344-201601-Heinrich Jahnke", filename);
这个测试实际上导致" 12344-201601 - "这使我得出这样的假设,即用于延迟加载客户对象的hibernate代理是问题所在。 firstname和lastname字段在从数据库加载之前为null,这将解释呈现的文件名。
有关如何解决此问题的任何想法?我已经尝试过的一些事情:
Hibernate.initialize(invoice);
Hibernate.initialize(invoice.getCustomer());
System.out.println(invoice.getCustomer().getFirstname());
答案 0 :(得分:1)
问题出在其他地方,SpEL和JPA / Hibernate合作得很好。对不起!
我的实际表达看起来像这样:
"invoicenumber + '-' + (customer.company == null ? customer.fname + ' ' + customer.sname : customer.company)"
可悲的是,从数据库加载的客户确实有一家公司,一家空公司...... 使用以下表达式,一切正常:
"invoicenumber + '-' + (customer.company == null or customer.company.isEmpty() ? customer.fname + ' ' + customer.sname : customer.company)"