我在我的项目中使用 Java8、Hibernate 5.2.10Final 和 MySQL 5.7。但是我在使用时遇到了一些问题java.time.LocalDate
。有两个实体类:
TradeDay.class:
@Entity
@Table(name = "ENTITY__TRADE_DAY")
public class TradeDay {
@Id
@Column(name = "TRADE_DAY_DATE")
private LocalDate date;
........
@OneToMany(targetEntity = Transaction.class, mappedBy = "tradeDay", cascade = CascadeType.ALL)
@LazyCollection(LazyCollectionOption.EXTRA)
private Set<Transaction> transactionSet=new LinkedHashSet<>();
........
}
和 Transaction.class
@Entity
@Table(name = "ENTITY__TRANSACTION")
public class Transaction {
@Id
@GeneratedValue(strategy = GenerationType.TABLE, generator = "increase")
@TableGenerator(name = "increase", allocationSize = 1)
@Column(name = "TRANSACTION_INDEX")
private int index;
........
@ManyToOne(targetEntity = TradeDay.class,fetch = FetchType.LAZY)
@JoinColumn(name = "TRADE_DAY_DATE")
private TradeDay tradeDay;
........
}
然后我遇到的问题:
1.当我LocalDate
在HQL中用作key时,SQL中的最终值将是上一个日期。例如:
@Override
public List<Transaction> getTransactionList(LocalDate date) {
Session session = HibernateSessionManager.getCurrentSession();
Query<Transaction> query = session.createQuery("from Transaction t where t.date=? order by t.index asc", Transaction.class);
query.setParameter(0,date);
return query.list();
}
ps:t.date
等于transaction.getTradeDay().getDate()
。
我使用此代码在数据库中搜索。但是,当我给出一个参数时2010-12-18
,结果的日期都是2010-12-17
.
2.我@LazyCollection(LazyCollectionOption.EXTRA)
用来确保当我调用方法transactionSet.size()
休眠时只会执行一个“计数”SQL。它确实有效,但是当我迭代它时,集合中什么都没有。
测试代码:
......//Before, get a TradeDay entity
Set<Transaction> transactionSet=tradeDay.getTransactionSet();
System.out.println(tradeDay.getDate()+" complete with "+transactionSet.size()+" records.");
for(Transaction transaction:transactionSet){
System.out.println(transaction.getIndex());
}
//Impl of `getTransactionList` is the code above
List<Transaction> transactionList=DAOManager.getTransactionDAO().getTransactionList(tradeDay.getDate());
System.out.println(tradeDay.getDate()+" complete with "+transactionList.size()+" records.");
for(Transaction transaction:transactionList){
System.out.println(transaction.getIndex());
}
输出如下:
//Just a count SQL because of @LazyCollection(LazyCollectionOption.EXTRA)
Hibernate: select count(TRANSACTION_INDEX) from ENTITY__TRANSACTION where TRADE_DAY_DATE =?
//count SQL got 4 result
1990-12-20 complete with 4 records.
//Iterate set, real SQL
Hibernate: select ...... from ENTITY__TRANSACTION transactio0_ where transactio0_.TRADE_DAY_DATE=?
//No index output???
//SQL by getTransactionList
Hibernate: select ...... from ENTITY__TRANSACTION transactio0_ where transactio0_.TRANSACTION_DATE=? order by transactio0_.TRANSACTION_INDEX asc
//Got 4 result too
1990-12-20 complete with 4 records.
//Success print the index
5535748
5882738
5925376
6165413
我该如何解决这些问题?谢谢你的帮助。