I'm trying to auto wire a repository for a simple springboot application. But When I start to do java -jar for my app it says: Field bugRepository in be.tquality.demospringdb.BugController required a bean of type 'be.tquality.demospringdb.BugRepository' that could not be found.
This is the bug repository:
package be.tquality.demospringdb;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
#Repository
public interface BugRepository extends JpaRepository<Bug, Long> {
}
and my controller
package be.tquality.demospringdb;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
public class BugController {
#Autowired
private BugRepository bugRepository;
#GetMapping(value = "bug/findall")
public List<Bug> findAll(){
return bugRepository.findAll();
}
}
And this my actual database class
package be.tquality.demospringdb;
import lombok.Data;
import javax.persistence.*;
import java.io.Serializable;
#Entity
#Table(name = "BUG")
#Data
public class Bug implements Serializable {
private static final long serialVersionUID = -2343243243242432341L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column(name = "TESTCASEID")
private int testcaseid;
#Column(name = "TESTSTEPID")
private int teststepid;
#Column(name = "TITLE")
private String title;
#Column(name = "DESCRIPTION")
private String description;
#Column(name = "STATUS")
private int status;
#Column(name = "ASSIGNEE")
private int assignee;
#Column(name = "PROJECTID")
private int projectid;
#Column(name = "EXPECTEDRESULT")
private String expectedresult;
#Column(name = "ACTUALRESULT")
private String actualresult;
public Bug(){}
public Bug(int testcaseid, int teststepid, String title, String description, int status,int assignee,int projectid,
String expectedresult,String actualresult) {
this.testcaseid = testcaseid;
this.teststepid = teststepid;
this.title = title;
this.description = description;
this.status = status;
this.assignee = assignee;
this.projectid = projectid;
this.expectedresult = expectedresult;
this.actualresult = actualresult;
}
}
I really don't see what I'm doing wrong and why it cannot connect to the repository. As in my ide it can connect easily
The part that's start issues when I run java -jar is
2022-11-15 14:45:27.901 WARN 32225 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'bugController': Unsatisfied dependency expressed through field 'bugRepository'; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No qualifying bean of type 'be.tquality.demospringdb.BugRepository' available: expected at least 1 bean which qualifies as autowire candidate. Dependency annotations: {#org.springframework.beans.factory.annotation.Autowired(required=true)}
2022-11-15 14:45:27.905 INFO 32225 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2022-11-15 14:45:28.035 INFO 32225 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-11-15 14:45:28.095 ERROR 32225 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Field bugRepository in be.tquality.demospringdb.BugController required a bean of type 'be.tquality.demospringdb.BugRepository' that could not be found.
The injection point has the following annotations:
- #org.springframework.beans.factory.annotation.Autowired(required=true)
Action:
Consider defining a bean of type 'be.tquality.demospringdb.BugRepository' in your configuration.
My spring boot application
package be.tquality.demospringdb;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class DemospringdbApplication {
public static void main(String[] args) {
SpringApplication.run(DemospringdbApplication.class, args);
}
}
Related
Created a new application with CrudRepository and mysql database. I try to launch the application, but the "A component required a bean named 'entityManagerFactory' that could not be found." error falls. I read other people's questions and answers, but I did not find a suitable one for my problem.
build.gradle
plugins {
id 'java'
id 'org.springframework.boot' version '2.7.5-SNAPSHOT'
id 'io.spring.dependency-management' version '1.1.0'
id "org.hibernate.orm" version "6.1.6.Final"
}
group = 'c'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
maven { url 'https://repo.spring.io/milestone' }
maven { url 'https://repo.spring.io/snapshot' }
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-security'
implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springframework.boot:spring-boot-starter-data-jpa'
implementation group: 'org.springframework.security.oauth', name: 'spring-security-oauth2', version: '2.5.2.RELEASE'
implementation group: 'mysql', name: 'mysql-connector-java', version: '8.0.31'
implementation group: 'org.json', name: 'json', version: '20220924'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
}
targetCompatibility = JavaVersion.VERSION_11
application.properties
spring.datasource.url=jdbc:mysql://localhost:3306/fgfg
spring.datasource.username=
spring.datasource.password=
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.jpa.database-platform=org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.generate-ddl=true
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.format_sql=true
spring.jpa.properties.hibernate.enable_lazy_load_no_trans=true
UserRepository.java
import dataox.backhttpsbitbucket.orgintrolabsystemsfrontamirsharerbiz.entities.UserEntity;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import java.util.Optional;
public interface UserRepository extends CrudRepository<UserEntity, Long> {
#Query("select u from UserEntity u where u.password = ?1 and u.email = ?2")
Optional<UserEntity> findByPasswordAndEmail(String password, String email);
}
UserEntity.java
import lombok.*;
import javax.persistence.*;
import java.time.LocalDateTime;
#Builder
#AllArgsConstructor
#NoArgsConstructor
#Getter
#Setter
#Entity
public class UserEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
private String name;
private String industry;
private String currentCompany;
private String currentPosition;
private String photoUrl;
private String linkedLink;
private Long linkedId;
private String phoneNumber;
private String email;
private String password;
private LocalDateTime registeredAt;
#Enumerated(EnumType.STRING)
#Column(name = "user_role")
private UserRole userRole;
Application
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
I tried fix application.properties with
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
I tried to use JpaRepository instead CrudRepository.
And after all I have this error:
2022-12-20 16:15:41.302 WARN 90827 --- [ main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'userRepository' defined in dataox.backhttpsbitbucket.orgintrolabsystemsfrontamirsharerbiz.repositories.UserRepository defined in #EnableJpaRepositories declared on JpaRepositoriesRegistrar.EnableJpaRepositoriesConfiguration: Cannot create inner bean '(inner bean)#602f8f94' of type [org.springframework.orm.jpa.SharedEntityManagerCreator] while setting bean property 'entityManager'; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name '(inner bean)#602f8f94': Cannot resolve reference to bean 'entityManagerFactory' while setting constructor argument; nested exception is org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available
2022-12-20 16:15:41.305 INFO 90827 --- [ main] o.apache.catalina.core.StandardService : Stopping service [Tomcat]
2022-12-20 16:15:41.316 INFO 90827 --- [ main] ConditionEvaluationReportLoggingListener :
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2022-12-20 16:15:41.330 ERROR 90827 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
A component required a bean named 'entityManagerFactory' that could not be found.
Action:
Consider defining a bean named 'entityManagerFactory' in your configuration.
> Task :Application.main() FAILED
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':Application.main()'.
> Process 'command '/opt/idea/jbr/bin/java'' finished with non-zero exit value 1
Try adding #EnableTransactionManagement to your #SpringBootConfiguration class.
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#EnableTransactionManagement
#SpringBootApplication
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
I'm getting this error while adding to the candidates table.candidates table extends the users table. Email and password columns come from this table.I think there is a problem with the database, I am using postreSql. What would be the reason ?
User Table
package com.example.hrmsdemo.entities.concretes;
import com.sun.istack.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import javax.persistence.*;
#Data
#Entity
#AllArgsConstructor
#NoArgsConstructor
#Table(name="users",uniqueConstraints = {#UniqueConstraint(columnNames = {"email"})})
#Inheritance(strategy = InheritanceType.JOINED)
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#NotNull
private int id;
#Column(name = "email")
#NotNull
private String email;
#NotNull
#Column(name = "password")
private String password;
}
Candidate Table
package com.example.hrmsdemo.entities.concretes;
import com.sun.istack.NotNull;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import org.springframework.format.annotation.DateTimeFormat;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import java.util.Date;
#Data
#AllArgsConstructor
#NoArgsConstructor
#Table(name="candidates",uniqueConstraints = {#UniqueConstraint(columnNames = {"identity_number"})})
#EqualsAndHashCode(callSuper = true)
#Entity
public class Candidate extends User {
#Column(name = "first_name")
#NotNull
private String first_name;
#NotNull
#Column(name = "last_name")
private String last_name;
#NotNull
#Column(name = "identity_number")
private String identity_number;
#NotNull
#DateTimeFormat(pattern = "yyyy-MM-dd")
#Column(name = "birth_date")
private Date birth_date;
}
Error
2021-05-26 15:59:53.230 WARN 24964 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 0, SQLState: 23502
2021-05-26 15:59:53.230 ERROR 24964 --- [nio-8080-exec-3] o.h.engine.jdbc.spi.SqlExceptionHelper : HATA: null value in column "email_address" of relation "users" violates not-null constraint
Ayrıntı: Hata veren satır (7, null, 123414, veyselhim#gmail.com) içeriyor.
2021-05-26 15:59:53.245 ERROR 24964 --- [nio-8080-exec-3] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [email_address" of relation "users]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
I assume you really map User#email to a column named email_address? That is the column that the database is complaining about but you do not show a mapping to that column.
Assuming that is true, you have defined that this attribute should be non-null which also seems to be how the database is defined. This would suggest that you are trying to save a User and did not set its email property.
Or maybe you really have not mapped that column and so Hibernate never tries to write to it. Hard to tell from just what you have given us.
I'm getting this error in a SpringBoot project. The query I'm running is working up until the point when I try to save a Consumer entity to the Spring JPA database.
Have you any ideas on how to fix this?? I think it might be to do with the way the classes are set up.
ERROR MESSAGE:
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
javax.persistence.PersistenceException: [PersistenceUnit: default]
Unable to build Hibernate SessionFactory; nested exception is
org.hibernate.MappingException: Could not determine type for:
com.fintechbankapi.Consumer.KYCNote, at table: consumer_kyc_notes, for
columns: [org.hibernate.mapping.Column(kyc_notes)]
CLASSES BELOW - I have included no argument constructor, constructor with arguments and getters and setters in each class.
import java.util.ArrayList;
import java.util.List;
import javax.persistence.ElementCollection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.Id;
//Object to store a Consumer's details.
#Entity
public class Consumer {
//variables
#Id
private String user_id;
#ElementCollection
private List<String> digital_footprint = new ArrayList<String>();
#ElementCollection
private List<String> contact_id = new ArrayList<String>();
#ElementCollection
private List<Contact> contacts = new ArrayList<Contact>();
#Embedded
private KYC kyc;
#ElementCollection
private List<KYCNote> kyc_notes = new ArrayList<KYCNote>();
private String address_id;
#ElementCollection
private List<Address> addresses = new ArrayList<Address>();
}
public class KYCNote {
//variables
private String code;
private String detail;
}
#Embeddable
public class KYC {
//variables
#Column(name="status")
private String status;
//An array containing information required to be verified. Will only be
//present if kyc.status = "review".
#Column(name="idv_required")
#ElementCollection
List<String> idv_required = new ArrayList<String>();
}
public class Contact {
//variables
private String id;
}
public class Address {
//variables
private String id;
}
Any help appreciated. Thanks.
Have you tried adding the following to your application.properties file?
"spring.jpa.hibernate.use-new-id-generator-mappings= false" ...
I have seen some questions on this subject but I have not got any valid solution for my case
I'm having an exception with jason serialization I have the following classes
when I do a GET Pacientes I have an exception of the serialization privilege type
2017-11-14 08:54:35.039 INFO 8724 --- [nio-8080-exec-1] o.h.e.internal.DefaultLoadEventListener : HHH000327: Error performing load command : org.hibernate.type.SerializationException: could not deserialize
2017-11-14 08:54:35.047 ERROR 8724 --- [nio-8080-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not deserialize; nested exception is org.hibernate.type.SerializationException: could not deserialize] with root cause
java.io.EOFException: null
at java.io.ObjectInputStream$PeekInputStream.readFully(Unknown Source) ~[na:1.8.0_144]
at java.io.ObjectInputStream$BlockDataInputStream.readShort(Unknown Source) ~[na:1.8.0_144]
at java.io.ObjectInputStream.readStreamHeader(Unknown Source) ~[na:1.8.0_144]
at java.io.ObjectInputStream.<init>(Unknown Source) ~[na:1.8.0_144]
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:309) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:299) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:218) ~[hibernate-core-5.0.12.Final.jar:5.0.12.Final]
I'm using framwork Spring boot with spring data jpa
class Paciente
import java.io.Serializable;
import java.math.BigInteger;
import javax.persistence.Basic;
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.ManyToOne;
import javax.persistence.Table;
import digifred.model.global.Entidades;
import digifred.model.global.IdentidadesGenero;
import digifred.model.global.OrientacoesSexuais;
import digifred.model.global.Pessoas;
#Entity
#Table(name = "pacientes", schema = "sau")
public class Pacientes implements Serializable {
private static final long serialVersionUID = 5776384003601026304L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idPaciente")
private Long idPaciente;
#JoinColumn(name="id_entidade")
#ManyToOne(cascade = CascadeType.ALL)
private Entidades entidade;
#Basic(optional = false)
#JoinColumn(name="idPessoa")
#ManyToOne(cascade = CascadeType.ALL)
private Pessoas pessoa;
#Column(name = "idResponsavel_familiar")
private BigInteger responsavelFamiliar;
#Column(name = "nomeResponsavel")
private String nomeResponsavel;
#Column(name = "cpfResponsavel")
private String cpfResponsavel;
#Column(name = "cnsResponsavel")
private String cnsResponsavel;
#Column(name = "flagAlergico")
private Integer flagAlergico;
#Column(name = "observacoesAlergias")
private String observacoesAlergias;
#Column(name = "microarea")
private String microarea;
#Column(name = "idDomicilio")
private Long idDomicilio;
#JoinColumn(name="idOrientacaoSexual")
#ManyToOne
private OrientacoesSexuais orientacaoSexual;
#JoinColumn(name="idIdentidadeGenero", insertable=false, updatable=false)
#ManyToOne
private IdentidadesGenero identidadeGenero;
#Basic(optional = false)
#Column(name = "flag_ativo")
private int flagAtivo;
#JoinColumn(name="idArea")
#ManyToOne
private Areas area;
#JoinColumn(name="idFamilia")
#ManyToOne
private Familias familia;
public Pacientes() {
}
getters and setters
}
Looks like you're trying to deserialize an empty stream.
You can’t simply transfer database entities over a REST interface, you have to create DTOs and transfer them instead of your entities.
For me, the cause was using #Column instead of #JoinColumn on an association. Was able to find out by turning on logging for the queries being run:
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.springframework.transaction=DEBUG
logging.level.org.hibernate=DEBUG
logging.level.org.hibernate.SQL=debug
logging.level.org.hibernate.type.descriptor.sql=trace
tbh, not sure which of those properties are actually needed, but I found them on some other SO question and just turn them all on when debugging. In the logs I saw a line for each of the columns that were fetched and the last one logged before the exception I was getting was the column value for the association where I had the wrong annotation.
I have a groovy entity ClientInvoiceAttachmentExt which extends java entity ClientInvoiceAttachment. The ClientInvoiceAttachment has #Id annotation but still am seeing the "No identifier specified for entity" error
Here is my stack trace
[Mar 03 17:11:54] ERROR | org.springframework.web.context.ContextLoader | Context initialization failed
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'collaborationAPI': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.dc.apps.collaborationportal.security.service.CollaborationSecurityService com.dc.apps.collaborationportal.core.api.CollaborationAPI.security; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'collaborationSecurityService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: protected com.dc.apps.collaborationportal.feature.service.FeatureService com.dc.apps.collaborationportal.security.service.CollaborationSecurityService.featureService; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'featureService': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private com.dc.core.api.Services com.dc.apps.collaborationportal.feature.service.FeatureService.api; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'services': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: public com.dc.core.api.SearchAPI com.dc.core.api.Services.search; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'searchAPI': Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException: Could not autowire field: private transient org.hibernate.SessionFactory com.dc.core.entity.service.impl.QueryService.sessionFactory; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'sessionFactory' defined in ServletContext resource [/WEB-INF/applicationContext.xml]: Invocation of init method failed; nested exception is com.dc.core.common.exception.BaseApplicationException: org.hibernate.AnnotationException: No identifier specified for entity: com.dc.apps.collaborationportal.ebilling.model.impl.ClientInvoiceAttachmentExt
Caused by: org.hibernate.AnnotationException: No identifier specified for entity: com.dc.apps.collaborationportal.ebilling.model.impl.ClientInvoiceAttachmentExt
at org.hibernate.cfg.InheritanceState.determineDefaultAccessType(InheritanceState.java:268)
at org.hibernate.cfg.InheritanceState.getElementsToProcess(InheritanceState.java:223)
at org.hibernate.cfg.AnnotationBinder.bindClass(AnnotationBinder.java:686)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processAnnotatedClassesQueue(Configuration.java:4035)
at org.hibernate.cfg.Configuration$MetadataSourceQueue.processMetadata(Configuration.java:3989)
at org.hibernate.cfg.Configuration.secondPassCompile(Configuration.java:1398)
at org.hibernate.cfg.Configuration.buildMappings(Configuration.java:1375)
at org.springframework.orm.hibernate3.LocalSessionFactoryBean.buildSessionFactory(LocalSessionFactoryBean.java:720)
at com.dc.core.entity.support.CustomFieldsSessionFactoryBean.buildSessionFactory(CustomFieldsSessionFactoryBean.java:252)
... 94 more
My pom dependancies
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>3.6.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-search</artifactId>
<!-- this is the latest version that works with lucene-core 3.0.3
(which we are stuck with until jackrabbit supports later versions) -->
<version>3.3.0.Final</version>
<scope>provided</scope>
<exclusions>
<exclusion>
<groupId>xml-apis</groupId>
<artifactId>xml-apis</artifactId>
</exclusion>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
</exclusion>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>ejb3-persistence</artifactId>
</exclusion>
<exclusion>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-commons-annotations</artifactId>
</exclusion>
<exclusion>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
</exclusion>
</exclusions>
</dependency>
Here is my Java class
package com.dc.apps.collaborationportal.ebilling.model.impl;
import javax.persistence.AssociationOverride;
import javax.persistence.Embedded;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Transient;
import org.hibernate.annotations.Entity;
import com.dc.core.common.annotations.AttributeMetadataDefaults;
import com.dc.core.common.annotations.EventDefaults;
import com.dc.core.common.annotations.EventHandlerDefaults;
import com.dc.core.entity.model.IPersistentEntityInstance;
import com.dc.core.entity.model.impl.File;
import com.dc.core.events.enums.EventTypeEnum;
import com.dc.core.security.annotation.AttributeReadPermission;
import com.dc.core.security.annotation.AttributeWritePermission;
import com.dc.core.security.annotation.ContainerReference;
#Entity
#EventDefaults({
#EventHandlerDefaults(eventType = EventTypeEnum.OnBeforeCreate, beanName = "checksumInvoiceAttachmentCommand"),
#EventHandlerDefaults(eventType = EventTypeEnum.OnBeforeCreate, beanName = "encryptInvoiceAttachmentCommand") })
public class ClientInvoiceAttachment implements IPersistentEntityInstance {
private static final long serialVersionUID = 1L;
private Long id;
private File attachment;
private String checksum;
private String invoiceNumber;
#Embedded
#AssociationOverride(name = "fileData", joinColumns = #JoinColumn(name = "attachment_file_data_id"))
public File getAttachment() {
return attachment;
}
public String getChecksum() {
return checksum;
}
#Transient
#AttributeMetadataDefaults(defaultDisplay = true)
public String getFileName() {
if (attachment == null) return "";
return attachment.getName();
}
#Id
#GeneratedValue
public Long getId() {
return id;
}
public String getInvoiceNumber() {
return invoiceNumber;
}
public void setAttachment(File attachment) {
this.attachment = attachment;
}
public void setChecksum(String checksum) {
this.checksum = checksum;
}
public void setId(Long id) {
this.id = id;
}
public void setInvoiceNumber(String invoiceNumber) {
this.invoiceNumber = invoiceNumber;
}
}
Here is my groovy class
package com.dc.apps.collaborationportal.ebilling.model.impl
import com.dc.core.api.Services;
import java.util.List
import javax.persistence.Column
import javax.persistence.OneToMany
import javax.persistence.ManyToMany
import javax.persistence.ManyToOne
import javax.persistence.Cacheable
import javax.persistence.Transient
import javax.persistence.JoinColumn
import javax.persistence.Embedded
import javax.persistence.Id
import javax.persistence.GeneratedValue
import javax.persistence.OneToOne
import javax.persistence.AssociationOverride
import javax.persistence.Lob
import javax.persistence.FetchType
import javax.persistence.Entity
import org.hibernate.search.annotations.DocumentId;
import org.hibernate.search.annotations.Indexed
import org.hibernate.search.annotations.Field;
import org.hibernate.search.annotations.Index;
import org.hibernate.search.annotations.Store;
import org.hibernate.annotations.NamedQueries
import org.hibernate.annotations.NamedQuery
import org.hibernate.envers.Audited
import org.hibernate.envers.NotAudited
import org.hibernate.annotations.Cascade
import org.hibernate.annotations.Type
//import org.hibernate.annotations.Index
import org.hibernate.annotations.LazyCollection
import org.hibernate.annotations.LazyCollectionOption
import org.hibernate.annotations.Formula
import org.hibernate.annotations.Fetch
import org.hibernate.annotations.FetchMode
import org.hibernate.annotations.BatchSize
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.context.ApplicationContext
import org.springframework.context.ApplicationContextAware
import org.springframework.beans.BeansException
import com.dc.core.entity.enums.VersionStatusEnum
import com.dc.core.behavior.command.model.ICommandResult
import com.dc.core.behavior.command.model.impl.CommandResult
import com.dc.core.behavior.command.model.IEntityInstanceCommand
import com.dc.core.entity.model.IPersistentEntityInstance
import com.dc.core.behavior.trackchanges.model.IEntityChangeset
import com.dc.core.security.model.IContainer
import com.dc.core.security.annotation.ContainerReference
import com.dc.core.security.annotation.Encrypted
import com.dc.core.collaboration.enums.CollaborationRequestStatus
import com.dc.core.collaboration.model.ICollaborationParcel
import com.dc.core.collaboration.model.ICollaborationFeatureDetail
import org.hibernate.annotations.Cache
import org.hibernate.annotations.CacheConcurrencyStrategy
#javax.persistence.Entity
class ClientInvoiceAttachmentExt extends com.dc.apps.collaborationportal.ebilling.model.impl.ClientInvoiceAttachment implements IAmGroovy, Serializable {
#Autowired
protected transient Services services;
private static final long serialVersionUID = 711967972L;
public java.lang.String getCreatedBy() {
return this.createdBy;
}
public void setCreatedBy(java.lang.String createdBy) {
this.createdBy = createdBy;
}
protected createdBy;
public java.lang.String getUpdatedBy() {
return this.updatedBy;
}
public void setUpdatedBy(java.lang.String updatedBy) {
this.updatedBy = updatedBy;
}
protected updatedBy;
public java.sql.Timestamp getCreatedAt() {
return this.createdAt;
}
public void setCreatedAt(java.sql.Timestamp createdAt) {
this.createdAt = createdAt;
}
protected createdAt;
public java.sql.Timestamp getUpdatedAt() {
return this.updatedAt;
}
public void setUpdatedAt(java.sql.Timestamp updatedAt) {
this.updatedAt = updatedAt;
}
protected updatedAt;
protected transient ApplicationContext applicationContext;
}
Your problem scenario is of Inheritance Mapping. The Id field is there in your super class but what about your child class, how they will be related to their parent.
There are different strategy to map an Inheritance hierarchy.
Using Discriminator value (Single Table)
Table per concrete class
Table per Child class (if parent is an abstract)
I think you are missing annotations related to above.
In Discriminator based approach.. You need to annotate your ParentClass as follows:
#Inheritance(strategy=InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name="type",discriminatorType=DiscriminatorType.STRING)
#DiscriminatorValue(value="ParentClass")
And in you child class:
#DiscriminatorValue("childClasss")
Please refer some tutorial on Inheritance Mapping like this one or you can google it.
There is a new annotation #MappedSuperclass that you add to the base class and it only affects the OOP without the need to change the DB. That is what I was looking for. You can read more about it in this post
I got the same error while working with JPA & I have added the #Id annotation,
While working with JPA, kindly make sure that this #Id annotation should be from package javax.persistence.Id & not from org.springframework.data.annotation.Id.
Hope it can save your precious time.
I saw the similar error. In case you have a Class which has a one to one relation with other class , that other class should have a Primary key as an identifier. (My app was using spring boot,jpa,h2,lombok)
Ex:
#Entity
#Getter
#Setter
Class A{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="b")
public B b;
}
Now the similar error might be raised if you missed writing the primary key or an identifier for the class B which is shown below
#Entity
#Getter
#Setter
Class b{
/* Same error may be raised when he below code is missing*/
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long b_id;
#OneToOne(mappedBy = "bid")
public A a;
}