I'm developing a request API in java spring boot, I developed my post but when testing it returns the 400 bad request error and the following error in the terminal
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "create table restaurant_orders (id uuid not null, address varchar(25) not null, block varchar(5), customer_name varchar(11) not null, door_number varchar(10) not null, order varchar(30) not null, phone_number varchar(15) not null, price float4 not null, registration_date timestamp(6) not null, primary key (id))" via JDBC Statement
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:67) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlString(AbstractSchemaMigrator.java:587) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.applySqlStrings(AbstractSchemaMigrator.java:532) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.createTable(AbstractSchemaMigrator.java:307) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]
at org.hibernate.tool.schema.internal.GroupedSchemaMigratorImpl.performTablesMigration(GroupedSchemaMigratorImpl.java:79) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.performMigration(AbstractSchemaMigrator.java:225) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]
at org.hibernate.tool.schema.internal.AbstractSchemaMigrator.doMigration(AbstractSchemaMigrator.java:126) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.performDatabaseAction(SchemaManagementToolCoordinator.java:284) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.lambda$process$5(SchemaManagementToolCoordinator.java:143) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]
at java.base/java.util.HashMap.forEach(HashMap.java:1429) ~[na:na]
at org.hibernate.tool.schema.spi.SchemaManagementToolCoordinator.process(SchemaManagementToolCoordinator.java:140) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:336) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]
at org.hibernate.boot.internal.SessionFactoryBuilderImpl.build(SessionFactoryBuilderImpl.java:415) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1425) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:66) ~[spring-orm-6.0.4.jar:6.0.4]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:376) ~[spring-orm-6.0.4.jar:6.0.4]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:409) ~[spring-orm-6.0.4.jar:6.0.4]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:396) ~[spring-orm-6.0.4.jar:6.0.4]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:352) ~[spring-orm-6.0.4.jar:6.0.4]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1797) ~[spring-beans-6.0.4.jar:6.0.4]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1747) ~[spring-beans-6.0.4.jar:6.0.4]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:599) ~[spring-beans-6.0.4.jar:6.0.4]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:521) ~[spring-beans-6.0.4.jar:6.0.4]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:326) ~[spring-beans-6.0.4.jar:6.0.4]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-6.0.4.jar:6.0.4]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:324) ~[spring-beans-6.0.4.jar:6.0.4]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200) ~[spring-beans-6.0.4.jar:6.0.4]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1130) ~[spring-context-6.0.4.jar:6.0.4]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:905) ~[spring-context-6.0.4.jar:6.0.4]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:584) ~[spring-context-6.0.4.jar:6.0.4]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:146) ~[spring-boot-3.0.2.jar:3.0.2]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:730) ~[spring-boot-3.0.2.jar:3.0.2]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:432) ~[spring-boot-3.0.2.jar:3.0.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:308) ~[spring-boot-3.0.2.jar:3.0.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1302) ~[spring-boot-3.0.2.jar:3.0.2]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1291) ~[spring-boot-3.0.2.jar:3.0.2]
at com.api.order_control.OrderControlApplication.main(OrderControlApplication.java:12) ~[classes/:na]
Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "order"
Position: 169
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2676) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2366) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:356) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.jdbc.PgStatement.executeInternal(PgStatement.java:496) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:413) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:333) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.jdbc.PgStatement.executeCachedSql(PgStatement.java:319) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.jdbc.PgStatement.executeWithFlags(PgStatement.java:295) ~[postgresql-42.5.1.jar:42.5.1]
at org.postgresql.jdbc.PgStatement.execute(PgStatement.java:290) ~[postgresql-42.5.1.jar:42.5.1]
at com.zaxxer.hikari.pool.ProxyStatement.execute(ProxyStatement.java:94) ~[HikariCP-5.0.1.jar:na]
at com.zaxxer.hikari.pool.HikariProxyStatement.execute(HikariProxyStatement.java) ~[HikariCP-5.0.1.jar:na]
at org.hibernate.tool.schema.internal.exec.GenerationTargetToDatabase.accept(GenerationTargetToDatabase.java:54) ~[hibernate-core-6.1.6.Final.jar:6.1.6.Final]
... 36 common frames omitted
I saw in some searches that the name "order" could be causing a problem in the database, so I changed it to "orders_restaurant" and I still have the same problem
model
package com.api.order_control.models;
import jakarta.persistence.*;
import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.UUID;
#Entity
#Table(name = "restaurant_orders")
public class OrderModel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private UUID id;
#Column(nullable = false, length = 11)
private String customerName;
#Column(nullable = false, length = 15)
private String phoneNumber;
#Column(nullable = false, length = 25)
private String address;
#Column(nullable = false, length = 10)
private String doorNumber;
#Column(nullable = true, length = 5)
private String block;
#Column(nullable = false, length = 30)
private String order;
#Column(nullable = false)
private Float price;
#Column(nullable = false)
private LocalDateTime registrationDate;
public UUID getId() {
return id;
}
public void setId(UUID id) {
this.id = id;
}
public String getCustomerName() {
return customerName;
}
public void setCustomerName(String customerName) {
this.customerName = customerName;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getDoorNumber() {
return doorNumber;
}
public void setDoorNumber(String doorNumber) {
this.doorNumber = doorNumber;
}
public String getBlock() {
return block;
}
public void setBlock(String block) {
this.block = block;
}
public String getOrder() {
return order;
}
public void setOrder(String order) {
this.order = order;
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public LocalDateTime getRegistrationDate() {
return registrationDate;
}
public void setRegistrationDate(LocalDateTime registrationDate) {
this.registrationDate = registrationDate;
}
}
controller
package com.api.order_control.controllers;
import com.api.order_control.dtos.OrderDto;
import com.api.order_control.models.OrderModel;
import com.api.order_control.services.OrderService;
import jakarta.validation.Valid;
import org.springframework.beans.BeanUtils;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
import java.time.ZoneId;
#RestController
#CrossOrigin(origins = "*", maxAge = 3600)
#RequestMapping("/order")
public class OrderController {
final OrderService orderService;
public OrderController(OrderService orderService) {
this.orderService = orderService;
}
#PostMapping
public ResponseEntity<Object> saveOrder(#RequestBody #Valid OrderDto orderDto) {
var orderModel = new OrderModel();
BeanUtils.copyProperties(orderDto, orderModel);
orderModel.setRegistrationDate(LocalDateTime.now(ZoneId.of("UTC")));
orderModel.setPrice(70.8f);
return ResponseEntity.status(HttpStatus.CREATED).body(orderService.save(orderModel));
}
}
Stack trace says that you have a problem in generated sql script at pos. 169. order is a keyword in sql, don't use it as a property name. Meanwhile, your table can have name orders without any problem
Related
I am trying to save the data in the database[PostgresQL] using graphql with JPA, spring-boot. I have created the schema and created the resolver.
I have created the Repository for the same.
While running the main java class it shows the below error.
It shows the error in resolver like there is no root resolver for the query type query.
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:658) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.ConstructorResolver.instantiateUsingFactoryMethod(ConstructorResolver.java:638) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.instantiateUsingFactoryMethod(AbstractAutowireCapableBeanFactory.java:1334) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBeanInstance(AbstractAutowireCapableBeanFactory.java:1177) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:564) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:524) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:335) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:234) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:333) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:208) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.preInstantiateSingletons(DefaultListableBeanFactory.java:944) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:918) ~[spring-context-5.3.9.jar:5.3.9]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:583) ~[spring-context-5.3.9.jar:5.3.9]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:754) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:434) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:338) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1343) ~[spring-boot-2.5.3.jar:2.5.3]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1332) ~[spring-boot-2.5.3.jar:2.5.3]
at com.example.demo.DemographqlApplication.main(DemographqlApplication.java:9) ~[main/:na]
Caused by: org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.coxautodev.graphql.tools.SchemaParser]: Factory method 'schemaParser' threw exception; nested exception is com.coxautodev.graphql.tools.SchemaClassScannerError: No Root resolvers for query type 'Query' found! Provide one or more com.coxautodev.graphql.tools.GraphQLQueryResolver to the builder.
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:185) ~[spring-beans-5.3.9.jar:5.3.9]
at org.springframework.beans.factory.support.ConstructorResolver.instantiate(ConstructorResolver.java:653) ~[spring-beans-5.3.9.jar:5.3.9]
... 18 common frames omitted
Caused by: com.coxautodev.graphql.tools.SchemaClassScannerError: No Root resolvers for query type 'Query' found! Provide one or more com.coxautodev.graphql.tools.GraphQLQueryResolver to the builder.
at com.coxautodev.graphql.tools.SchemaClassScanner$RootTypesHolder.createRootType(SchemaClassScanner.kt:424) ~[graphql-java-tools-5.2.4.jar:na]
at com.coxautodev.graphql.tools.SchemaClassScanner$RootTypesHolder.<init>(SchemaClassScanner.kt:405) ~[graphql-java-tools-5.2.4.jar:na]
at com.coxautodev.graphql.tools.SchemaClassScanner.scanForClasses(SchemaClassScanner.kt:78) ~[graphql-java-tools-5.2.4.jar:na]
at com.coxautodev.graphql.tools.SchemaParserBuilder.scan(SchemaParserBuilder.kt:151) ~[graphql-java-tools-5.2.4.jar:na]
at com.coxautodev.graphql.tools.SchemaParserBuilder.build(SchemaParserBuilder.kt:157) ~[graphql-java-tools-5.2.4.jar:na]
at com.oembedler.moon.graphql.boot.GraphQLJavaToolsAutoConfiguration.schemaParser(GraphQLJavaToolsAutoConfiguration.java:57) ~[graphql-spring-boot-autoconfigure-5.0.2.jar:na]
at com.oembedler.moon.graphql.boot.GraphQLJavaToolsAutoConfiguration$$EnhancerBySpringCGLIB$$7201a319.CGLIB$schemaParser$2(<generated>) ~[graphql-spring-boot-autoconfigure-5.0.2.jar:na]
at com.oembedler.moon.graphql.boot.GraphQLJavaToolsAutoConfiguration$$EnhancerBySpringCGLIB$$7201a319$$FastClassBySpringCGLIB$$52dead8e.invoke(<generated>) ~[graphql-spring-boot-autoconfigure-5.0.2.jar:na]
at org.springframework.cglib.proxy.MethodProxy.invokeSuper(MethodProxy.java:244) ~[spring-core-5.3.9.jar:5.3.9]
at org.springframework.context.annotation.ConfigurationClassEnhancer$BeanMethodInterceptor.intercept(ConfigurationClassEnhancer.java:331) ~[spring-context-5.3.9.jar:5.3.9]
at com.oembedler.moon.graphql.boot.GraphQLJavaToolsAutoConfiguration$$EnhancerBySpringCGLIB$$7201a319.schemaParser(<generated>) ~[graphql-spring-boot-autoconfigure-5.0.2.jar:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:78) ~[na:na]
at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) ~[na:na]
at java.base/java.lang.reflect.Method.invoke(Method.java:567) ~[na:na]
at org.springframework.beans.factory.support.SimpleInstantiationStrategy.instantiate(SimpleInstantiationStrategy.java:154) ~[spring-beans-5.3.9.jar:5.3.9]
... 19 common frames omitted```
**Model/autor.java**
#Entity
public class Author {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "name", nullable = false)
private String name;
#Column(name = "age")
private Integer age;
public Author() {
}
public Author(Long id) {
this.id = id;
}
public Author(String name, Integer age) {
this.name = name;
this.age = age;
}
public Long getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name=name;
}
public void setAge(Integer age) {
this.age=age;
}
public Integer getAge() {
return age;
}
#Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + "]";
}
}
**model/tutorial.java**
```#Entity
public class Tutorial {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "title", nullable = false)
private String title;
#Column(name = "description")
private String description;
#ManyToOne
#JoinColumn(name = "author_id", nullable = false, updatable = false)
private Author author;
public Tutorial() {
}
public Tutorial(String title, String description, Author author) {
this.title = title;
this.description = description;
this.author = author;
}
public Long getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Author getAuthor() {
return author;
}
public void setAuthor(Author author) {
this.author = author;
}
#Override
public String toString() {
return "Tutorial [id=" + id + ", title=" + title + ", description=" + description + ", author=" + author + "]";
}
}```
**Author Repository**
```import org.springframework.data.jpa.repository.*;
import com.example.demo.model.Author;
public interface AuthorRepository extends JpaRepository<Author, Long>{
}```
**Tutorial repository**
```import com.example.demo.model.Tutorial;
import org.springframework.data.jpa.repository.*;
public interface TutorialRepository extends JpaRepository<Tutorial, Long> {}```
**Mutation resolver**
``` import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.example.demo.model.Author;
import com.example.demo.model.Tutorial;
import com.example.demo.repository.AuthorRepository;
import com.example.demo.repository.TutorialRepository;
//import graphql.kickstart.tools.GraphQLMutationResolver;
import javassist.NotFoundException;
import com.coxautodev.graphql.tools.GraphQLMutationResolver;
#Component
public class Mutation implements GraphQLMutationResolver {
private AuthorRepository authorRepository;
private TutorialRepository tutorialRepository;
#Autowired
public Mutation(AuthorRepository authorRepository, TutorialRepository tutorialRepository) {
this.authorRepository = authorRepository;
this.tutorialRepository = tutorialRepository;
}
public Author createAuthor(String name, Integer age) {
Author author = new Author();
author.setName(name);
author.setAge(age);
authorRepository.save(author);
return author;
}
public Tutorial createTutorial(String title, String description, Long authorId) {
Tutorial tutorial = new Tutorial();
tutorial.setAuthor(new Author(authorId));
tutorial.setTitle(title);
tutorial.setDescription(description);
tutorialRepository.save(tutorial);
return tutorial;
}
public boolean deleteTutorial(Long id) {
tutorialRepository.deleteById(id);
return true;
}
public Tutorial updateTutorial(Long id, String title, String description) throws NotFoundException {
Optional<Tutorial> optTutorial = tutorialRepository.findById(id);
if (optTutorial.isPresent()) {
Tutorial tutorial = optTutorial.get();
if (title != null)
tutorial.setTitle(title);
if (description != null)
tutorial.setDescription(description);
tutorialRepository.save(tutorial);
return tutorial;
}
throw new NotFoundException("Not found Tutorial to update!");
}
}```
**Query-resolver**
``` import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.example.demo.model.Author;
import com.example.demo.model.Tutorial;
import com.example.demo.repository.AuthorRepository;
import com.example.demo.repository.TutorialRepository;
//import com.coxautodev.graphql.tools.GraphQLQueryResolver
import graphql.kickstart.tools.GraphQLQueryResolver;
#Component
public class Query implements GraphQLQueryResolver {
private AuthorRepository authorRepository;
private TutorialRepository tutorialRepository;
#Autowired
public Query(AuthorRepository authorRepository, TutorialRepository tutorialRepository) {
this.authorRepository = authorRepository;
this.tutorialRepository = tutorialRepository;
}
public Iterable<Author> findAllAuthors() {
return authorRepository.findAll();
}
public Iterable<Tutorial> findAllTutorials() {
return tutorialRepository.findAll();
}
public long countAuthors() {
return authorRepository.count();
}
public long countTutorials() {
return tutorialRepository.count();
}
}```
**Tutorial Resolver**
```import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.coxautodev.graphql.tools.GraphQLResolver;
import com.example.demo.model.Author;
import com.example.demo.model.Tutorial;
import com.example.demo.repository.AuthorRepository;
#Component
public class TutorialResolver implements GraphQLResolver<Tutorial> {
#Autowired
private AuthorRepository authorRepository;
public TutorialResolver(AuthorRepository authorRepository) {
this.authorRepository = authorRepository;
}
public Author getAuthor(Tutorial tutorial) {
return authorRepository.findById(tutorial.getAuthor().getId()).orElseThrow(null);
}
}```
**application.properties**
spring.datasource.url=jdbc:postgresql://localhost:5432/spgraphql_demo
spring.datasource.username=login
spring.datasource.password=admin#123
spring.jpa.hibernate.ddl-auto=update
# The SQL dialect makes Hibernate generate better SQL for the chosen database
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.main.web-application-type=none
When i run with springboot application i am getting the below error,
Error :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-05-21 14:22:24.399 ERROR 55512 --- [ main] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'customerRepository': FactoryBean threw exception on object creation; nested exception is java.lang.IllegalArgumentException: Not a managed type: class com.example.Model.Customer
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:178) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.getObjectFromFactoryBean(FactoryBeanRegistrySupport.java:101) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getObjectForBeanInstance(AbstractBeanFactory.java:1821) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.getObjectForBeanInstance(AbstractAutowireCapableBeanFactory.java:1266) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:260) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:623) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.beans.factory.support.DefaultListableBeanFactory.getBeansOfType(DefaultListableBeanFactory.java:611) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:51) ~[spring-data-commons-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.data.repository.config.DeferredRepositoryInitializationListener.onApplicationEvent(DeferredRepositoryInitializationListener.java:36) ~[spring-data-commons-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:403) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.publishEvent(AbstractApplicationContext.java:360) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:897) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:553) ~[spring-context-5.2.6.RELEASE.jar:5.2.6.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:143) ~[spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:758) [spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750) [spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) [spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1237) [spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) [spring-boot-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at com.example.demo.DemoApplication.main(DemoApplication.java:10) [classes/:na]
Caused by: java.lang.IllegalArgumentException: Not a managed type: class com.example.Model.Customer
at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:582) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.hibernate.metamodel.internal.MetamodelImpl.managedType(MetamodelImpl.java:85) ~[hibernate-core-5.4.15.Final.jar:5.4.15.Final]
at org.springframework.data.jpa.repository.support.JpaMetamodelEntityInformation.<init>(JpaMetamodelEntityInformation.java:75) ~[spring-data-jpa-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.data.jpa.repository.support.JpaEntityInformationSupport.getEntityInformation(JpaEntityInformationSupport.java:66) ~[spring-data-jpa-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getEntityInformation(JpaRepositoryFactory.java:229) ~[spring-data-jpa-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:179) ~[spring-data-jpa-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:162) ~[spring-data-jpa-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.data.jpa.repository.support.JpaRepositoryFactory.getTargetRepository(JpaRepositoryFactory.java:72) ~[spring-data-jpa-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactorySupport.getRepository(RepositoryFactorySupport.java:309) ~[spring-data-commons-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.lambda$afterPropertiesSet$5(RepositoryFactoryBeanSupport.java:297) ~[spring-data-commons-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport$$Lambda$569.000000001410C340.get(Unknown Source) ~[na:na]
at org.springframework.data.util.Lazy.getNullable(Lazy.java:212) ~[spring-data-commons-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.data.util.Lazy.get(Lazy.java:94) ~[spring-data-commons-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:244) ~[spring-data-commons-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.data.repository.core.support.RepositoryFactoryBeanSupport.getObject(RepositoryFactoryBeanSupport.java:57) ~[spring-data-commons-2.3.0.RELEASE.jar:2.3.0.RELEASE]
at org.springframework.beans.factory.support.FactoryBeanRegistrySupport.doGetObjectFromFactoryBean(FactoryBeanRegistrySupport.java:171) ~[spring-beans-5.2.6.RELEASE.jar:5.2.6.RELEASE]
... 24 common frames omitted
My respostiry class:
#Repository
public interface CustomerRepository extends JpaRepository<Customer,Long>{
}
My model class:
#Entity
#Table(name="customer")
public class Customer implements Serializable{
private static final long serialVersionUID = -2343243243242432341L;
#Id
#GeneratedValue(strategy=GenerationType.TABLE)
private long id;
#Override
public String toString() {
return "Customer [id=" + id + ", source=" + source + ", type=" + type + ", customername=" + customername
+ ", company=" + company + ", customeremail=" + customeremail + ", customernumber=" + customernumber
+ ", address=" + address + ", postcode=" + postcode + ", postoffice=" + postoffice + "]";
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getSource() {
return source;
}
public void setSource(String source) {
this.source = source;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getCustomername() {
return customername;
}
public void setCustomername(String customername) {
this.customername = customername;
}
public String getCompany() {
return company;
}
public void setCompany(String company) {
this.company = company;
}
public String getCustomeremail() {
return customeremail;
}
public void setCustomeremail(String customeremail) {
this.customeremail = customeremail;
}
public long getCustomernumber() {
return customernumber;
}
public void setCustomernumber(long customernumber) {
this.customernumber = customernumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getPostoffice() {
return postoffice;
}
public void setPostoffice(String postoffice) {
this.postoffice = postoffice;
}
#Column(name="source")
private String source;
#Column(name="type")
private String type;
#Column(name="customername")
private String customername;
#Column(name="company")
private String company;
#Column(name="customeremail")
private String customeremail;
#Column(name="customernumber")
private long customernumber;
#Column(name="address")
private String address;
#Column(name="postcode")
private String postcode;
#Column(name="postoffice")
private String postoffice;
}
My controller class :
#Configuration
#Controller
#EntityScan
#ComponentScan("com.example.demo.CustomerRepository")
#EnableAutoConfiguration
public class CustomerController {
#Autowired
private CustomerRepository rep;
#RequestMapping("/search/{id}")
public void search(#PathVariable long id)
{
String cust_res=rep.findById(id).toString();
System.out.println("search response ... "+cust_res);
}
}
Can you please help me to resolve this issue at earliest.???
use Long as id instead of primitive long
Suggestion : if possible use #GeneratedValue(strategy=GenerationType.IDENTITY)
instead of GenerationType.TABLE
https://vladmihalcea.com/why-you-should-never-use-the-table-identifier-generator-with-jpa-and-hibernate/
You are getting error - Not a managed type: class com.example.Model.Customer.
Application is not able to pick entities and manage them.
Resolution - Provide path of entities to #EntityScan as below:
#Configuration
#Controller
#EntityScan("com.example.Model")
#ComponentScan("com.example.demo.CustomerRepository")
#EnableAutoConfiguration
public class CustomerController
I am trying to retrieve data from 2 tables in MySql using spring boot and hibernate #OneToMany bi-directional mapping. But am getting this error among others:
No identifier specified for entity: com.dafe.spring.applogger.entity.Action
Please Check the error trace below:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-03-14 18:56:59.251 ERROR 8200 --- [ restartedMain] o.s.boot.SpringApplication : Application run failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.AnnotationException: No identifier specified for entity: com.dafe.spring.applogger.entity.Action
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1771) ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:593) ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:515) ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:320) ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:318) ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:199) ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1105) ~[spring-context-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:867) ~[spring-context-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE]
at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:744) [spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE]
at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:391) [spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:312) [spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) [spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE]
at org.springframework.boot.SpringApplication.run(SpringApplication.java:1204) [spring-boot-2.1.13.RELEASE.jar:2.1.13.RELEASE]
at com.dafe.spring.applogger.AppLoggerApplication.main(AppLoggerApplication.java:10) [classes/:na]
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:1.8.0_161]
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_161]
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source) ~[na:1.8.0_161]
at java.lang.reflect.Method.invoke(Unknown Source) ~[na:1.8.0_161]
at org.springframework.boot.devtools.restart.RestartLauncher.run(RestartLauncher.java:49) [spring-boot-devtools-2.1.13.RELEASE.jar:2.1.13.RELEASE]
Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com.dafe.spring.applogger.entity.Action
at org.hibernate.cfg.InheritanceState.determineDefaultAccessType(InheritanceState.java:266) ~[hibernate-core-5.3.15.Final.jar:5.3.15.Final]
at org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:211) ~[hibernate-core-5.3.15.Final.jar:5.3.15.Final]
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:775) ~[hibernate-core-5.3.15.Final.jar:5.3.15.Final]
at org.hibernate.boot.model.source.internal.annotations.AnnotationMetadataSourceProcessorImpl.processEntityHierarchies(AnnotationMetadataSourceProcessorImpl.java:250) ~[hibernate-core-5.3.15.Final.jar:5.3.15.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess$1.processEntityHierarchies(MetadataBuildingProcess.java:231) ~[hibernate-core-5.3.15.Final.jar:5.3.15.Final]
at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:274) ~[hibernate-core-5.3.15.Final.jar:5.3.15.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1215) ~[hibernate-core-5.3.15.Final.jar:5.3.15.Final]
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1246) ~[hibernate-core-5.3.15.Final.jar:5.3.15.Final]
at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391) ~[spring-orm-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:378) ~[spring-orm-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1830) ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]
at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1767) ~[spring-beans-5.1.14.RELEASE.jar:5.1.14.RELEASE]
... 21 common frames omitted
the class the error is pointing to is below but I don't seem to know what the problem is. Find below is the com.dafe.spring.applogger.entity.Action class :
package com.dafe.spring.applogger.entity;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import org.springframework.data.annotation.Id;
#Entity
#Table(name="action")
public class Action {
//declare & annotate your fields
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="time")
private Timestamp logTime;
#Column(name="type")
private String logType;
#Column(name="log_id")
private int userLogId;
#ManyToOne
#JoinColumn(name="log_id")
private UserLog userLog;
public Action(int id, Timestamp logTime, String logType, int userLogId, UserLog userLog) {
this.id = id;
this.logTime = logTime;
this.logType = logType;
this.userLogId = userLogId;
this.userLog = userLog;
}
//create and generate constructor
public Action() {
}
public Action(Timestamp logTime, String logType, int userLogId) {
this.logTime = logTime;
this.logType = logType;
this.userLogId = userLogId;
}
//generate getters and setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Timestamp getLogTime() {
return logTime;
}
public void setLogTime(Timestamp logTime) {
this.logTime = logTime;
}
public String getLogType() {
return logType;
}
public void setLogType(String logType) {
this.logType = logType;
}
public int getLogId() {
return userLogId;
}
public void setLogId(int logId) {
this.userLogId = logId;
}
public UserLog userLog() {
return userLog;
}
public void setLogs(UserLog userLog) {
this.userLog = userLog;
}
//generate toString
#Override
public String toString() {
return "Action [id=" + id + ", logTime=" + logTime + ", logType=" + logType + ", userLogId=" + userLogId + "]";
}
}
The action class is supposed to fetch data from database and has a foreign key relationship with class UserLog.
package com.dafe.spring.applogger.entity;
import java.util.ArrayList;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name="log")
public class UserLog {
//define field
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id")
private int id;
#Column(name="user_id")
private String userId;
#Column(name="session_id")
private String sessionId;
#OneToMany(mappedBy="log",cascade=CascadeType.ALL)
private ArrayList<Action>action;
//define constructors
public UserLog(String userId, String sessionId) {
this.userId = userId;
this.sessionId = sessionId;
}
//define getters and setters
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getSessionId() {
return sessionId;
}
public void setSessionId(String sessionId) {
this.sessionId = sessionId;
}
public ArrayList<Action> getAction() {
return action;
}
public void setAction(ArrayList<Action> action) {
this.action = action;
}
//convenience method for Action
public void addAction(Action tempAction) {
if (action == null) {
action = new ArrayList<>();
}
action.add(tempAction);
}
//define toString
#Override
public String toString() {
return "Log [id=" + id + ", userId=" + userId + ", sessionId=" + sessionId + "]";
}
}
please help me figure out the problem and a possible solution. Thanks.
You have imported the Id from the wrong package.This error can be thrown when you import a different library for #Id than javax.persistance.Id ;
So change
import org.springframework.data.annotation.Id;
To
import javax.persistence.Id
Refer this thread
I think an issue is related to this mapping:
#OneToMany(mappedBy="log",cascade=CascadeType.ALL)
private ArrayList<Action>action;
mappedBy points to the name of the property on the 'owning' side. So in your case you should specify mappedBy="userLog" as it's defined in Action class
#ManyToOne
#JoinColumn(name="log_id")
private UserLog userLog;
My project based on spring boot,Thymeleaf,mysql,html and Jquery.I tried to make a #oneToMany Relation with unidirectional in maintable,but it produces only error like
2017-10-23 16:17:49.908 ERROR 18724 --- [ main] o.s.boot.SpringApplication : Application startup failed
org.springframework.beans.factory.BeanCreationException: Error
creating bean with name 'entityManagerFactory' defined in class path
resource
[org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaAutoConfiguration.class]:
Invocation of init method failed; nested exception is
org.hibernate.AnnotationException: **Unable to map collection
com.vfraternity.process.entity.EntPropertyMaster.blockListPropSub** at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1702)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:583)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:502)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:312)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:228)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:310)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:200)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1083)
~[spring-context-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:858)
~[spring-context-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549)
~[spring-context-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:122)
~[spring-boot-2.0.0.M4.jar:2.0.0.M4] at
org.springframework.boot.SpringApplication.refresh(SpringApplication.java:750)
[spring-boot-2.0.0.M4.jar:2.0.0.M4] at
org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:386)
[spring-boot-2.0.0.M4.jar:2.0.0.M4] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:327)
[spring-boot-2.0.0.M4.jar:2.0.0.M4] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1245)
[spring-boot-2.0.0.M4.jar:2.0.0.M4] at
org.springframework.boot.SpringApplication.run(SpringApplication.java:1233)
[spring-boot-2.0.0.M4.jar:2.0.0.M4] at
com.vfraternity.VfSpringBootMain.main(VfSpringBootMain.java:12)
[classes/:na] Caused by: org.hibernate.AnnotationException: Unable to
map collection
com.vfraternity.process.entity.EntPropertyMaster.blockListPropSub at
org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1604)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.cfg.annotations.CollectionBinder.bindOneToManySecondPass(CollectionBinder.java:871)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.cfg.annotations.CollectionBinder.bindStarToManySecondPass(CollectionBinder.java:786)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.cfg.annotations.CollectionBinder$1.secondPass(CollectionBinder.java:725)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.cfg.CollectionSecondPass.doSecondPass(CollectionSecondPass.java:54)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1621)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.boot.internal.InFlightMetadataCollectorImpl.processSecondPasses(InFlightMetadataCollectorImpl.java:1589)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:278)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:858)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:885)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:57)
~[spring-orm-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:358)
~[spring-orm-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:384)
~[spring-orm-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:373)
~[spring-orm-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods AbstractAutowireCapableBeanFactory.java:1761)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] at
org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1698)
~[spring-beans-5.0.0.RC4.jar:5.0.0.RC4] ... 16 common frames omitted
Caused by: org.hibernate.cfg.RecoverableException: Unable to find
column with logical name: propertysubpk in
org.hibernate.mapping.Table(property_master) and its related
supertables and secondary tables at
org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:831)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.cfg.BinderHelper.createSyntheticPropertyReference(BinderHelper.java:243)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] at
org.hibernate.cfg.annotations.CollectionBinder.bindCollectionSecondPass(CollectionBinder.java:1594)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] ... 31 common frames
omitted Caused by: org.hibernate.MappingException: Unable to find
column with logical name: propertysubpk in
org.hibernate.mapping.Table(property_master) and its related
supertables and secondary tables at
org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:826)
~[hibernate-core-5.2.10.Final.jar:5.2.10.Final] ... 33 common frames
omitted
I tried to achive unidirectional using
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="propertysubfkid", referencedColumnName="propertysubpk")
private List<EntPropertySub> blockListPropSub = newArrayList<EntPropertySub>();
But it produces only error...
Here is my complete codes..
**EntPropertyMaster**
package com.vfraternity.process.entity;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;
#Entity
#Table(name="Property_Master")
public class EntPropertyMaster implements Serializable{
/**
*
*/
private static final long serialVersionUID = 6162594257264775391L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="propertyid")
private int property_id;
#NotNull
private String property_name;
#NotNull
private String address1;
#NotNull
#Column(columnDefinition="varchar(15) default'None'")
private String address2;
#NotNull
private String city;
#NotNull
private String state;
#NotNull
private String country;
#NotNull
private int zipcode;
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="propertysubfkid", referencedColumnName="propertysubpk")
private List<EntPropertySub> blockListPropSub = new ArrayList<EntPropertySub>();
#Version
private int version;
private Boolean is_active;
private String created_by;
private Date created_ts;
private String modified_by;
private Date modified_ts;
private String approved_by;
private Date approved_ts;
public EntPropertyMaster() {
}
//Getter Setter
public int getProperty_id() {
return property_id;
}
public void setProperty_id(int property_id) {
this.property_id = property_id;
}
public String getProperty_name() {
return property_name;
}
public void setProperty_name(String property_name) {
this.property_name = property_name;
}
public String getAddress1() {
return address1;
}
public void setAddress1(String address1) {
this.address1 = address1;
}
public String getAddress2() {
return address2;
}
public void setAddress2(String address2) {
this.address2 = address2;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public Boolean getIs_active() {
return is_active;
}
public void setIs_active(Boolean is_active) {
this.is_active = is_active;
}
public String getCreated_by() {
return created_by;
}
public void setCreated_by(String created_by) {
this.created_by = created_by;
}
public Date getCreated_ts() {
return created_ts;
}
public void setCreated_ts(Date created_ts) {
this.created_ts = created_ts;
}
public String getModified_by() {
return modified_by;
}
public void setModified_by(String modified_by) {
this.modified_by = modified_by;
}
public Date getModified_ts() {
return modified_ts;
}
public void setModified_ts(Date modified_ts) {
this.modified_ts = modified_ts;
}
public String getApproved_by() {
return approved_by;
}
public void setApproved_by(String approved_by) {
this.approved_by = approved_by;
}
public Date getApproved_ts() {
return approved_ts;
}
public void setApproved_ts(Date approved_ts) {
this.approved_ts = approved_ts;
}
public int getZipcode() {
return zipcode;
}
public void setZipcode(int zipcode) {
this.zipcode = zipcode;
}
public List<EntPropertySub> getBlockListPropSub() {
return blockListPropSub;
}
public void setBlockListPropSub(List<EntPropertySub> blockListPropSub) {
this.blockListPropSub = blockListPropSub;
}
}
/////////////////////////////////////////////////////////////
EntPropertySub
package com.vfraternity.process.entity;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import javax.persistence.Version;
import javax.validation.constraints.NotNull;
#Entity
#Table(name="propertysub")
public class EntPropertySub implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 810618405796553525L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="propertysubpk")
private int propertySub_pk;
#NotNull
private String blockname;
#NotNull
private int floors;
#NotNull
private String flatstart;
private String flatend;
#Version
private int version;
private Boolean is_active;
private String created_by;
private Date created_ts;
private String modified_by;
private Date modified_ts;
private String approved_by;
private Date approved_ts;
public EntPropertySub() {
}
//Getter Setter
public int getPropertySub_pk() {
return propertySub_pk;
}
public void setPropertySub_pk(int propertySub_pk) {
this.propertySub_pk = propertySub_pk;
}
public String getBlockname() {
return blockname;
}
public void setBlockname(String blockname) {
this.blockname = blockname;
}
public int getFloors() {
return floors;
}
public void setFloors(int floors) {
this.floors = floors;
}
public String getFlatstart() {
return flatstart;
}
public void setFlatstart(String flatstart) {
this.flatstart = flatstart;
}
public String getFlatend() {
return flatend;
}
public void setFlatend(String flatend) {
this.flatend = flatend;
}
public int getVersion() {
return version;
}
public void setVersion(int version) {
this.version = version;
}
public Boolean getIs_active() {
return is_active;
}
public void setIs_active(Boolean is_active) {
this.is_active = is_active;
}
public String getCreated_by() {
return created_by;
}
public void setCreated_by(String created_by) {
this.created_by = created_by;
}
public Date getCreated_ts() {
return created_ts;
}
public void setCreated_ts(Date created_ts) {
this.created_ts = created_ts;
}
public String getModified_by() {
return modified_by;
}
public void setModified_by(String modified_by) {
this.modified_by = modified_by;
}
public Date getModified_ts() {
return modified_ts;
}
public void setModified_ts(Date modified_ts) {
this.modified_ts = modified_ts;
}
public String getApproved_by() {
return approved_by;
}
public void setApproved_by(String approved_by) {
this.approved_by = approved_by;
}
public Date getApproved_ts() {
return approved_ts;
}
public void setApproved_ts(Date approved_ts) {
this.approved_ts = approved_ts;
}
}
Please help me to solve this..Thanks in advance
The cause of the error is:
Unable to find column with logical name: propertysubpk in org.hibernate.mapping.Table(property_master)
The reason is that you have the referencedColumnName attribute wrong. It is supposed to be:
JPA 2.1 11.1.25: The name of the column referenced
by this foreign key column. When
used with entity relationship mappings
other than the cases described below, the
referenced column is in the table of the target
entity. When used with a unidirectional
OneToMany foreign key mapping, the referenced
column is in the table of the
source entity. When used inside a Join-
Table annotation, the referenced key column
is in the entity table of the owning
entity, or inverse entity if the join is part of
the inverse join definition. When used in a
collection table mapping, the referenced
column is in the table of the entity containing
the collection.
To explain: a #JoinColumn creates a column in the many side of the relation (the EntPropertySub here) with the given name that references the PK of the parent entity, unless referencedColumnName is specified. In the latter case the FK in the "many" table references the column given in referencedColumnName. In your case you want to reference the PK of EntPropertyMaster, so referencedColumnName is redundant. Simply use:
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="propertysubfkid")
private List<EntPropertySub> blockListPropSub = newArrayList<EntPropertySub>();
Try this: make sure how the foreign key in the table EntPopertySub called
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="propertyid")
private List<EntPropertySub> blockListPropSub = new ArrayList<EntPropertySub>();
It's not possible to create a physical column on the master table because you have a OneToMany relation. OneToMany means that Master has many Sub Table references.
Let's explain the Problem:
If you would have a column in the master table you need to would add a list of references in one cell.
For Example
------------------
| sub-fk |
|1, 2, 3, 4| <-- and this is against the database normalization
But this is not necessary:
Hibernate will automatically select all the referenced sub-columns for you (intern hibernate joins to the columns)
If you use the entitymanager to select the master data, the sub-data is included in the List blockListPropSub attribute
When you use the #JoinColumn on a #OneToMany relationship, the name attribute will point to the relating tables column, that is EntPropertySub entity and the referencedColumnName should be pointing to the column of the entity in which the #OneToMany annotation is present, that is EntPropertyMaster.
So basically you have it other way round and it should be in my opinion:
#OneToMany(cascade=CascadeType.ALL)
#JoinColumn(name="propertysubpk", referencedColumnName="propertysubfkid")
private List<EntPropertySub> blockListPropSub = newArrayList<EntPropertySub>();
The error clearly shows mapping missing in your schema relation.
You need to map EntPropertyMaster in EntPropertySub.
#OneToMany(cascade=CascadeType.ALL, mappedBy="entPropertyMaster")
private List<EntPropertySub> blockListPropSub = newArrayList<EntPropertySub>();
Provide EntPropertyMaster mapping in relation entity too.i.e.
#ManyToOne
#JoinColumn(name="entPropertyMasterId",referencedColumnName="id")
private EntPropertyMaster entPropertyMaster;
Relationships in JPA are always unidirectional, unless you associate
the parent with the child in both directions. Cascading REMOVE
operations from the parent to the child will require a relation from
the parent to the child (not just the opposite).
Finnaly i got a answer..
i made a changes in master entity "EntPropertyMaster"
"#OneToMany(cascade=CascadeType.ALL)"
"#JoinColumn(name="propertyidfk")"
private List<EntPropertySub> blockListPropSub = new ArrayList<EntPropertySub>();
It will create column in child table,but i wrote this code in parent Entity...
Please Note we need to give unique name for column creation,Then only it creates a column in child table.... not a primarykey column name
of child /parent table..
I have problem trying authenticate user using spring security and extracting users from the db. I am using Postgres for this purpose and I am sure it is configured because I am able to manipulate entities from other tables. Here is the error I receive:
org.springframework.security.authentication.InternalAuthenticationServiceException: could not extract ResultSet
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:125)
at org.springframework.security.authentication.dao.AbstractUserDetailsAuthenticationProvider.authenticate(AbstractUserDetailsAuthenticationProvider.java:143)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:167)
at org.springframework.security.authentication.ProviderManager.authenticate(ProviderManager.java:192)
at org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter.attemptAuthentication(UsernamePasswordAuthenticationFilter.java:93)
at org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter.doFilter(AbstractAuthenticationProcessingFilter.java:217)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.authentication.logout.LogoutFilter.doFilter(LogoutFilter.java:120)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.csrf.CsrfFilter.doFilterInternal(CsrfFilter.java:120)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.header.HeaderWriterFilter.doFilterInternal(HeaderWriterFilter.java:64)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.SecurityContextPersistenceFilter.doFilter(SecurityContextPersistenceFilter.java:91)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.context.request.async.WebAsyncManagerIntegrationFilter.doFilterInternal(WebAsyncManagerIntegrationFilter.java:53)
at org.springframework.web.filter.OncePerRequestFilter.doFilter(OncePerRequestFilter.java:107)
at org.springframework.security.web.FilterChainProxy$VirtualFilterChain.doFilter(FilterChainProxy.java:330)
at org.springframework.security.web.FilterChainProxy.doFilterInternal(FilterChainProxy.java:213)
at org.springframework.security.web.FilterChainProxy.doFilter(FilterChainProxy.java:176)
at org.springframework.web.filter.DelegatingFilterProxy.invokeDelegate(DelegatingFilterProxy.java:344)
at org.springframework.web.filter.DelegatingFilterProxy.doFilter(DelegatingFilterProxy.java:261)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:503)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:421)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1070)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:611)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:314)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
at org.hibernate.exception.internal.SQLStateConversionDelegate.convert(SQLStateConversionDelegate.java:123)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:49)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:126)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:112)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:91)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.getResultSet(AbstractLoadPlanBasedLoader.java:449)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeQueryStatement(AbstractLoadPlanBasedLoader.java:202)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:137)
at org.hibernate.loader.plan.exec.internal.AbstractLoadPlanBasedLoader.executeLoad(AbstractLoadPlanBasedLoader.java:102)
at org.hibernate.loader.collection.plan.AbstractLoadPlanBasedCollectionInitializer.initialize(AbstractLoadPlanBasedCollectionInitializer.java:100)
at org.hibernate.persister.collection.AbstractCollectionPersister.initialize(AbstractCollectionPersister.java:693)
at org.hibernate.event.internal.DefaultInitializeCollectionEventListener.onInitializeCollection(DefaultInitializeCollectionEventListener.java:92)
at org.hibernate.internal.SessionImpl.initializeCollection(SessionImpl.java:1897)
at org.hibernate.collection.internal.AbstractPersistentCollection$4.doWork(AbstractPersistentCollection.java:558)
at org.hibernate.collection.internal.AbstractPersistentCollection.withTemporarySessionIfNeeded(AbstractPersistentCollection.java:260)
at org.hibernate.collection.internal.AbstractPersistentCollection.initialize(AbstractPersistentCollection.java:554)
at org.hibernate.collection.internal.AbstractPersistentCollection.read(AbstractPersistentCollection.java:142)
at org.hibernate.collection.internal.PersistentSet.iterator(PersistentSet.java:180)
at com.musala.ving.serviceimpl.MyUserDetailsService.buildUserAuthority(MyUserDetailsService.java:49)
at com.musala.ving.serviceimpl.MyUserDetailsService.loadUserByUsername(MyUserDetailsService.java:33)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:483)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:317)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:190)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:281)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:207)
at com.sun.proxy.$Proxy211.loadUserByUsername(Unknown Source)
at org.springframework.security.authentication.dao.DaoAuthenticationProvider.retrieveUser(DaoAuthenticationProvider.java:114)
... 40 more
Caused by: org.postgresql.util.PSQLException: ERROR: column userrole0_.user_id does not exist
Position: 8
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2198)
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:1927)
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:255)
at org.postgresql.jdbc2.AbstractJdbc2Statement.execute(AbstractJdbc2Statement.java:561)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeWithFlags(AbstractJdbc2Statement.java:419)
at org.postgresql.jdbc2.AbstractJdbc2Statement.executeQuery(AbstractJdbc2Statement.java:304)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:82)
... 69 more
Here is my User class:
import java.io.Serializable;
import java.util.HashSet;
import java.util.LinkedHashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "USERS")
public class User implements Serializable {
#Id
#Column(name = "USER_ID", unique = true, nullable = false)
private String userId;
#Column(name = "USER_NAME")
private String userName;
#Column(name = "PASSWORD")
private String password;
#Column(name = "FIRST_NAME")
private String firstName;
#Column(name = "LAST_NAME")
private String lastName;
#Column(name = "DEFAULT_ROOM")
private String defaultRoom;
#Column(name = "VOICEMAIL_BOX")
private String voicemailBox;
#ManyToMany(cascade = { CascadeType.ALL })
#JoinTable(name = "USERS_ROOMS", joinColumns = { #JoinColumn(name = "USER_ID") }, inverseJoinColumns = { #JoinColumn(name = "ROOM_ID") })
private Set<Room> rooms = new LinkedHashSet<Room>();
#OneToMany(cascade = { CascadeType.ALL })
#JoinColumn(name = "USER_ID")
private Set<Extension> extensions = new HashSet<Extension>();
#Column(name = "LOGIN_PIN")
private String loginPin;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "user")
private Set<UserRole> userRole = new HashSet<UserRole>(0);
#Column(name = "ENABLED")
private boolean enabled;
public User() {
super();
}
public User(String userId) {
this.userId = userId;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getVoicemailBox() {
return voicemailBox;
}
public void setVoicemailBox(String voicemailBox) {
this.voicemailBox = voicemailBox;
}
public Set<Room> getRooms() {
return rooms;
}
public void setRooms(Set<Room> rooms) {
this.rooms = rooms;
}
public Set<Extension> getExtensions() {
return extensions;
}
public void setExtensions(Set<Extension> extensions) {
this.extensions = extensions;
}
public String getDefaultRoom() {
return defaultRoom;
}
public void setDefaultRoom(String defaultRoom) {
this.defaultRoom = defaultRoom;
}
public String getLoginPin() {
return loginPin;
}
public void setLoginPin(String loginPin) {
this.loginPin = loginPin;
}
public Set<UserRole> getUserRole() {
return userRole;
}
public void setUserRole(Set<UserRole> userRole) {
this.userRole = userRole;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
My UserRole class:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "USER_ROLE")
public class UserRole {
private String id;
private User user;
private String role;
public UserRole() {
}
public UserRole(User user, String role) {
this.user = user;
this.role = role;
}
#Id
#Column(name = "ID", unique = true, nullable = false)
#GeneratedValue
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "USER_ID", nullable = false)
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getRole() {
return role;
}
#Column(name = "ROLE")
public void setRole(String role) {
this.role = role;
}
}
As a reference I used the following tutorial: http://www.mkyong.com/spring-security/spring-security-hibernate-annotation-example/
EDIT: creation of the tables:
1) user_role:
CREATE TABLE user_role
(
id character varying NOT NULL,
role character varying,
CONSTRAINT id PRIMARY KEY (id),
CONSTRAINT "user" FOREIGN KEY (id)
REFERENCES users (user_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
2) users:
CREATE TABLE users
(
id serial NOT NULL,
user_id character varying(16) NOT NULL,
user_name character varying(16),
password character varying(16),
first_name character varying(16),
last_name character varying(16),
voicemail_box character varying(16),
default_room character varying(16),
login_pin character varying(4),
enabled boolean,
CONSTRAINT users_pkey PRIMARY KEY (user_id),
CONSTRAINT users_fkey1 FOREIGN KEY (user_id)
REFERENCES user_settings (user_id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
Any answers are appreciated :) sorry if it is a duplicate question. I will mark it as duplicate as soon as I have a clue what causes the error. Thank you!
You need to do the following thing
CREATE TABLE user_role
(
id character varying NOT NULL,
role character varying,
user_id character varying,
CONSTRAINT id PRIMARY KEY (id),
CONSTRAINT "user" FOREIGN KEY (user_id)
REFERENCES users (id) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
What you were missing was user_id column which has to be the foreign key, right now you have mapped your id field from your user_role table as both primary and foreign key.