带H2的春季启动-不是托管类型



我在启动Spring Boot应用程序时遇到问题:

Caused by: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'coffeeService': Unsatisfied dependency expressed through field 'coffeeRepository': Error creating bean with name 'coffeeRepository' defined in com.coffeetime.coffeeshop.repository.CoffeeRepository defined in @EnableJpaRepositories declared on CoffeeshopApplication: Not a managed type: class com.coffeetime.coffeeshop.domain.Coffee
Caused by: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'coffeeRepository' defined in com.coffeetime.coffeeshop.repository.CoffeeRepository defined in @EnableJpaRepositories declared on CoffeeshopApplication: Not a managed type: class com.coffeetime.coffeeshop.domain.Coffee
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.coffeetime.coffeeshop.domain.Coffee

Spring Bot的版本是3.0,Java是17(大多数来自Initialzr的更新版本)。我想使用H2作为内存数据库:

<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-data-jpa</artifactId>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>javax.persistence-api</artifactId>
<version>2.2</version>
</dependency>
<dependency>
<groupId>com.h2database</groupId>
<artifactId>h2</artifactId>
<scope>runtime</scope>
</dependency>

包层次结构便于扫描实体。所以,我认为没有必要添加@ entitscan(我也试过了)

文件结构application.properties:

spring.datasource.url=jdbc:h2:mem:coffeeshopdb
spring.datasource.driverClassName=org.h2.Driver
spring.datasource.username=sa
spring.datasource.password=pass1234
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.show-sql=true
spring.h2.console.enabled=true
spring.jpa.defer-datasource-initialization=true

import org.springframework.data.jpa.repository.JpaRepository;
import com.coffeetime.coffeeshop.domain.Coffee;
public interface CoffeeRepository extends JpaRepository<Coffee, Long>{
}

和实体:

@Entity
@Table(name = "coffee")
public class Coffee {

@Id
@GeneratedValue(strategy=GenerationType.AUTO)
private Long id;

@Column(name = "name")
@NotEmpty(message = "Coffee name cannot be empty")
private String name;

@Column(name = "amount")
@NotNull(message = "Coffee price cannot be empty")
@Min(value = 0, message = "Coffee price must be greater than or equal to 0")
private BigDecimal amount;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public BigDecimal getAmount() {
return amount;
}
public void setAmount(BigDecimal amount) {
this.amount = amount;
}
}

我检查了类似的问题在这个线程,没有任何答案工作。我怀疑是H2

感谢我试着使用@ entitscan和玩application.properties。

我找到问题了。Spring Boot 3.0.0版本开始使用jakarta而不是javax.persistence。重新组织导入解决了这个问题。

相关内容

  • 没有找到相关文章

最新更新