User
Code:
@Entity
@Table(name = "USER")
public class User {
@Id
@Column(name = "USER_ID", nullable = false)
private Integer id;
@Column(name = "EMAIL", length = 100, unique = true, nullable = false)
private String email;
@Column(name = "NAME", length = 50, nullable = false)
private String name;
// It's a bad idea to use string password, please use binary password that is encrypted.
// Of course, when save or update the data, Java application need encrypt the string password to binary password
// by some algorithms, such as SHA1, MD5, RSA ...
@Column(name = "PASSWORD", length = 20, nullable = false);
private byte[] password;
@OneToMany(mappedBy = "from") // Fake side, mappedBy Transaction.from
private Set<Transaction> transactionsFromMe;
@OneToMany(mappedBy = "to") // Fake side, mappedBy Transaction.to
private Set<Transaction> transactionsToMe;
public Set<Transaction> getTransactionsFromMe() {
if (this.transactionsFromMe == null) {
this.transactionsFromMe = new HashSet<>();
}
return this.transactionsFromMe;
}
public Set<Transaction> getTransactionsToMe() {
if (this.transactionsToMe == null) {
this.transactionsToMe = new HashSet<>();
}
return this.transactionsToMe;
}
Other getters and setters
}
Transaction
Code:
@Entity
@Table(name = "TRANSACTION")
public class Transaction {
@Id
@Column(name = "TRANSACTION_ID", nullable = false)
private Integer id;
@ManyToOne
@JoinColumn(name = "FROM_ID", nullable = false)
private User from; //Real side
@ManyToOne
@JoinColumn(name = "TO_ID", nullable = false)
private User to; //Real side
@Column(name = "TYPE", nullable = false)
@Enumerated(EnumType.STRING)
private TransactionType type;
@Column(name = "DESCRIPTION", length = 1000, nullable = false)
private String description;
// It's a bad idea to use float or double for money
// Use java.math.BigDecimal to specify the amount to make it is precise absolutely.
@Column(name = "AMOUNT", nullable = false)
private BigDecimal amount;
Getters and setters
}
TransactionType
Code:
public enum TransactionType {
....
}
Two bidirectional associations are careted: One is combined by User.transactionFromMe and Transaction.from; the other one is combined by User.transactionsToMe and Transaction.to.
Note:user.getTransactionsFromMe().add(transaction);
// Change fake side, can not update relationship of databasetransaction.setFrom(user);
// Change real side, only this way can be used to update the relationship of database.