使用Hibernate映射实体到表时出现BeanCreationException问题求助
Hey there, let's break down this error you're seeing:
org.hibernate.AnnotationException: @OneToOne or @ManyToOne on com.userFront.domain.SavingsTransaction.savingsAccount references an unknown entity: com.userFront.domain.SavingsAccount
The root cause is super straightforward: your SavingsAccount class is missing the @Entity annotation, so Hibernate doesn't recognize it as a persistent database entity. When SavingsTransaction tries to reference it via @ManyToOne, Hibernate has no idea what SavingsAccount is supposed to be.
What's Wrong Exactly?
Looking at your code, SavingsTransaction correctly has the @Entity annotation (telling Hibernate to map it to a database table), but SavingsAccount has no such annotation. Without @Entity, Hibernate ignores the class entirely—so it can't resolve the relationship between the two.
The Fix
Just add the @Entity annotation to SavingsAccount and import the corresponding package. Here's the corrected code:
package com.userFront.domain; import java.math.BigDecimal; import java.util.List; import javax.persistence.CascadeType; import javax.persistence.Entity; // Add this import import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.OneToMany; import net.minidev.json.annotate.JsonIgnore; @Entity // Add this annotation public class SavingsAccount { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long id ; private int accountNumber; private BigDecimal accountBalance; @OneToMany(mappedBy="savingsAccount",cascade=CascadeType.ALL,fetch=FetchType.LAZY) @JsonIgnore private List<SavingsTransaction> SavingsTransactionList; // Getters and setters remain the same public Long getId() { return id; } public void setId(Long id) { this.id = id; } public int getAccountNumber() { return accountNumber; } public void setAccountNumber(int accountNumber) { this.accountNumber = accountNumber; } public BigDecimal getAccountBalance() { return accountBalance; } public void setAccountBalance(BigDecimal accountBalance) { this.accountBalance = accountBalance; } public List<SavingsTransaction> getSavingsTransactionList() { return SavingsTransactionList; } public void setSavingsTransactionList(List<SavingsTransaction> savingsTransactionList) { SavingsTransactionList = savingsTransactionList; } }
Quick Additional Checks (If It Still Fails)
If you still run into issues after adding @Entity, double-check these:
- Make sure your Spring Boot main application class is in a parent package of
com.userFront.domain(e.g.,com.userFront), so it automatically scans for entities. If not, use the@EntityScan("com.userFront.domain")annotation on your main class to specify the entity package. - Verify that both classes are in the exact same package (
com.userFront.domain)—a typo here could also cause Hibernate to miss the entity.
内容的提问来源于stack exchange,提问作者Hamza Khadhri

