我正在Spring中创建一个Web应用程序,其中包含一些事务和类别。交易与ManyToOne
有Category
关系。现在,我要通过ID而不是Category
(作为对象)来设置类别。
之所以不能使用EntityManager
是因为我在EntityListener
中需要它。在我的回答中,我找到了一种自动连接此EntityListener
的方法,从而解决了我的问题。
春季有可能吗?
我在StackOverflow Hibernate - Add member entity instance by ID上找到了它,但是我无法在需要的地方使用EntityManager
。
这是我的交易实体:
@Entity
@ToString
@Slf4j
@EntityListeners(TransactionListener.class)
@Getter
@Setter
public class Transaction {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
@Column
private long account;
@Column
@JsonFormat(pattern = "dd-MM-yyyy")
private LocalDate date;
@Column
private float amount;
@Column(columnDefinition = "text")
private String description;
@Column(unique = true)
private String hash;
@ManyToOne
@JoinColumn(name = "category_id")
@JsonIgnoreProperties("transactions")
private Category category;
}
这是我的类别实体
@Entity
@ToString
@Getter
@Setter
@EntityListeners(CategoryListener.class)
public class Category {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
@Column
private String name;
@Column
private String color;
@Column
private String[] matchers;
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
@OneToMany(mappedBy = "category")
@JsonIgnoreProperties("category")
private List<Transaction> transactions;
}
答案 0 :(得分:0)
我无法自动连接EntityManager,因为我在实体侦听器中需要此功能,并且这些未自动连接。我找到了一种在Injecting a Spring dependency into a JPA EntityListener上自动接线的方法。
感谢所有帮助我的人! :)