Spring Boot Data JPA сaused by: Error accessing field - postgresql

community!
I get an error (Error accessing field) when in application.properties I change the value (spring.jpa.hibernate.ddl-auto) from create-drop to validate or update.
The error occurs when I try to get the OwnerProfile object from the database.
I use:
spring boot: 2.4.1
postgresql driver: 42.2.5
Caused by: org.springframework.orm.jpa.JpaSystemException: Error accessing field [private java.lang.Long giveawaystatistics.model.OwnerProfile.pk] by reflection for persistent property [giveawaystatistics.model.OwnerProfile#pk] : 1; nested exception is org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Long giveawaystatistics.model.OwnerProfile.pk] by reflection for persistent property [giveawaystatistics.model.OwnerProfile#pk] : 1
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.convertHibernateAccessException(HibernateJpaDialect.java:331) ~[spring-orm-5.3.2.jar:5.3.2]
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:233) ~[spring-orm-5.3.2.jar:5.3.2]
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:551) ~[spring-orm-5.3.2.jar:5.3.2]
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:61) ~[spring-tx-5.3.2.jar:5.3.2]
at org.springframework.dao.support.DataAccessUtils.translateIfNecessary(DataAccessUtils.java:242) ~[spring-tx-5.3.2.jar:5.3.2]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:152) ~[spring-tx-5.3.2.jar:5.3.2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.data.jpa.repository.support.CrudMethodMetadataPostProcessor$CrudMethodMetadataPopulatingMethodInterceptor.invoke(CrudMethodMetadataPostProcessor.java:145) ~[spring-data-jpa-2.4.2.jar:2.4.2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:97) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:215) ~[spring-aop-5.3.2.jar:5.3.2]
at com.sun.proxy.$Proxy98.findOwnerProfileByPk(Unknown Source) ~[na:na]
at com.gmail.andreyzarazka.giveawaystatistics.service.impl.OwnerProfileServiceImpl.info(OwnerProfileServiceImpl.java:50) ~[classes/:na]
at com.gmail.andreyzarazka.giveawaystatistics.GiveawayStatisticsApp.lambda$commandLineRunner$0(GiveawayStatisticsApp.java:44) ~[classes/:na]
at org.springframework.boot.SpringApplication.callRunner(SpringApplication.java:804) ~[spring-boot-2.4.1.jar:2.4.1]
... 10 common frames omitted
Caused by: org.hibernate.property.access.spi.PropertyAccessException: Error accessing field [private java.lang.Long giveawaystatistics.model.OwnerProfile.pk] by reflection for persistent property [giveawaystatistics.model.OwnerProfile#pk] : 1
at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:75) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.tuple.component.AbstractComponentTuplizer.getPropertyValue(AbstractComponentTuplizer.java:59) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.type.ComponentType.getPropertyValue(ComponentType.java:419) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.type.ComponentType.getHashCode(ComponentType.java:246) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.spi.EntityUniqueKey.generateHashCode(EntityUniqueKey.java:67) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.spi.EntityUniqueKey.<init>(EntityUniqueKey.java:48) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.type.EntityType.loadByUniqueKey(EntityType.java:748) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.type.EntityType.resolve(EntityType.java:467) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.internal.TwoPhaseLoad$EntityResolver.lambda$static$0(TwoPhaseLoad.java:605) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntityEntryLoadedState(TwoPhaseLoad.java:248) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:182) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.internal.TwoPhaseLoad.initializeEntity(TwoPhaseLoad.java:151) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.initializeEntitiesAndCollections(Loader.java:1200) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.processResultSet(Loader.java:1001) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.doQuery(Loader.java:959) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:349) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2850) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.doList(Loader.java:2832) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2664) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.Loader.list(Loader.java:2659) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:506) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:400) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:219) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1414) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1625) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1593) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.query.internal.AbstractProducedQuery.getSingleResult(AbstractProducedQuery.java:1641) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at org.hibernate.query.criteria.internal.compile.CriteriaQueryTypeQueryAdapter.getSingleResult(CriteriaQueryTypeQueryAdapter.java:111) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method) ~[na:na]
at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:64) ~[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:564) ~[na:na]
at org.springframework.orm.jpa.SharedEntityManagerCreator$DeferredQueryInvocationHandler.invoke(SharedEntityManagerCreator.java:406) ~[spring-orm-5.3.2.jar:5.3.2]
at com.sun.proxy.$Proxy115.getSingleResult(Unknown Source) ~[na:na]
at org.springframework.data.jpa.repository.query.JpaQueryExecution$SingleEntityExecution.doExecute(JpaQueryExecution.java:196) ~[spring-data-jpa-2.4.2.jar:2.4.2]
at org.springframework.data.jpa.repository.query.JpaQueryExecution.execute(JpaQueryExecution.java:88) ~[spring-data-jpa-2.4.2.jar:2.4.2]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.doExecute(AbstractJpaQuery.java:155) ~[spring-data-jpa-2.4.2.jar:2.4.2]
at org.springframework.data.jpa.repository.query.AbstractJpaQuery.execute(AbstractJpaQuery.java:143) ~[spring-data-jpa-2.4.2.jar:2.4.2]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.doInvoke(RepositoryMethodInvoker.java:137) ~[spring-data-commons-2.4.2.jar:2.4.2]
at org.springframework.data.repository.core.support.RepositoryMethodInvoker.invoke(RepositoryMethodInvoker.java:121) ~[spring-data-commons-2.4.2.jar:2.4.2]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.doInvoke(QueryExecutorMethodInterceptor.java:152) ~[spring-data-commons-2.4.2.jar:2.4.2]
at org.springframework.data.repository.core.support.QueryExecutorMethodInterceptor.invoke(QueryExecutorMethodInterceptor.java:131) ~[spring-data-commons-2.4.2.jar:2.4.2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.data.projection.DefaultMethodInvokingMethodInterceptor.invoke(DefaultMethodInvokingMethodInterceptor.java:80) ~[spring-data-commons-2.4.2.jar:2.4.2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:123) ~[spring-tx-5.3.2.jar:5.3.2]
at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:388) ~[spring-tx-5.3.2.jar:5.3.2]
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:119) ~[spring-tx-5.3.2.jar:5.3.2]
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:186) ~[spring-aop-5.3.2.jar:5.3.2]
at org.springframework.dao.support.PersistenceExceptionTranslationInterceptor.invoke(PersistenceExceptionTranslationInterceptor.java:137) ~[spring-tx-5.3.2.jar:5.3.2]
... 20 common frames omitted
Caused by: java.lang.IllegalArgumentException: Can not set java.lang.Long field giveawaystatistics.model.OwnerProfile.pk to java.lang.Long
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:167) ~[na:na]
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.throwSetIllegalArgumentException(UnsafeFieldAccessorImpl.java:171) ~[na:na]
at java.base/jdk.internal.reflect.UnsafeFieldAccessorImpl.ensureObj(UnsafeFieldAccessorImpl.java:58) ~[na:na]
at java.base/jdk.internal.reflect.UnsafeObjectFieldAccessorImpl.get(UnsafeObjectFieldAccessorImpl.java:36) ~[na:na]
at java.base/java.lang.reflect.Field.get(Field.java:419) ~[na:na]
at org.hibernate.property.access.spi.GetterFieldImpl.get(GetterFieldImpl.java:71) ~[hibernate-core-5.4.25.Final.jar:5.4.25.Final]
... 69 common frames omitted
My application.properties file looks like this
spring.datasource.url=jdbc:postgresql://localhost:5432/gsdb
spring.datasource.username=postgres
spring.datasource.password=postgres
spring.jpa.hibernate.ddl-auto=validate
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.properties.hibernate.format_sql=true
#Entity(name = "OwnerProfile")
#Table(name = "owner_profile",
uniqueConstraints = {
#UniqueConstraint(
name = "owner_profile_pk_unique",
columnNames = "pk"),
#UniqueConstraint(
name = "owner_profile_username_unique",
columnNames = "username")})
public class OwnerProfile implements Serializable {
#Id
#SequenceGenerator(
name = "owner_profile_sequence",
sequenceName = "owner_profile_sequence",
allocationSize = 1)
#GeneratedValue(
strategy = SEQUENCE,
generator = "owner_profile_sequence")
#Column(
name = "id",
updatable = false)
private Long id;
#Column(
name = "pk",
nullable = false,
updatable = false)
private Long pk;
#Column(
name = "username",
nullable = false,
columnDefinition = "TEXT")
private String username;
#Column(
name = "profile_pic_url",
nullable = false,
columnDefinition = "TEXT")
private String profilePicUrl;
#Column(
name = "phone_number",
nullable = true,
columnDefinition = "TEXT")
private String phoneNumber;
#OneToOne(
mappedBy = "ownerProfile",
cascade = CascadeType.ALL,
fetch = FetchType.EAGER)
private Company company;
public OwnerProfile() {
}
public OwnerProfile(SelfProfile profile) {
this.pk = profile.getPk();
this.username = profile.getUsername();
this.profilePicUrl = profile.getProfilePicUrl();
this.phoneNumber = profile.getPhoneNumber();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getPk() {
return pk;
}
public void setPk(Long pk) {
this.pk = pk;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getProfilePicUrl() {
return profilePicUrl;
}
public void setProfilePicUrl(String profilePicUrl) {
this.profilePicUrl = profilePicUrl;
}
public String getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public Company getCompany() {
return company;
}
public void setCompany(Company company) {
this.company = company;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Company)) return false;
Company company = (Company) o;
return getId().equals(company.getId())
&& getPk().equals(company.getPk())
&& getUsername().equals(company.getUsername());
}
#Override
public int hashCode() {
return Objects.hash(getId(), getPk(), getUsername());
}
#Override
public String toString() {
return "OwnerProfileService{" +
"id=" + id +
", pk=" + pk +
", username='" + username + '\'' +
", profilePicUrl='" + profilePicUrl + '\'' +
", phoneNumber='" + phoneNumber + '\'' +
'}';
}
}
#Entity(name = "Company")
#Table(
name = "company",
uniqueConstraints = {
#UniqueConstraint(
name = "company_pk_unique",
columnNames = "pk"),
#UniqueConstraint(
name = "company_username_unique",
columnNames = "username")})
public class Company implements Serializable {
#Id
#SequenceGenerator(
name = "company_sequence",
sequenceName = "company_sequence",
allocationSize = 1)
#GeneratedValue(
strategy = SEQUENCE,
generator = "company_sequence")
#Column(
name = "id",
updatable = false)
private Long id;
#Column(
name = "pk",
nullable = false,
updatable = false)
private Long pk;
#Column(
name = "username",
nullable = false,
columnDefinition = "TEXT")
private String username;
#Column(
name = "full_name",
nullable = true,
columnDefinition = "TEXT")
private String fullName;
#Column(
name = "profile_pic_url",
nullable = false,
columnDefinition = "TEXT")
private String profilePicUrl;
#Column(
name = "profile_pic_id",
nullable = true,
columnDefinition = "TEXT")
private String profilePicId;
#Column(
name = "following_count",
nullable = false)
private Integer followingCount;
#Column(
name = "biography",
nullable = true,
columnDefinition = "TEXT")
private String biography;
#Column(
name = "account_type",
nullable = false)
private Integer accountType;
#Column(
name = "is_private",
nullable = false,
columnDefinition = "boolean default false")
private Boolean isPrivate;
#Column(
name = "is_business",
nullable = false,
columnDefinition = "boolean default false")
private Boolean isBusiness;
#OneToOne(
cascade = CascadeType.ALL,
fetch = FetchType.EAGER)
#JoinColumn(
name = "owner_profile_pk",
referencedColumnName = "pk",
foreignKey = #ForeignKey(
name = "owner_profile_pk_fk"))
private OwnerProfile ownerProfile;
#OneToMany(
mappedBy = "company",
orphanRemoval = true,
cascade = CascadeType.ALL)
private Set<CompanyRegistration> companyRegistrations = new HashSet<>();
#OneToMany(
mappedBy = "company",
orphanRemoval = true,
cascade = CascadeType.ALL)
private Set<GiveawayFollowers> giveawayFollowers = new HashSet<>();
#OneToMany(
mappedBy = "company",
orphanRemoval = true,
cascade = CascadeType.ALL,
fetch = FetchType.EAGER)
private Set<TargetAudience> targetAudiences = new HashSet<>();
public Company() {
}
public Company(User user) {
this.pk = user.getPk();
this.username = user.getUsername();
this.fullName = user.getFull_name();
this.profilePicUrl = user.getProfile_pic_url();
this.profilePicId = user.getProfile_pic_id();
this.followingCount = user.getFollowing_count();
this.biography = user.getBiography();
this.accountType = user.getAccount_type();
this.isPrivate = user.is_private();
this.isBusiness = user.is_business();
}
public Company(Long pk,
String username,
String fullName,
String profilePicUrl,
String profilePicId,
Integer followingCount,
String biography,
Integer accountType,
Boolean isPrivate,
Boolean isBusiness) {
this.pk = pk;
this.username = username;
this.fullName = fullName;
this.profilePicUrl = profilePicUrl;
this.profilePicId = profilePicId;
this.followingCount = followingCount;
this.biography = biography;
this.accountType = accountType;
this.isPrivate = isPrivate;
this.isBusiness = isBusiness;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public Long getPk() {
return pk;
}
public void setPk(Long pk) {
this.pk = pk;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getProfilePicUrl() {
return profilePicUrl;
}
public void setProfilePicUrl(String profilePicUrl) {
this.profilePicUrl = profilePicUrl;
}
public String getProfilePicId() {
return profilePicId;
}
public void setProfilePicId(String profilePicId) {
this.profilePicId = profilePicId;
}
public Integer getFollowingCount() {
return followingCount;
}
public void setFollowingCount(Integer followingCount) {
this.followingCount = followingCount;
}
public String getBiography() {
return biography;
}
public void setBiography(String biography) {
this.biography = biography;
}
public Integer getAccountType() {
return accountType;
}
public void setAccountType(Integer accountType) {
this.accountType = accountType;
}
public Boolean getPrivate() {
return isPrivate;
}
public void setPrivate(Boolean aPrivate) {
isPrivate = aPrivate;
}
public Boolean getBusiness() {
return isBusiness;
}
public void setBusiness(Boolean business) {
isBusiness = business;
}
public OwnerProfile getOwnerProfile() {
return ownerProfile;
}
public void setOwnerProfile(OwnerProfile ownerProfile) {
this.ownerProfile = ownerProfile;
}
public Set<CompanyRegistration> getCompanyRegistrations() {
return companyRegistrations;
}
public void addCompanyRegistration(CompanyRegistration companyRegistration) {
companyRegistrations.add(companyRegistration);
}
public void removeCompanyRegistration(CompanyRegistration companyRegistration) {
companyRegistrations.remove(companyRegistration);
}
public Set<GiveawayFollowers> getGiveawayFollowers() {
return giveawayFollowers;
}
public void addGiveawayFollower(GiveawayFollowers giveawayFollowers) {
this.giveawayFollowers.add(giveawayFollowers);
}
public void removeGiveawayFollower(GiveawayFollowers giveawayFollowers) {
this.giveawayFollowers.remove(giveawayFollowers);
}
public Set<TargetAudience> getTargetAudiences() {
return targetAudiences;
}
public void addTargetAudience(TargetAudience targetAudience) {
this.targetAudiences.add(targetAudience);
}
public void removeTargetAudience(TargetAudience targetAudience) {
this.targetAudiences.remove(targetAudience);
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Company)) return false;
Company company = (Company) o;
return getId().equals(company.getId())
&& getPk().equals(company.getPk())
&& getUsername().equals(company.getUsername());
}
#Override
public int hashCode() {
return Objects.hash(getId(), getPk(), getUsername());
}
#Override
public String toString() {
return "CompanyDetails{" +
"id=" + id +
", pk=" + pk +
", username='" + username + '\'' +
", fullName='" + fullName + '\'' +
", profilePicUrl='" + profilePicUrl + '\'' +
", profilePicId=" + profilePicId +
", followingCount=" + followingCount +
", biography='" + biography + '\'' +
", accountType=" + accountType +
", isPrivate=" + isPrivate +
", isBusiness=" + isBusiness +
'}';
}
}
public interface OwnerProfileRepository extends JpaRepository<OwnerProfile, Long> {
Optional<OwnerProfile> findOwnerProfileByPk(Long pk);
}
Any idea why this is happening and how you can fix it?

Related

JPA many to many relation: unable to insert into generated table

I have 2 entities "Entree" and "Emplacement":
#Entity
#Table(name = "ENTREE")
public class Entree {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID_ENTREE", updatable = false, nullable = false)
private long idEntree;
#Column(name = "NUM_DECLARATION", insertable=true, updatable=true, nullable=true)
private String numDeclaration;
#Column(name = "DATE_ENTREE", insertable=true, updatable=true, nullable=true)
private String dateEntree;
#Column(name = "TYPE_ENTREE", insertable=true, updatable=true, nullable=true)
private String typeEntree;
#Column(name = "NOM_ARTICLE", insertable=true, updatable=true, nullable=true)
private String nomArticle;
#Column(name = "TYPE_ARTICLE", insertable=true, updatable=true, nullable=true)
private String typeArticle;
#Column(name = "QUANTITE_ENTREE", insertable=true, updatable=true, nullable=true)
private int quantiteEntree;
#ManyToOne
#JoinColumn(name="idDossier", nullable=false)
private Dossier dossier;
#ManyToMany( fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
#JoinTable(name = "entree_emplacement",
joinColumns = {
#JoinColumn(name = "id_entree", referencedColumnName = "id_entree",
nullable = false, updatable = false)},
inverseJoinColumns = {
#JoinColumn(name = "id_emplacement", referencedColumnName = "id_emplacement",
nullable = false, updatable = false)})
private Set<Emplacement> emplacement = new HashSet<>();
public Entree() {
super();
}
public Entree( String numDeclaration, String dateEntree, String typeEntree, String nomArticle, String typeArticle, int quantiteEntree, boolean isDone) {
super();
this.numDeclaration = numDeclaration;
this.dateEntree = dateEntree;
this.typeEntree = typeEntree;
this.nomArticle = nomArticle;
this.typeArticle = typeArticle;
this.quantiteEntree = quantiteEntree;
}
public long getIdEntree() {
return idEntree;
}
public void setIdEntree(long idEntree) {
this.idEntree = idEntree;
}
public String getNumDeclaration() {
return numDeclaration;
}
public void setNumDeclaration(String numDeclaration) {
this.numDeclaration = numDeclaration;
}
public String getDateEntree() {
return dateEntree;
}
public void setDateEntree(String dateEntree) {
this.dateEntree = dateEntree;
}
public String getTypeEntree() {
return typeEntree;
}
public void setTypeEntree(String typeEntree) {
this.typeEntree = typeEntree;
}
public String getNomArticle() {
return nomArticle;
}
public void setNomArticle(String nomArticle) {
this.nomArticle = nomArticle;
}
public String getTypeArticle() {
return typeArticle;
}
public void setTypeArticle(String typeArticle) {
this.typeArticle = typeArticle;
}
public int getQuantiteEntree() {
return quantiteEntree;
}
public void setQuantiteEntree(int quantiteEntree) {
this.quantiteEntree = quantiteEntree;
}
public Dossier getDossier() {
return dossier;
}
public void setDossier(Dossier dossier) {
this.dossier = dossier;
}
public Set<Emplacement> getEmplacements() {
return emplacement;
}
public void addEmplacement(Emplacement emplacement) {
this.emplacement.add(emplacement);
emplacement.getEntrees().add(this);
}
public void removeEmplacement(Emplacement emplacement) {
this.emplacement.remove(emplacement);
emplacement.getEntrees().remove(this);
}
}
And here the second entity:
#Entity
#Table(name = "EMPLACEMENT")
public class Emplacement {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID_EMPLACEMENT", updatable = false, nullable = false)
private long idEmplacement;
#Column(name = "NUM_EMPLACEMENT", insertable=true, updatable=true, nullable=false)
private String numEmplacement;
#ManyToMany(mappedBy = "emplacement", fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
private Set<Entree> entree = new HashSet<>();
public Emplacement() {
}
public Emplacement( String numEmplacement) {
this.numEmplacement = numEmplacement;
}
public long getIdEmplacement() {
return idEmplacement;
}
public void setIdEmplacement(long idEmplacement) {
this.idEmplacement = idEmplacement;
}
public String getNumEmplacement() {
return numEmplacement;
}
public void setNumEmplacement(String numEmplacement) {
this.numEmplacement = numEmplacement;
}
public Set<Entree> getEntrees() {
return entree;
}
}
Here is my inserting code:
#PostMapping("/ajouterEntree")
public ResponseEntity<String> addEntree(#Valid Entree entree, BindingResult result,ModelMap modelMap, #RequestParam(name = "numDossier") String numDossier, #RequestParam(name = "emplacement") String liste_emplacements) {
Emplacement e = new Emplacement(liste_emplacements);
entree.getEmplacements().add(e);
entreeService.saveEntree(entree);
return new ResponseEntity<String>("ok" + result, HttpStatus.OK);
}
I am able to insert datas into Entree and Emplacement tables, but the third generated table named entree-emplacement is empty.
So how can I insert datas into generated table in #ManyToMany relation?
Thanks
Ok it's resolved. Here is my code:
if(!liste_emplacements.equals(""))
{
List<String> list = new ArrayList<String>(Arrays.asList(liste_emplacements.split(",")));
Emplacement[] emp = new Emplacement[list.size()];
for (int i=0; i<list.size() ;i++)
{
emp[i] = new Emplacement(Long.parseLong(list.get(i)));
entree.getEmplacements().add(emp[i]);
emp[i].getEntrees().add(entree);
}
}
entreeService.saveEntree(entree);
return new ResponseEntity<String>("ok" + result, HttpStatus.OK);

jpa named query using foreign key is not working

MY Entity class
#Entity
#Table(catalog = "", schema = "MYIS")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Answers.findAll", query = "SELECT a FROM Answers a"),
#NamedQuery(name = "Answers.findByAid", query = "SELECT a FROM Answers a WHERE a.aid = :aid"),
#NamedQuery(name ="Anaswers.findByqid", query ="SELECT a FROM Answers a WHERE a.answerQid.qid = :x"),
#NamedQuery(name = "Answers.findByAnsValue", query = "SELECT a FROM Answers a WHERE a.ansValue = :ansValue"),
#NamedQuery(name = "Answers.findByAnsDate", query = "SELECT a FROM Answers a WHERE a.ansDate = :ansDate")})
public class Answers implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Column(nullable = false)
private Integer aid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 4000)
#Column(name = "ANS_VALUE", nullable = false, length = 4000)
private String ansValue;
#Basic(optional = false)
#NotNull
#Column(name = "ANS_DATE", nullable = false)
#Temporal(TemporalType.TIMESTAMP)
private Date ansDate;
#JoinColumn(name = "A_USERID", referencedColumnName = "USERID", nullable = false)
#ManyToOne(optional = false)
private Users aUserid;
#JoinColumn(name = "ANSWER_QID", referencedColumnName = "QID", nullable = false)
#ManyToOne(optional = false)
private Questions answerQid;
#JoinColumn(name = "A_GROUPID", referencedColumnName = "GID", nullable = false)
#ManyToOne(optional = false)
private Groups aGroupid;
public Answers() {
}
public Answers(Integer aid) {
this.aid = aid;
}
public Answers(Integer aid, String ansValue, Date ansDate) {
this.aid = aid;
this.ansValue = ansValue;
this.ansDate = ansDate;
}
public Integer getAid() {
return aid;
}
public void setAid(Integer aid) {
this.aid = aid;
}
public String getAnsValue() {
return ansValue;
}
public void setAnsValue(String ansValue) {
this.ansValue = ansValue;
}
public Date getAnsDate() {
return ansDate;
}
public void setAnsDate(Date ansDate) {
this.ansDate = ansDate;
}
public Users getAUserid() {
return aUserid;
}
public void setAUserid(Users aUserid) {
this.aUserid = aUserid;
}
public Questions getAnswerQid() {
return answerQid;
}
public void setAnswerQid(Questions answerQid) {
this.answerQid = answerQid;
}
public Groups getAGroupid() {
return aGroupid;
}
public void setAGroupid(Groups aGroupid) {
this.aGroupid = aGroupid;
}
#Override
public int hashCode() {
int hash = 0;
hash += (aid != null ? aid.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Answers)) {
return false;
}
Answers other = (Answers) object;
if ((this.aid == null && other.aid != null) || (this.aid != null && !this.aid.equals(other.aid))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.entity.Answers[ aid=" + aid + " ]";
}
}
MY SESSION FACADE
import com.entity.Answers;
import com.entity.Groups;
import java.util.List;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
/**
*
* #author krishna teja
*/
#Stateless
public class AnswersFacade extends AbstractFacade<Answers> implements AnswersFacadeLocal {
#PersistenceContext(unitName = "My_communityPU")
private EntityManager em;
#Override
protected EntityManager getEntityManager() {
return em;
}
public AnswersFacade() {
super(Answers.class);
}
public List<Answers> getdataByQid(Long qid){
Query query=em.createNamedQuery("Answers.findByqid");
query.setParameter(1, qid);
List<Answers> a =query.getResultList();
return a;
}
}
My managed bean
#PostConstruct
public void init(){
questions = questionsFacade.findAll();
ansList = answersFacade.getdataByQid(g);
}
I am getting following exception
at com.ejb.AnswersFacade.getdataByQid(AnswersFacade.java:36)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
I have created named query for the foreign key attribute answerQid and and created method in the sessionfacade and tried to access it in the managed bean the default methods work perfectly but my method for query is not working please help me
Looks like a simple typo. Named query is defined as Anaswers.findByqid, but used as Answers.findByqid.

ClassCastException on itself after redeploy of same application`

I am developing a JSF application with Netbeans and Glassfish. When I change something and Netbeans redeploys to Glassfish, then a ClassCastException is been thrown on the entity class itself.
Caused by: java.lang.ClassCastException: com.twibu.entity.Tipper cannot be cast to com.twibu.entity.Tipper
at com.twibu.service.TipperService.findByUseridPwd(TipperService.java:22)
How is this caused and how can I solve it?
For reference, here's the full stack trace:
WARNING: EJB5184:A system exception occurred during an invocation on EJB TipperService, method: public com.twibu.entity.Tipper com.twibu.service.TipperService.findByUseridPwd(java.lang.String,java.lang.String)
WARNING: javax.ejb.EJBException
at com.sun.ejb.containers.BaseContainer.processSystemException(BaseContainer.java:5215)
at com.sun.ejb.containers.BaseContainer.completeNewTx(BaseContainer.java:5113)
at com.sun.ejb.containers.BaseContainer.postInvokeTx(BaseContainer.java:4901)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:2045)
at com.sun.ejb.containers.BaseContainer.postInvoke(BaseContainer.java:1994)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:222)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandlerDelegate.invoke(EJBLocalObjectInvocationHandlerDelegate.java:89)
at com.sun.proxy.$Proxy141.findByUseridPwd(Unknown Source)
at com.twibu.service.__EJB31_Generated__TipperService__Intf____Bean__.findByUseridPwd(Unknown Source)
at com.twibu.bean.AuthBean.login(AuthBean.java:122)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.el.parser.AstValue.invoke(AstValue.java:254)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:302)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at javax.faces.component.MethodBindingMethodExpressionAdapter.invoke(MethodBindingMethodExpressionAdapter.java:88)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:794)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1259)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:118)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:593)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1550)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:281)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:175)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:655)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:595)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:161)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:331)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:231)
at com.sun.enterprise.v3.services.impl.ContainerMapper$AdapterCallable.call(ContainerMapper.java:317)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:195)
at com.sun.grizzly.http.ProcessorTask.invokeAdapter(ProcessorTask.java:860)
at com.sun.grizzly.http.ProcessorTask.doProcess(ProcessorTask.java:757)
at com.sun.grizzly.http.ProcessorTask.process(ProcessorTask.java:1056)
at com.sun.grizzly.http.DefaultProtocolFilter.execute(DefaultProtocolFilter.java:229)
at com.sun.grizzly.DefaultProtocolChain.executeProtocolFilter(DefaultProtocolChain.java:137)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:104)
at com.sun.grizzly.DefaultProtocolChain.execute(DefaultProtocolChain.java:90)
at com.sun.grizzly.http.HttpProtocolChain.execute(HttpProtocolChain.java:79)
at com.sun.grizzly.ProtocolChainContextTask.doCall(ProtocolChainContextTask.java:54)
at com.sun.grizzly.SelectionKeyContextTask.call(SelectionKeyContextTask.java:59)
at com.sun.grizzly.ContextTask.run(ContextTask.java:71)
at com.sun.grizzly.util.AbstractThreadPool$Worker.doWork(AbstractThreadPool.java:532)
at com.sun.grizzly.util.AbstractThreadPool$Worker.run(AbstractThreadPool.java:513)
at java.lang.Thread.run(Thread.java:722)
Caused by: java.lang.ClassCastException: com.twibu.entity.Tipper cannot be cast to com.twibu.entity.Tipper
at com.twibu.service.TipperService.findByUseridPwd(TipperService.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at org.glassfish.ejb.security.application.EJBSecurityManager.runMethod(EJBSecurityManager.java:1052)
at org.glassfish.ejb.security.application.EJBSecurityManager.invoke(EJBSecurityManager.java:1124)
at com.sun.ejb.containers.BaseContainer.invokeBeanMethod(BaseContainer.java:5388)
at com.sun.ejb.EjbInvocation.invokeBeanMethod(EjbInvocation.java:619)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
at com.sun.ejb.EjbInvocation.proceed(EjbInvocation.java:571)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.doAround(SystemInterceptorProxy.java:162)
at com.sun.ejb.containers.interceptors.SystemInterceptorProxy.aroundInvoke(SystemInterceptorProxy.java:144)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:601)
at com.sun.ejb.containers.interceptors.AroundInvokeInterceptor.intercept(InterceptorManager.java:861)
at com.sun.ejb.containers.interceptors.AroundInvokeChainImpl.invokeNext(InterceptorManager.java:800)
at com.sun.ejb.containers.interceptors.InterceptorManager.intercept(InterceptorManager.java:370)
at com.sun.ejb.containers.BaseContainer.__intercept(BaseContainer.java:5360)
at com.sun.ejb.containers.BaseContainer.intercept(BaseContainer.java:5348)
at com.sun.ejb.containers.EJBLocalObjectInvocationHandler.invoke(EJBLocalObjectInvocationHandler.java:214)
... 44 more
Here's the entity:
#Entity
#Table(name = "tipper")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Tipper.findAll", query = "SELECT t FROM Tipper t"),
#NamedQuery(name = "Tipper.findById", query = "SELECT t FROM Tipper t WHERE t.id = :id"),
#NamedQuery(name = "Tipper.findByName", query = "SELECT t FROM Tipper t WHERE t.name = :name"),
#NamedQuery(name = "Tipper.findByUserid", query = "SELECT t FROM Tipper t WHERE t.userid = :userid"),
#NamedQuery(name = "Tipper.findByPwd", query = "SELECT t FROM Tipper t WHERE t.pwd = :pwd"),
#NamedQuery(name = "Tipper.findByEmail", query = "SELECT t FROM Tipper t WHERE t.email = :email")})
#NamedNativeQueries({
#NamedNativeQuery(name = "Tipper.findByUseridPwd", query = "" +
"SELECT a.id AS id, " +
" a.idgruppe AS idgruppe, " +
" a.name AS name, " +
" a.userid AS userid, " +
" a.pwd AS pwd, " +
" a.email AS email " +
"FROM tipper AS a " +
"WHERE a.userid = ? " +
" AND a.pwd = MD5(?)",
resultClass=Tipper.class)})
public class Tipper implements Serializable {
private static final long serialVersionUID = 20130311L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "name")
private String name;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 20)
#Column(name = "userid")
private String userid;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 32)
#Column(name = "pwd")
private String pwd;
// #Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "email")
private String email;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "tipper")
private Collection<Zulassung> zulassungCollection;
#JoinColumn(name = "idgruppe", referencedColumnName = "id")
#ManyToOne(optional = false)
private Gruppe idgruppe;
public Tipper() {
}
public Tipper(Integer id) {
this.id = id;
}
public Tipper(Integer id, String name, String userid, String pwd, String email) {
this.id = id;
this.name = name;
this.userid = userid;
this.pwd = pwd;
this.email = email;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getUserid() {
return userid;
}
public void setUserid(String userid) {
this.userid = userid;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#XmlTransient
public Collection<Zulassung> getZulassungCollection() {
return zulassungCollection;
}
public void setZulassungCollection(Collection<Zulassung> zulassungCollection) {
this.zulassungCollection = zulassungCollection;
}
public Gruppe getIdgruppe() {
return idgruppe;
}
public void setIdgruppe(Gruppe idgruppe) {
this.idgruppe = idgruppe;
}
public boolean isUser() {
return idgruppe.getName().equals("user") || idgruppe.getName().equals("admin");
}
public boolean isAdmin() {
return idgruppe.getName().equals("admin");
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Tipper)) {
return false;
}
Tipper other = (Tipper) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.twibu.entity.Tipper[ id=" + id + " ]";
}
}
And here's the service class:
#Singleton
public class TipperService extends AbstractService {
public Tipper findByUseridPwd(String userid, String pwd) {
Query nq = getTwibuManager().createNamedQuery("Tipper.findByUseridPwd");
nq.setParameter(1, userid);
nq.setParameter(2, pwd);
return (Tipper)nq.getSingleResult();
}
}
Seems like the old application is not getting undeployed.
If you are not using a container managed persistence unit, then you need to close your EntityManagerFactory when undeploying.

Why JPA doesnt generate a join junction table in this case

I have two tables Students and Books , with a many to many relationship. The code of both are given below. Now when I try to run the code I get the error.
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.2.v20111125-r10461): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'acme.book_stud' doesn't exist
Error Code: 1146
Call: INSERT INTO book_stud (idStudents, idBooks) VALUES (?, ?)
bind => [2 parameters bound]
It seems like JPA is trying to write to a juction table which does not exist (in this case it assumes a junction table books_students is already created so it doesnt create one.). It works if I create a books_students but I dont want to do that since its JPA responsibility to create it. Is there a way in which I could explicitly tell it to create one. ? (I am taking a wild guess here - but I guess when creating a persitance unit I specified "none" I think thats why it didnt create that table . Am I correct ? Anyways here are my Student and Books Classes
BOOKS CLASS
#Entity
#Table(name = "books")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Books.findAll", query = "SELECT b FROM Books b"),
#NamedQuery(name = "Books.findByIdBooks", query = "SELECT b FROM Books b WHERE b.idBooks = :idBooks"),
#NamedQuery(name = "Books.findByBookName", query = "SELECT b FROM Books b WHERE b.bookName = :bookName"),
#NamedQuery(name = "Books.findByBookType", query = "SELECT b FROM Books b WHERE b.bookType = :bookType")})
public class Books implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "idBooks")
private String idBooks;
#Size(max = 45)
#Column(name = "BookName")
private String bookName;
#Size(max = 45)
#Column(name = "BookType")
private String bookType;
/******************************************ADDED **********************/
#ManyToMany
#JoinTable(name = "book_stud",
joinColumns = { #JoinColumn(name = "idStudents") },
inverseJoinColumns = { #JoinColumn(name = "idBooks") })
/**************************************ENDED*****************************/
public Books() {
}
public Books(String idBooks) {
this.idBooks = idBooks;
}
public String getIdBooks() {
return idBooks;
}
public void setIdBooks(String idBooks) {
this.idBooks = idBooks;
}
public String getBookName() {
return bookName;
}
public void setBookName(String bookName) {
this.bookName = bookName;
}
public String getBookType() {
return bookType;
}
public void setBookType(String bookType) {
this.bookType = bookType;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idBooks != null ? idBooks.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Books)) {
return false;
}
Books other = (Books) object;
if ((this.idBooks == null && other.idBooks != null) || (this.idBooks != null && !this.idBooks.equals(other.idBooks))) {
return false;
}
return true;
}
#Override
public String toString() {
return "domain.Books[ idBooks=" + idBooks + " ]";
}
}
STUDENT CLASS
#Entity
#Table(name = "students")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "StudentEnroll.findAll", query = "SELECT s FROM StudentEnroll s"),
#NamedQuery(name = "StudentEnroll.findByIdStudents", query = "SELECT s FROM StudentEnroll s WHERE s.idStudents = :idStudents"),
#NamedQuery(name = "StudentEnroll.findByName", query = "SELECT s FROM StudentEnroll s WHERE s.name = :name"),
#NamedQuery(name = "StudentEnroll.findByRoll", query = "SELECT s FROM StudentEnroll s WHERE s.roll = :roll"),
#NamedQuery(name = "StudentEnroll.findBySsn", query = "SELECT s FROM StudentEnroll s WHERE s.ssn = :ssn"),
#NamedQuery(name = "StudentEnroll.findByProgram", query = "SELECT s FROM StudentEnroll s WHERE s.program = :program")})
public class StudentEnroll implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 40)
#Column(name = "idStudents")
private String idStudents;
#Size(max = 45)
#Column(name = "Name")
private String name;
#Column(name = "Roll")
private Integer roll;
#Column(name = "SSN")
private Integer ssn;
#Size(max = 45)
#Column(name = "Program")
private String program;
#JoinColumn(name = "CustomerID", referencedColumnName = "UserID")
#ManyToOne
private Customer customerID;
//#OneToMany(mappedBy = "studentRoll")
#OneToMany(mappedBy = "studentRoll",cascade = CascadeType.REMOVE)//added REMOVE
private Collection<Subject> subjectCollection;
/**************************ADDED*****************************/
#ManyToMany
#JoinTable(name = "book_stud",
joinColumns = { #JoinColumn(name = "idBooks") },
inverseJoinColumns = { #JoinColumn(name = "idStudents") })
/**********************************END**********************/
public StudentEnroll() {
}
public StudentEnroll(String idStudents) {
this.idStudents = idStudents;
}
public String getIdStudents() {
return idStudents;
}
public void setIdStudents(String idStudents) {
this.idStudents = idStudents;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getRoll() {
return roll;
}
public void setRoll(Integer roll) {
this.roll = roll;
}
public Integer getSsn() {
return ssn;
}
public void setSsn(Integer ssn) {
this.ssn = ssn;
}
public String getProgram() {
return program;
}
public void setProgram(String program) {
this.program = program;
}
public Customer getCustomerID() {
return customerID;
}
public void setCustomerID(Customer customerID) {
this.customerID = customerID;
}
#XmlTransient
public Collection<Subject> getSubjectCollection() {
return subjectCollection;
}
public void setSubjectCollection(Collection<Subject> subjectCollection) {
this.subjectCollection = subjectCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idStudents != null ? idStudents.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof StudentEnroll)) {
return false;
}
StudentEnroll other = (StudentEnroll) object;
if ((this.idStudents == null && other.idStudents != null) || (this.idStudents != null && !this.idStudents.equals(other.idStudents))) {
return false;
}
return true;
}
#Override
public String toString() {
return "domain.StudentEnroll[ idStudents=" + idStudents + " ]";
}
}

EclipseLink GeneratedValue null on postgres only on one entity

I have a rather weird case. I have some entities generated with netbeans and i can persist all except one. I see no difference in the database nor in the entity class. Can someone help me, here is my entity class , database, and error that i am receiving
CREATE TABLE objekat
(
id_objekat bigserial NOT NULL,
id_opstina serial NOT NULL,
naziv character varying(50) NOT NULL,
kapacitet character varying(50),
adresa character varying(100),
lokacija_sirina double precision,
lokacija_duzina double precision,
opis character varying(500),
korisnicko_ime character varying(50),
sifra character varying(50),
maks_broj_slike integer,
absolute_path_logo character varying(255),
CONSTRAINT objekat_pkey PRIMARY KEY (id_objekat),
CONSTRAINT fkobjekat924176 FOREIGN KEY (id_opstina)
REFERENCES opstina (id_opstina) MATCH SIMPLE
ON UPDATE NO ACTION ON DELETE NO ACTION
)
WITH (
OIDS=FALSE
);
and this is my entity bean.
#Entity
#Table(name = "objekat")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Objekat.findAll", query = "SELECT o FROM Objekat o"),
#NamedQuery(name = "Objekat.findByIdObjekat", query = "SELECT o FROM Objekat o WHERE o.idObjekat = :idObjekat"),
#NamedQuery(name = "Objekat.findByNaziv", query = "SELECT o FROM Objekat o WHERE upper (o.naziv) like upper(:naziv)"),
#NamedQuery(name = "Objekat.findByNazivAndOpstina", query = "SELECT o FROM Objekat o inner join o.idOpstina op WHERE upper (o.naziv) like upper(:naziv) and op.idOpstina = :idOpstina"),
#NamedQuery(name = "Objekat.findByKapacitet", query = "SELECT o FROM Objekat o WHERE o.kapacitet = :kapacitet"),
#NamedQuery(name = "Objekat.findByAdresa", query = "SELECT o FROM Objekat o WHERE o.adresa = :adresa"),
#NamedQuery(name = "Objekat.findByLokacijaSirina", query = "SELECT o FROM Objekat o WHERE o.lokacijaSirina = :lokacijaSirina"),
#NamedQuery(name = "Objekat.findByLokacijaDuzina", query = "SELECT o FROM Objekat o WHERE o.lokacijaDuzina = :lokacijaDuzina")})
public class Objekat implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id_objekat",columnDefinition = "BIGSERIAL")
private Long idObjekat;
#Size(max = 255)
#Column(name = "absolute_path_logo")
private String absolutePathLogo;
#OneToMany( mappedBy = "objekatidObjekat")
private List<DogadjajObjekat> dogadjajObjekatList;
#OneToMany( mappedBy = "objekatidObjekat")
private List<SlikeLokacijaObjekat> slikeLokacijaObjekatList;
#OneToMany( mappedBy = "idObjekat")
private List<RasporedObjekat> rasporedObjekatList;
#Column(name = "maks_broj_slike")
private Integer maksBrojSlike;
#Size(max = 50)
#Column(name = "korisnicko_ime")
private String korisnickoIme;
#Size(max = 50)
#Column(name = "sifra")
private String sifra;
#Size(max = 500)
#Column(name = "opis")
private String opis;
// #Max(value=?) #Min(value=?)//if you know range of your decimal fields consider using these annotations to enforce field validation
#Column(name = "lokacija_sirina")
private Double lokacijaSirina;
#Column(name = "lokacija_duzina")
private Double lokacijaDuzina;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 50)
#Column(name = "naziv")
private String naziv;
#Size(max = 50)
#Column(name = "kapacitet")
private String kapacitet;
#Size(max = 100)
#Column(name = "adresa")
private String adresa;
#JoinTable(name = "tip_objekta_objekat", joinColumns = {
#JoinColumn(name = "objekatid_objekat", referencedColumnName = "id_objekat")}, inverseJoinColumns = {
#JoinColumn(name = "tip_objektaid_tip_objekta", referencedColumnName = "id_tip_objekta")})
#ManyToMany
private List<TipObjekta> tipObjektaList;
#JoinColumn(name = "id_opstina", referencedColumnName = "id_opstina")
#ManyToOne(optional = false)
private Opstina idOpstina;
public Objekat() {
}
public Objekat(Long idObjekat) {
this.idObjekat = idObjekat;
}
public Objekat(Long idObjekat, String naziv) {
this.idObjekat = idObjekat;
this.naziv = naziv;
}
public Long getIdObjekat() {
return idObjekat;
}
public void setIdObjekat(Long idObjekat) {
this.idObjekat = idObjekat;
}
public String getNaziv() {
return naziv;
}
public void setNaziv(String naziv) {
this.naziv = naziv;
}
public String getKapacitet() {
return kapacitet;
}
public void setKapacitet(String kapacitet) {
this.kapacitet = kapacitet;
}
public String getAdresa() {
return adresa;
}
public void setAdresa(String adresa) {
this.adresa = adresa;
}
#XmlTransient
public List<TipObjekta> getTipObjektaList() {
return tipObjektaList;
}
public void setTipObjektaList(List<TipObjekta> tipObjektaList) {
this.tipObjektaList = tipObjektaList;
}
public Opstina getIdOpstina() {
return idOpstina;
}
public void setIdOpstina(Opstina idOpstina) {
this.idOpstina = idOpstina;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idObjekat != null ? idObjekat.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Objekat)) {
return false;
}
Objekat other = (Objekat) object;
if ((this.idObjekat == null && other.idObjekat != null) || (this.idObjekat != null && !this.idObjekat.equals(other.idObjekat))) {
return false;
}
return true;
}
#Override
public String toString() {
return "rs.dzetSet.entiteti.Objekat[ idObjekat=" + idObjekat + " ]";
}
public String getOpis() {
return opis;
}
public void setOpis(String opis) {
this.opis = opis;
}
public Double getLokacijaSirina() {
return lokacijaSirina;
}
public void setLokacijaSirina(Double lokacijaSirina) {
this.lokacijaSirina = lokacijaSirina;
}
public Double getLokacijaDuzina() {
return lokacijaDuzina;
}
public void setLokacijaDuzina(Double lokacijaDuzina) {
this.lokacijaDuzina = lokacijaDuzina;
}
public String getKorisnickoIme() {
return korisnickoIme;
}
public void setKorisnickoIme(String korisnickoIme) {
this.korisnickoIme = korisnickoIme;
}
public String getSifra() {
return sifra;
}
public void setSifra(String sifra) {
this.sifra = sifra;
}
public Integer getMaksBrojSlike() {
return maksBrojSlike;
}
public void setMaksBrojSlike(Integer maksBrojSlike) {
this.maksBrojSlike = maksBrojSlike;
}
public void pocevajMaksBrojSlike(){
this.maksBrojSlike++;
}
public String getAbsolutePathLogo() {
return absolutePathLogo;
}
public void setAbsolutePathLogo(String absolutePathLogo) {
this.absolutePathLogo = absolutePathLogo;
}
#XmlTransient
public List<RasporedObjekat> rasporedObjekatListPrePodne(){
List<RasporedObjekat> rez = new ArrayList<RasporedObjekat>();
if(rasporedObjekatList==null){
rasporedObjekatList = new ArrayList<RasporedObjekat>();
}
for(RasporedObjekat ro:rasporedObjekatList){
if(!ro.getVecernjiProgram()){
rez.add(ro);
}
}
return rez;
}
#XmlTransient
public List<RasporedObjekat> rasporedObjekatListPoslePodne(){
List<RasporedObjekat> rez = new ArrayList<RasporedObjekat>();
if(rasporedObjekatList==null){
rasporedObjekatList = new ArrayList<RasporedObjekat>();
}
for(RasporedObjekat ro:rasporedObjekatList){
if(ro.getVecernjiProgram()){
rez.add(ro);
}
}
return rez;
}
#XmlTransient
public List<DogadjajObjekat> getDogadjajObjekatList() {
return dogadjajObjekatList;
}
public void setDogadjajObjekatList(List<DogadjajObjekat> dogadjajObjekatList) {
this.dogadjajObjekatList = dogadjajObjekatList;
}
#XmlTransient
public List<SlikeLokacijaObjekat> getSlikeLokacijaObjekatList() {
return slikeLokacijaObjekatList;
}
public void setSlikeLokacijaObjekatList(List<SlikeLokacijaObjekat> slikeLokacijaObjekatList) {
this.slikeLokacijaObjekatList = slikeLokacijaObjekatList;
}
#XmlTransient
public List<RasporedObjekat> getRasporedObjekatList() {
return rasporedObjekatList;
}
public void setRasporedObjekatList(List<RasporedObjekat> rasporedObjekatList) {
this.rasporedObjekatList = rasporedObjekatList;
}
and i persist it in a rather normal way, or i just think so.
utx.begin();
if(noviObjekat.getIdObjekat() == null){
em.persist(noviObjekat);
}else{
em.merge(noviObjekat);
}
utx.commit();
and i get a pretty weird error
Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: org.postgresql.util.PSQLException: ERROR: null value in column "id_opstina" violates not-null constraint
Error Code: 0
Call: INSERT INTO objekat (absolute_path_logo, adresa, kapacitet, korisnicko_ime, lokacija_duzina, lokacija_sirina, maks_broj_slike, naziv, opis, sifra, id_opstina) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
bind => [11 parameters bound]
Query: InsertObjectQuery(rs.dzetSet.entiteti.Objekat[ idObjekat=null ])
}
You set a generator on the field for "id_objekat" but the exception is for the not-null constraint on "id_opstina". You will need to set this field yourself or use a returning policy to get it instead:
http://wiki.eclipse.org/Using_EclipseLink_JPA_Extensions_(ELUG)#Using_EclipseLink_JPA_Extensions_for_Returning_Policy