使用 spring 启动与休眠的持久性问题,IllegalArgumentException:不是实体
Persistence problem using spring boot with hibernate, IllegalArgumentException: Not an entity
我的日志
. ____ _ __ _ _
/\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.4)
2021-04-15 19:59:32.923 INFO 12676 --- [ restartedMain] br.com.api.ApiApplication : Starting ApiApplication using Java 15.0.2 on DESKTOP-TEEJGQ6 with PID 12676 (C:\Users\karpi\Desktop\api-hcf\target\classes started by karpi in C:\Users\karpi\Desktop\api-hcf)
2021-04-15 19:59:32.936 INFO 12676 --- [ restartedMain] br.com.api.ApiApplication : No active profile set, falling back to default profiles: default
2021-04-15 19:59:33.017 INFO 12676 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-04-15 19:59:33.017 INFO 12676 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2021-04-15 19:59:34.323 INFO 12676 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-04-15 19:59:34.340 INFO 12676 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-04-15 19:59:34.340 INFO 12676 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.44]
2021-04-15 19:59:34.462 INFO 12676 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-04-15 19:59:34.463 INFO 12676 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1445 ms
2021-04-15 19:59:34.690 INFO 12676 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2021-04-15 19:59:34.923 INFO 12676 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2021-04-15 19:59:34.998 INFO 12676 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-04-15 19:59:35.010 INFO 12676 --- [ restartedMain] br.com.api.ApiApplication : Started ApiApplication in 2.686 seconds (JVM running for 3.449)
2021-04-15 19:59:46.003 INFO 12676 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-04-15 19:59:46.003 INFO 12676 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-04-15 19:59:46.004 INFO 12676 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
2021-04-15 19:59:46.132 INFO 12676 --- [nio-8080-exec-1] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.29.Final
2021-04-15 19:59:46.137 INFO 12676 --- [nio-8080-exec-1] org.hibernate.cfg.Environment : HHH000205: Loaded properties from resource hibernate.properties: {hibernate.format_sql=false, hibernate.hbm2ddl.auto=update, hibernate.c3p0.max_size=10, hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect, hibernate.c3p0.min_size=5, hibernate.connection.username=root, hibernate.enable_lazy_load_no_trans=true, hibernate.connection.url=jdbc:mysql://localhost:3306/springboot?useTimezone=true&serverTimezone=America/Sao_Paulo, hibernate.show_sql=false, hibernate.connection.driver_class=com.mysql.cj.jdbc.Driver, hibernate.c3p0.max_statements=30, hibernate.connection.password=****, hibernate.c3p0.timeout=3000, hibernate.bytecode.use_reflection_optimizer=false}
2021-04-15 19:59:50.130 INFO 12676 --- [nio-8080-exec-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-04-15 19:59:50.262 WARN 12676 --- [nio-8080-exec-1] o.h.e.j.c.i.ConnectionProviderInitiator : HHH000022: c3p0 properties were encountered, but the c3p0 provider class was not found on the classpath; these properties are going to be ignored.
2021-04-15 19:59:50.265 WARN 12676 --- [nio-8080-exec-1] org.hibernate.orm.connections.pooling : HHH10001002: Using Hibernate built-in connection pool (not for production use!)
2021-04-15 19:59:50.275 INFO 12676 --- [nio-8080-exec-1] org.hibernate.orm.connections.pooling : HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/springboot?useTimezone=true&serverTimezone=America/Sao_Paulo]
2021-04-15 19:59:50.276 INFO 12676 --- [nio-8080-exec-1] org.hibernate.orm.connections.pooling : HHH10001001: Connection properties: {password=****, user=root}
2021-04-15 19:59:50.276 INFO 12676 --- [nio-8080-exec-1] org.hibernate.orm.connections.pooling : HHH10001003: Autocommit mode: false
2021-04-15 19:59:50.279 INFO 12676 --- [nio-8080-exec-1] .c.i.DriverManagerConnectionProviderImpl : HHH000115: Hibernate connection pool size: 20 (min=1)
2021-04-15 19:59:50.683 INFO 12676 --- [nio-8080-exec-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
2021-04-15 19:59:51.398 INFO 12676 --- [nio-8080-exec-1] org.hibernate.orm.connections.access : HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@2b29f169] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
2021-04-15 19:59:51.441 INFO 12676 --- [nio-8080-exec-1] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
java.lang.IllegalArgumentException: Not an entity: class br.com.api.entities.Persona
at org.hibernate.metamodel.internal.MetamodelImpl.entity(MetamodelImpl.java:566)
at org.hibernate.query.criteria.internal.QueryStructure.from(QueryStructure.java:127)
at org.hibernate.query.criteria.internal.CriteriaQueryImpl.from(CriteriaQueryImpl.java:158)
at br.com.hcf.HCFConnection.all(HCFConnection.java:139)
at br.com.api.controls.CharacterControl.getAll(CharacterControl.java:26)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:832)
我的元模型
public static void getAnnotatedClasses() {
EntityManager em = null;
try {
em = sessionFactory.createEntityManager();
em.getMetamodel().getEntities().forEach(System.out::println); // Persona is here
} catch (Exception e) {
e.printStackTrace();
} finally {
if (em != null) {
em.close();
}
}
}
我的控制器
package br.com.api.controls;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import br.com.api.entities.Persona;
import br.com.hcf.HCFConnection;
import br.com.hcf.HCFactory;
@RestController
@RequestMapping("api/v1/public")
public class CharacterControl {
@GetMapping("/characters")
public ResponseEntity<Object> getAll() {
try {
HCFactory.getFactory();
HCFactory.getAnnotatedClasses();
return ResponseEntity.ok(new HCFConnection<>(Persona.class).all());
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
}
我的实体
package br.com.api.entities;
import java.time.LocalDateTime;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Persona {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
private LocalDateTime modified;
private String resourceURI;
public Persona() {
}
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDateTime getModified() {
return modified;
}
public void setModified(LocalDateTime modified) {
this.modified = modified;
}
public String getResourceURI() {
return resourceURI;
}
public void setResourceURI(String resourceURI) {
this.resourceURI = resourceURI;
}
@Override
public String toString() {
return "Persona [id=" + id + ", name=" + name + ", description=" + description + ", modified=" + modified
+ ", resourceURI=" + resourceURI + "]";
}
}
在主要方法中它起作用了,那么 springboot 有什么问题,我看过了,但没有解决任何问题,有没有人知道什么可能正在发生,依赖关系,spring 配置,休眠配置,pom.xml 配置,项目配置,任何东西?
我添加了 EntityScan,但错误仍然存在。
package br.com.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
@SpringBootApplication
@EntityScan(basePackages = "br.com.api.entities")
public class ApiApplication {
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
}
api 我正在使用:https://github.com/Eduardo-Karpinski/hcf
为了解决问题,我将代码修改为更接近 Spring 想要的模型,但错误仍然存在。
package br.com.api;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import br.com.hcf.HCFFactory;
@Configuration
@EntityScan(basePackages = "br.com.api.entities")
public class Config {
@Bean
public HCFFactory factory() {
HCFFactory factory = HCFFactory.getInstance();
return factory;
}
}
package br.com.api.controls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import br.com.api.entities.Persona;
import br.com.hcf.HCFConnection;
import br.com.hcf.HCFFactory;
@RestController
@RequestMapping("api/v1/public")
public class CharacterControl {
@Autowired
HCFFactory factory;
@GetMapping("/characters")
public ResponseEntity<Object> getAll() {
try {
factory.getFactory();
factory.getAnnotatedClasses();
return ResponseEntity.ok(new HCFConnection<>(Persona.class).all());
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
}
在调试 MetamodelImpl class 期间,我发现出现在我面前的错误是不可能的,因为我想保留的 class 在 Map "** jpaEntityTypeMap **" 中。
调试中的变量值:
jpaEntityTypeMap ConcurrentHashMap <K, V> (id = 135)
[0] ConcurrentHashMap $ MapEntry <K, V> (id = 252)
key Class <T> (br.com.api.entities.Persona) (id = 156)
value EntityTypeImpl <J> (id = 157)
cls Class <T> (br.com.api.entities.Persona) (id = 244)
我开始认为这是一个 spring 引导错误
在运行进行其他测试时,我意识到当运行在CharacterControl class
中进行以下块时
public static void main(String[] args) {
HCFFactory.getInstance().getFactory();
HCFFactory.getInstance().getAnnotatedClasses();
new HCFConnection<>(Persona.class).all().forEach(System.out::println);
}
同样的错误是因为**jpaEntityTypeMap**为null,但是我在Personaclass上运行的时候没有报错,什么意思?
这次改了还是一样的错误,spring不喜欢我。
package br.com.api.controls;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import br.com.api.entities.Persona;
@RestController
@RequestMapping("api/v1/public")
public class CharacterControl {
@GetMapping("/characters")
public ResponseEntity<Object> getAll() {
Configuration conf = new Configuration();
conf.setProperty("hibernate.connection.username", "root");
conf.setProperty("hibernate.connection.password", "root");
conf.setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
conf.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/springboot?useTimezone=true&serverTimezone=America/Sao_Paulo");
conf.setProperty("hibernate.hbm2ddl.auto", "update");
conf.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
conf.addAnnotatedClass(Persona.class);
SessionFactory factory = conf.buildSessionFactory();
try (Session session = factory.openSession()){
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Persona> criteria = builder.createQuery(Persona.class);
criteria.from(Persona.class);
List<Persona> resultList = session.createQuery(criteria).getResultList();
return ResponseEntity.ok(resultList);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
}
堆栈
java.lang.IllegalArgumentException: Not an entity: class br.com.api.entities.Persona
at org.hibernate.metamodel.internal.MetamodelImpl.entity(MetamodelImpl.java:566)
at org.hibernate.query.criteria.internal.QueryStructure.from(QueryStructure.java:127)
at org.hibernate.query.criteria.internal.CriteriaQueryImpl.from(CriteriaQueryImpl.java:158)
at br.com.api.controls.CharacterControl.getAll(CharacterControl.java:38)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:832)
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>br.com</groupId>
<artifactId>exemple</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>exemple</name>
<description>Demo project</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
似乎未扫描包“br.com.api.entities”,因此您的实体未知。您应该添加:
@EntityScan(basePackages = "br.com.api.entities")
在配置中 class 所以它会被识别。
此致。
在解析您的代码时,我注意到您正在以静态方式创建自己的会话工厂和实体管理器。所以我认为你应该对实体包扫描做同样的事情,因为 @EntityScan 不会工作,因为你没有使用 spring.
您应该手动添加实体(或通过扫描包裹),例如:
Configuration conf = new Configuration();
...
conf.addAnnotatedClass(EntityClass.class)
我在一个项目中测试了你的控制器代码,它工作正常,我没有包括 spring-boot-starter-data-jpa 因为你想自己构建会话工厂:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>test-self-configuration</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.7.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
```
我的日志
. ____ _ __ _ _
/\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.4.4)
2021-04-15 19:59:32.923 INFO 12676 --- [ restartedMain] br.com.api.ApiApplication : Starting ApiApplication using Java 15.0.2 on DESKTOP-TEEJGQ6 with PID 12676 (C:\Users\karpi\Desktop\api-hcf\target\classes started by karpi in C:\Users\karpi\Desktop\api-hcf)
2021-04-15 19:59:32.936 INFO 12676 --- [ restartedMain] br.com.api.ApiApplication : No active profile set, falling back to default profiles: default
2021-04-15 19:59:33.017 INFO 12676 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : Devtools property defaults active! Set 'spring.devtools.add-properties' to 'false' to disable
2021-04-15 19:59:33.017 INFO 12676 --- [ restartedMain] .e.DevToolsPropertyDefaultsPostProcessor : For additional web related logging consider setting the 'logging.level.web' property to 'DEBUG'
2021-04-15 19:59:34.323 INFO 12676 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat initialized with port(s): 8080 (http)
2021-04-15 19:59:34.340 INFO 12676 --- [ restartedMain] o.apache.catalina.core.StandardService : Starting service [Tomcat]
2021-04-15 19:59:34.340 INFO 12676 --- [ restartedMain] org.apache.catalina.core.StandardEngine : Starting Servlet engine: [Apache Tomcat/9.0.44]
2021-04-15 19:59:34.462 INFO 12676 --- [ restartedMain] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring embedded WebApplicationContext
2021-04-15 19:59:34.463 INFO 12676 --- [ restartedMain] w.s.c.ServletWebServerApplicationContext : Root WebApplicationContext: initialization completed in 1445 ms
2021-04-15 19:59:34.690 INFO 12676 --- [ restartedMain] o.s.s.concurrent.ThreadPoolTaskExecutor : Initializing ExecutorService 'applicationTaskExecutor'
2021-04-15 19:59:34.923 INFO 12676 --- [ restartedMain] o.s.b.d.a.OptionalLiveReloadServer : LiveReload server is running on port 35729
2021-04-15 19:59:34.998 INFO 12676 --- [ restartedMain] o.s.b.w.embedded.tomcat.TomcatWebServer : Tomcat started on port(s): 8080 (http) with context path ''
2021-04-15 19:59:35.010 INFO 12676 --- [ restartedMain] br.com.api.ApiApplication : Started ApiApplication in 2.686 seconds (JVM running for 3.449)
2021-04-15 19:59:46.003 INFO 12676 --- [nio-8080-exec-1] o.a.c.c.C.[Tomcat].[localhost].[/] : Initializing Spring DispatcherServlet 'dispatcherServlet'
2021-04-15 19:59:46.003 INFO 12676 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Initializing Servlet 'dispatcherServlet'
2021-04-15 19:59:46.004 INFO 12676 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 1 ms
2021-04-15 19:59:46.132 INFO 12676 --- [nio-8080-exec-1] org.hibernate.Version : HHH000412: Hibernate ORM core version 5.4.29.Final
2021-04-15 19:59:46.137 INFO 12676 --- [nio-8080-exec-1] org.hibernate.cfg.Environment : HHH000205: Loaded properties from resource hibernate.properties: {hibernate.format_sql=false, hibernate.hbm2ddl.auto=update, hibernate.c3p0.max_size=10, hibernate.dialect=org.hibernate.dialect.MySQL5InnoDBDialect, hibernate.c3p0.min_size=5, hibernate.connection.username=root, hibernate.enable_lazy_load_no_trans=true, hibernate.connection.url=jdbc:mysql://localhost:3306/springboot?useTimezone=true&serverTimezone=America/Sao_Paulo, hibernate.show_sql=false, hibernate.connection.driver_class=com.mysql.cj.jdbc.Driver, hibernate.c3p0.max_statements=30, hibernate.connection.password=****, hibernate.c3p0.timeout=3000, hibernate.bytecode.use_reflection_optimizer=false}
2021-04-15 19:59:50.130 INFO 12676 --- [nio-8080-exec-1] o.hibernate.annotations.common.Version : HCANN000001: Hibernate Commons Annotations {5.1.2.Final}
2021-04-15 19:59:50.262 WARN 12676 --- [nio-8080-exec-1] o.h.e.j.c.i.ConnectionProviderInitiator : HHH000022: c3p0 properties were encountered, but the c3p0 provider class was not found on the classpath; these properties are going to be ignored.
2021-04-15 19:59:50.265 WARN 12676 --- [nio-8080-exec-1] org.hibernate.orm.connections.pooling : HHH10001002: Using Hibernate built-in connection pool (not for production use!)
2021-04-15 19:59:50.275 INFO 12676 --- [nio-8080-exec-1] org.hibernate.orm.connections.pooling : HHH10001005: using driver [com.mysql.cj.jdbc.Driver] at URL [jdbc:mysql://localhost:3306/springboot?useTimezone=true&serverTimezone=America/Sao_Paulo]
2021-04-15 19:59:50.276 INFO 12676 --- [nio-8080-exec-1] org.hibernate.orm.connections.pooling : HHH10001001: Connection properties: {password=****, user=root}
2021-04-15 19:59:50.276 INFO 12676 --- [nio-8080-exec-1] org.hibernate.orm.connections.pooling : HHH10001003: Autocommit mode: false
2021-04-15 19:59:50.279 INFO 12676 --- [nio-8080-exec-1] .c.i.DriverManagerConnectionProviderImpl : HHH000115: Hibernate connection pool size: 20 (min=1)
2021-04-15 19:59:50.683 INFO 12676 --- [nio-8080-exec-1] org.hibernate.dialect.Dialect : HHH000400: Using dialect: org.hibernate.dialect.MySQL5InnoDBDialect
2021-04-15 19:59:51.398 INFO 12676 --- [nio-8080-exec-1] org.hibernate.orm.connections.access : HHH10001501: Connection obtained from JdbcConnectionAccess [org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator$ConnectionProviderJdbcConnectionAccess@2b29f169] for (non-JTA) DDL execution was not in auto-commit mode; the Connection 'local transaction' will be committed and the Connection will be set into auto-commit mode.
2021-04-15 19:59:51.441 INFO 12676 --- [nio-8080-exec-1] o.h.e.t.j.p.i.JtaPlatformInitiator : HHH000490: Using JtaPlatform implementation: [org.hibernate.engine.transaction.jta.platform.internal.NoJtaPlatform]
java.lang.IllegalArgumentException: Not an entity: class br.com.api.entities.Persona
at org.hibernate.metamodel.internal.MetamodelImpl.entity(MetamodelImpl.java:566)
at org.hibernate.query.criteria.internal.QueryStructure.from(QueryStructure.java:127)
at org.hibernate.query.criteria.internal.CriteriaQueryImpl.from(CriteriaQueryImpl.java:158)
at br.com.hcf.HCFConnection.all(HCFConnection.java:139)
at br.com.api.controls.CharacterControl.getAll(CharacterControl.java:26)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:832)
我的元模型
public static void getAnnotatedClasses() {
EntityManager em = null;
try {
em = sessionFactory.createEntityManager();
em.getMetamodel().getEntities().forEach(System.out::println); // Persona is here
} catch (Exception e) {
e.printStackTrace();
} finally {
if (em != null) {
em.close();
}
}
}
我的控制器
package br.com.api.controls;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import br.com.api.entities.Persona;
import br.com.hcf.HCFConnection;
import br.com.hcf.HCFactory;
@RestController
@RequestMapping("api/v1/public")
public class CharacterControl {
@GetMapping("/characters")
public ResponseEntity<Object> getAll() {
try {
HCFactory.getFactory();
HCFactory.getAnnotatedClasses();
return ResponseEntity.ok(new HCFConnection<>(Persona.class).all());
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
}
我的实体
package br.com.api.entities;
import java.time.LocalDateTime;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
@Entity
public class Persona {
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String name;
private String description;
private LocalDateTime modified;
private String resourceURI;
public Persona() {
}
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public LocalDateTime getModified() {
return modified;
}
public void setModified(LocalDateTime modified) {
this.modified = modified;
}
public String getResourceURI() {
return resourceURI;
}
public void setResourceURI(String resourceURI) {
this.resourceURI = resourceURI;
}
@Override
public String toString() {
return "Persona [id=" + id + ", name=" + name + ", description=" + description + ", modified=" + modified
+ ", resourceURI=" + resourceURI + "]";
}
}
在主要方法中它起作用了,那么 springboot 有什么问题,我看过了,但没有解决任何问题,有没有人知道什么可能正在发生,依赖关系,spring 配置,休眠配置,pom.xml 配置,项目配置,任何东西?
我添加了 EntityScan,但错误仍然存在。
package br.com.api;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.domain.EntityScan;
@SpringBootApplication
@EntityScan(basePackages = "br.com.api.entities")
public class ApiApplication {
public static void main(String[] args) {
SpringApplication.run(ApiApplication.class, args);
}
}
api 我正在使用:https://github.com/Eduardo-Karpinski/hcf
为了解决问题,我将代码修改为更接近 Spring 想要的模型,但错误仍然存在。
package br.com.api;
import org.springframework.boot.autoconfigure.domain.EntityScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import br.com.hcf.HCFFactory;
@Configuration
@EntityScan(basePackages = "br.com.api.entities")
public class Config {
@Bean
public HCFFactory factory() {
HCFFactory factory = HCFFactory.getInstance();
return factory;
}
}
package br.com.api.controls;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import br.com.api.entities.Persona;
import br.com.hcf.HCFConnection;
import br.com.hcf.HCFFactory;
@RestController
@RequestMapping("api/v1/public")
public class CharacterControl {
@Autowired
HCFFactory factory;
@GetMapping("/characters")
public ResponseEntity<Object> getAll() {
try {
factory.getFactory();
factory.getAnnotatedClasses();
return ResponseEntity.ok(new HCFConnection<>(Persona.class).all());
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
}
在调试 MetamodelImpl class 期间,我发现出现在我面前的错误是不可能的,因为我想保留的 class 在 Map "** jpaEntityTypeMap **" 中。
调试中的变量值:
jpaEntityTypeMap ConcurrentHashMap <K, V> (id = 135)
[0] ConcurrentHashMap $ MapEntry <K, V> (id = 252)
key Class <T> (br.com.api.entities.Persona) (id = 156)
value EntityTypeImpl <J> (id = 157)
cls Class <T> (br.com.api.entities.Persona) (id = 244)
我开始认为这是一个 spring 引导错误
在运行进行其他测试时,我意识到当运行在CharacterControl class
中进行以下块时public static void main(String[] args) {
HCFFactory.getInstance().getFactory();
HCFFactory.getInstance().getAnnotatedClasses();
new HCFConnection<>(Persona.class).all().forEach(System.out::println);
}
同样的错误是因为**jpaEntityTypeMap**为null,但是我在Personaclass上运行的时候没有报错,什么意思?
这次改了还是一样的错误,spring不喜欢我。
package br.com.api.controls;
import java.util.List;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import br.com.api.entities.Persona;
@RestController
@RequestMapping("api/v1/public")
public class CharacterControl {
@GetMapping("/characters")
public ResponseEntity<Object> getAll() {
Configuration conf = new Configuration();
conf.setProperty("hibernate.connection.username", "root");
conf.setProperty("hibernate.connection.password", "root");
conf.setProperty("hibernate.connection.driver_class", "com.mysql.cj.jdbc.Driver");
conf.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/springboot?useTimezone=true&serverTimezone=America/Sao_Paulo");
conf.setProperty("hibernate.hbm2ddl.auto", "update");
conf.setProperty("hibernate.dialect", "org.hibernate.dialect.MySQL5InnoDBDialect");
conf.addAnnotatedClass(Persona.class);
SessionFactory factory = conf.buildSessionFactory();
try (Session session = factory.openSession()){
CriteriaBuilder builder = session.getCriteriaBuilder();
CriteriaQuery<Persona> criteria = builder.createQuery(Persona.class);
criteria.from(Persona.class);
List<Persona> resultList = session.createQuery(criteria).getResultList();
return ResponseEntity.ok(resultList);
} catch (Exception e) {
e.printStackTrace();
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(e.getMessage());
}
}
}
堆栈
java.lang.IllegalArgumentException: Not an entity: class br.com.api.entities.Persona
at org.hibernate.metamodel.internal.MetamodelImpl.entity(MetamodelImpl.java:566)
at org.hibernate.query.criteria.internal.QueryStructure.from(QueryStructure.java:127)
at org.hibernate.query.criteria.internal.CriteriaQueryImpl.from(CriteriaQueryImpl.java:158)
at br.com.api.controls.CharacterControl.getAll(CharacterControl.java:38)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64)
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.base/java.lang.reflect.Method.invoke(Method.java:564)
at org.springframework.web.method.support.InvocableHandlerMethod.doInvoke(InvocableHandlerMethod.java:197)
at org.springframework.web.method.support.InvocableHandlerMethod.invokeForRequest(InvocableHandlerMethod.java:141)
at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:106)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:894)
at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:808)
at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:87)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:1060)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:962)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1006)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:898)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:626)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:883)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:733)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:227)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.RequestContextFilter.doFilterInternal(RequestContextFilter.java:100)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.FormContentFilter.doFilterInternal(FormContentFilter.java:93)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.springframework.web.filter.CharacterEncodingFilter.doFilterInternal(CharacterEncodingFilter.java:201)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:119)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:189)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:162)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:202)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:97)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:542)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:143)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:92)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:78)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:357)
at org.apache.coyote.http11.Http11Processor.service(Http11Processor.java:374)
at org.apache.coyote.AbstractProcessorLight.process(AbstractProcessorLight.java:65)
at org.apache.coyote.AbstractProtocol$ConnectionHandler.process(AbstractProtocol.java:893)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1707)
at org.apache.tomcat.util.net.SocketProcessorBase.run(SocketProcessorBase.java:49)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.base/java.lang.Thread.run(Thread.java:832)
Pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.4.5</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
<groupId>br.com</groupId>
<artifactId>exemple</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>exemple</name>
<description>Demo project</description>
<properties>
<java.version>11</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>runtime</scope>
<optional>true</optional>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
似乎未扫描包“br.com.api.entities”,因此您的实体未知。您应该添加:
@EntityScan(basePackages = "br.com.api.entities")
在配置中 class 所以它会被识别。
此致。
在解析您的代码时,我注意到您正在以静态方式创建自己的会话工厂和实体管理器。所以我认为你应该对实体包扫描做同样的事情,因为 @EntityScan 不会工作,因为你没有使用 spring.
您应该手动添加实体(或通过扫描包裹),例如:
Configuration conf = new Configuration();
...
conf.addAnnotatedClass(EntityClass.class)
我在一个项目中测试了你的控制器代码,它工作正常,我没有包括 spring-boot-starter-data-jpa 因为你想自己构建会话工厂:
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.test</groupId>
<artifactId>test-self-configuration</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>jar</packaging>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.7.RELEASE</version>
<relativePath />
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
```