简体   繁体   English

通过ID而非实体添加与实体的关系

[英]Add relation to entity by id instead of object

I'm creating a web application in Spring where I've some transactions and categories. 我在Spring中创建一个Web应用程序,其中包含一些事务和类别。 The transactions have a ManyToOne relation to Category . 交易与Category具有ManyToOne关系。 Now I want to set the category by id and not by Category (as object). 现在,我想按ID而不是按Category (作为对象)设置类别。

The reason why I couldn't use the EntityManager is because I needed this in a EntityListener . 我之所以不能使用EntityManager是因为我在EntityListener需要它。 In my answer I found a way to autowire this EntityListener which fixed my problem. 在我的回答中,我找到了一种自动连接此EntityListener的方法,从而解决了我的问题。

Is this possible in Spring ? 春天有可能吗?

I found this on StackOverflow Hibernate - Add member entity instance by ID , but I can't use the EntityManager where I need it. 我在StackOverflow Hibernate上发现了此问题-通过ID添加成员实体实例 ,但是无法在需要的地方使用EntityManager

This is my transaction entity: 这是我的交易实体:

@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;
}

and this is my category entity 这是我的类别实体

@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;
}

I could not autowire the EntityManager because I needed this in a entity listener and these are not autowired. 我无法自动连接EntityManager,因为我在实体侦听器中需要此功能,并且这些功能不会自动连接。 I found a way to get this autowired on Injecting a Spring dependency into a JPA EntityListener . 我发现了一种在将Spring依赖项注入JPA EntityListener中时自动连接的方法

Thanks for everyone who helped me! 感谢所有帮助我的人! :) :)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM