因此,我有一个家庭作业,需要实现两个实体-帐户和交易 此外,我需要能够在两个帐户之间创建交易(场景:仅涉及两个帐户)
我还需要找出Transaction的表结构,并且希望能对Transaction table创建脚本有所帮助。
我的问题是:我需要了解如何引用这两个表之间的外键和关系,因为现在对我来说还不清楚。
逻辑是下一个:
我在想,也许Account
会有两个List<Transaction>
,如:
private List<Transaction> transactionsMade;
private List<Transaction> transactionsReceived.
因此:
在Transaction
类中,将是:
@ManyToOne
引用了transactionMadeList
private Account emitter;
@ManyToOne
引用了transactionReceivedList
private Account receptor;
这是我的课程
Account.class
public class Account {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private String holder;
@NotNull
private Integer balance;
@OneToMany(mappedBy = "emitter",fetch = FetchType.EAGER,cascade = CascadeType.ALL)
private List<Transaction> transactionsMade;
@OneToMany(mappedBy = "receptor",fetch = FetchType.EAGER,cascade = CascadeType.ALL)
private List<Transaction> transactionsReceived;
}
Transaction.class
public class Transaction {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@NotNull
private Integer amount;
@NotNull
private LocalDateTime created;
@ManyToOne
@JoinColumn(name = "transactionEmitter")
private Account emitter;
@ManyToOne
@JoinColumn(name = "transactionReceptor")
private Account receptor;
public Transaction(Integer amount, Account emitter, Account receptor){
this.created = LocalDateTime.now();
this.amount = amount;
this.emitter = emitter;
this.receptor = receptor;
}
}
现在就这样。
提前谢谢! :)
答案 0 :(得分:1)
我发现只有两件事可以做得更好:
1)使用
Instant
而不是LocalDateTime
,它将以UTC时间存储。
更改此:
private LocalDateTime created;
对此:
private Instant created;
2)不要使用
EAGER
初始化:
@OneToMany(mappedBy = "emitter",fetch = FetchType.EAGER,cascade = CascadeType.ALL)
private List<Transaction> transactionsMade;
@OneToMany(mappedBy = "receptor",fetch = FetchType.EAGER,cascade = CascadeType.ALL)
private List<Transaction> transactionsReceived;
将变为:
@OneToMany(mappedBy = "emitter",fetch = FetchType.LAZY,cascade = CascadeType.ALL)
private List<Transaction> transactionsMade;
@OneToMany(mappedBy = "receptor",fetch = FetchType.LAZY,cascade = CascadeType.ALL)
private List<Transaction> transactionsReceived;
如果您着名LazyInitializationException
,请尝试将其包裹在@Transactional
周围。这样做可能会使事情复杂化,但是从长远来看,它将节省您一些服务器资源,因为您甚至不需要使用所有帐户的交易时也不会加载这些交易。
3)创建一个存储库以模块化您的功能,就像这样:
@Repository
public interface TransactionRepository extends JpaRepository<Transaction, Long> {
Collection<Transaction> findAllByEmitter(Account emitter);
Collection<Transaction> findAllByReceptor(Account receptor);
}