I have the following tables :
wherein idclient is unsigned auto_increment.
code of the Client entity:
import java.io.Serializable;
import java.util.List;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlTransient;
#Entity
#Table(name = "CLIENT", catalog = "TEST", schema = "PUBLIC")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Client.findAll", query = "SELECT c FROM Client c"),
#NamedQuery(name = "Client.findByIdclient", query = "SELECT c FROM Client c WHERE c.idclient = :idclient"),
#NamedQuery(name = "Client.findByLibel", query = "SELECT c FROM Client c WHERE c.libel = :libel"),
#NamedQuery(name = "Client.findByAdresse", query = "SELECT c FROM Client c WHERE c.adresse = :adresse"),
#NamedQuery(name = "Client.findByNomResp", query = "SELECT c FROM Client c WHERE c.nomResp = :nomResp"),
#NamedQuery(name = "Client.findByTelPortable", query = "SELECT c FROM Client c WHERE c.telPortable = :telPortable"),
#NamedQuery(name = "Client.findByTelFixe", query = "SELECT c FROM Client c WHERE c.telFixe = :telFixe"),
#NamedQuery(name = "Client.findByFax", query = "SELECT c FROM Client c WHERE c.fax = :fax"),
#NamedQuery(name = "Client.findByCodeTva", query = "SELECT c FROM Client c WHERE c.codeTva = :codeTva"),
#NamedQuery(name = "Client.findByCodeExo", query = "SELECT c FROM Client c WHERE c.codeExo = :codeExo"),
#NamedQuery(name = "Client.findByBanque", query = "SELECT c FROM Client c WHERE c.banque = :banque"),
#NamedQuery(name = "Client.findByRib", query = "SELECT c FROM Client c WHERE c.rib = :rib"),
#NamedQuery(name = "Client.findByCredit", query = "SELECT c FROM Client c WHERE c.credit = :credit"),
#NamedQuery(name = "Client.findByEchance", query = "SELECT c FROM Client c WHERE c.echance = :echance"),
#NamedQuery(name = "Client.findByMail", query = "SELECT c FROM Client c WHERE c.mail = :mail"),
#NamedQuery(name = "Client.findByEtat", query = "SELECT c FROM Client c WHERE c.etat = :etat")})
public class Client implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "IDCLIENT", nullable = false)
private Integer idclient;
#Basic(optional = false)
#Column(name = "LIBEL", nullable = false, length = 100)
private String libel;
#Basic(optional = false)
#Column(name = "ADRESSE", nullable = false, length = 100)
private String adresse;
#Basic(optional = false)
#Column(name = "NOM_RESP", nullable = false, length = 60)
private String nomResp;
#Basic(optional = false)
#Column(name = "TEL_PORTABLE", nullable = false, length = 16)
private String telPortable;
#Basic(optional = false)
#Column(name = "TEL_FIXE", nullable = false, length = 16)
private String telFixe;
#Basic(optional = false)
#Column(name = "FAX", nullable = false, length = 16)
private String fax;
#Basic(optional = false)
#Column(name = "CODE_TVA", nullable = false, length = 30)
private String codeTva;
#Basic(optional = false)
#Column(name = "CODE_EXO", nullable = false, length = 30)
private String codeExo;
#Basic(optional = false)
#Column(name = "BANQUE", nullable = false, length = 60)
private String banque;
#Basic(optional = false)
#Column(name = "RIB", nullable = false, length = 22)
private String rib;
#Basic(optional = false)
#Column(name = "CREDIT", nullable = false)
private double credit;
#Basic(optional = false)
#Column(name = "ECHANCE", nullable = false)
private int echance;
#Basic(optional = false)
#Column(name = "MAIL", nullable = false, length = 70)
private String mail;
#Basic(optional = false)
#Column(name = "ETAT", nullable = false)
private char etat;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "clientIdclient")
private List<Facture> factureList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "clientIdclient")
private List<FactProforma> factProformaList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "clientIdclient")
private List<Bl> blList;
public Client() {
}
public Client(Integer idclient) {
this.idclient = idclient;
}
public Client(Integer idclient, String libel, String adresse, String nomResp, String telPortable, String telFixe, String fax, String codeTva, String codeExo, String banque, String rib, double credit, int echance, String mail, char etat) {
this.idclient = idclient;
this.libel = libel;
this.adresse = adresse;
this.nomResp = nomResp;
this.telPortable = telPortable;
this.telFixe = telFixe;
this.fax = fax;
this.codeTva = codeTva;
this.codeExo = codeExo;
this.banque = banque;
this.rib = rib;
this.credit = credit;
this.echance = echance;
this.mail = mail;
this.etat = etat;
}
public Integer getIdclient() {
return idclient;
}
public void setIdclient(Integer idclient) {
this.idclient = idclient;
}
public String getLibel() {
return libel;
}
public void setLibel(String libel) {
this.libel = libel;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
public String getNomResp() {
return nomResp;
}
public void setNomResp(String nomResp) {
this.nomResp = nomResp;
}
public String getTelPortable() {
return telPortable;
}
public void setTelPortable(String telPortable) {
this.telPortable = telPortable;
}
public String getTelFixe() {
return telFixe;
}
public void setTelFixe(String telFixe) {
this.telFixe = telFixe;
}
public String getFax() {
return fax;
}
public void setFax(String fax) {
this.fax = fax;
}
public String getCodeTva() {
return codeTva;
}
public void setCodeTva(String codeTva) {
this.codeTva = codeTva;
}
public String getCodeExo() {
return codeExo;
}
public void setCodeExo(String codeExo) {
this.codeExo = codeExo;
}
public String getBanque() {
return banque;
}
public void setBanque(String banque) {
this.banque = banque;
}
public String getRib() {
return rib;
}
public void setRib(String rib) {
this.rib = rib;
}
public double getCredit() {
return credit;
}
public void setCredit(double credit) {
this.credit = credit;
}
public int getEchance() {
return echance;
}
public void setEchance(int echance) {
this.echance = echance;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public char getEtat() {
return etat;
}
public void setEtat(char etat) {
this.etat = etat;
}
#XmlTransient
public List<Facture> getFactureList() {
return factureList;
}
public void setFactureList(List<Facture> factureList) {
this.factureList = factureList;
}
#XmlTransient
public List<FactProforma> getFactProformaList() {
return factProformaList;
}
public void setFactProformaList(List<FactProforma> factProformaList) {
this.factProformaList = factProformaList;
}
#XmlTransient
public List<Bl> getBlList() {
return blList;
}
public void setBlList(List<Bl> blList) {
this.blList = blList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idclient != null ? idclient.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 Client)) {
return false;
}
Client other = (Client) object;
if ((this.idclient == null && other.idclient != null) || (this.idclient != null && !this.idclient.equals(other.idclient))) {
return false;
}
return true;
}
#Override
public String toString() {
return "glob.entitys.Client[ idclient=" + idclient + " ]";
}
}
when I try to insert a row into the data base :
Utilisateur user=new Utilisateur(loginActuel);
Client client=new Client(0);// the error comes from here
Facture fact=new Facture(null,new Date());
fact.setClientIdclient(client);
fact.setUtilisateurLogin(user);
FactureJpaController fjc=new FactureJpaController(emf);
fjc.create(fact);
I get this ugly error(but when i set new Client(1) it works well):
Exception in thread "AWT-EventQueue-0" javax.persistence.RollbackException: Exception [EclipseLink-7197] (Eclipse Persistence Services - 2.3.0.v20110604-r9504): org.eclipse.persistence.exceptions.ValidationException
Exception Description: Null or zero primary key encountered in unit of work clone [glob.entitys.Client[ idclient=0 ]], primary key [0]. Set descriptors IdValidation or the "eclipselink.id-validation" property.
how to solve this problem ?
remark: the client idclient = 0 is already inserted in the Database(but manually)
I'd like once and for all overcome this "problem" , how to prevent JPA or H2 Database to start from 0 ?
H2 does allow to use 0 as the primary key. The error message doesn't come from H2.
However, it seems to me that some (older?) version of EclipseLink doesn't allow to use 0.
the client idclient = 0 is already inserted in the Database
It seems this is not supported by this version of EclipseLink. It looks like to work around this problem, you should not use the value 0.
There are two ways how to allow zeroes in primary keys in Eclipselink:
Parameter in persistence.xml:
<property name="eclipselink.id-validation" value="NULL"/>
PrimaryKey annotation on concerned entity class:
#PrimaryKey(validation = IdValidation.NULL)
For JPA (specification 2.0) having (or negative) value for id is fine. And also as primary key value for H2.
Older versions of EclipseLink do consider value 0 or smaller as invalid primary key. See for example following:Bug 249948. So updating EclipseLink can help.
By the way, why you do set in constructor value for idclient that is supposed to be generated?
I had this error and adding the following annotations to my jpa identity resolved it:
#Column(name = "ID_SEARCH_LOG", nullable = false, insertable = true, updatable = true, length = 10, precision = 0)
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int idSearchLog;
The docs say
By default, EclipseLink interprets zero as null for primitive types that cannot be null (such as int and long) causing zero to be an invalid value for primary keys.
but also that that it is possible to change this behaviour in either the persistence.xml or on a particular entity.
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Entities/Ids/Id#Allowing_Zero_Value_Primary_Keys
Related
Account Entity
#Getter
#Accessors(chain = true, fluent = true)
#NoArgsConstructor
#AllArgsConstructor(staticName = "of")
#ToString(of = {"customerName"}, callSuper = true)
#Entity
#Table(name = "ACCOUNTS",
uniqueConstraints = #UniqueConstraint(name = UNQ_CUSTOMER_NAME, columnNames = { "CUSTOMER_NAME" }),
indexes = {
#Index(name = IDX_CUSTOMER_ENTITY, columnList = "CUSTOMER_ENTITY")
}
)
public class Account extends BaseAutoAssignableVersionableEntity<String, Long> implements Diffable<Account> {
public static final String CUSTOMER_ENTITY = "Customer Entity";
public static final String CUSTOMER_REPORTING_MANAGER = "Customer Reporting Manager";
public static final String CUSTOMER_NAME = "Customer Name";
public static final String ACCOUNT_MANAGER = "Account Manager";
public static final String CITY = "City";
public static final String CUSTOMER_TIME_TRACKING = "Customer Time Tracking";
#NotNull
#Column(name = "CUSTOMER_NAME", nullable = false, length = 150)
#Audited(withModifiedFlag = true)
private String customerName; // Unique
#NotNull
#Size(min = 1, max = 4)
#Column(name = "CUSTOMER_GROUP", nullable = false, length = 4)
#Audited(withModifiedFlag = true)
private String customerGroup;
// #NotNull
#Column(name = "CUSTOMER_ENTITY", nullable = true, length = 150)
#Audited(withModifiedFlag = true)
private String customerEntity; // customer entity is optional and can be same for multiple accounts
#NotNull
#Column(name = "CUSTOMER_REPORTING_MANAGER", nullable = false, length = 150)
#Audited(withModifiedFlag = true)
private String customerReportingManager;
#Column(name = "CUSTOMER_TIME_TRACKING", length = 1)
#Audited(withModifiedFlag = true)
private boolean customerTimeTracking = false;
#NotNull
#OneToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "ACCOUNT_MANAGER_CODE", unique = false, nullable = false, foreignKey = #ForeignKey(name = FK_ACCOUNTS_MGR_RESOURCE_CODE))
#Audited(withModifiedFlag = true, targetAuditMode = RelationTargetAuditMode.NOT_AUDITED, modifiedColumnName = "ACCOUNT_MANAGER_CODE_MOD")
private Resource accountManager;
Resource Entity
#Getter
#Accessors(chain = true, fluent = true)
#NoArgsConstructor
#ToString(of = { "name" }, callSuper = true)
#Entity
// #formatter:off
#Table(name = "RESOURCES",
uniqueConstraints = {
#UniqueConstraint(name = UNQ_RESOURCES_LOGIN_ID, columnNames = {"LOGIN_ID"}),
#UniqueConstraint(name = UNQ_RESOURCES_EMAIL_ID, columnNames = {"EMAIL_ID"}),
#UniqueConstraint(name = UNQ_RESOURCES_PAYROLL_ID, columnNames = {"PAYROLL_ID"})
},
indexes = {
#Index(name = IDX_RESOURCES_NAME, columnList = "NAME")
}
)
// #formatter:on
public class Resource extends BaseAutoAssignableVersionableEntity<String, Long> implements Diffable<Resource> {
public static final String EMAIL_ID = "Email ID";
public static final String GRAYT_HR_ID = "Grayt HR ID";
public static final String NAME = "Name";
public static final String GENEDER = "Gender";
public static final String DESIGNATION = "Designation";
public static final String TYPE_OF_RESOURCE = "Resource Type";
public static final String STATUS_OF_RESOURCE = "Resource Status";
public static final String BASE_LOCATION = "Base Location";
public static final String DEPUTED_LOCATION = "Deputed Location";
public static final String PRIMARY_SKILLS = "Primary Skills";
public static final String SECONDARY_SKILLS = "Secondary Skills";
public static final String EXPECTED_JOINING_DATE = "Expected Joining Date";
public static final String ACTUAL_JOINING_DATE = "Actual Joining Date";
public static final String EXIST_DATE = "Exist Date";
// #Pattern(regexp = REGEX_LOGIN_ID, message = MESSAGE_LOGIN_ID_INVALID)
// #NotNull(message = MESSAGE_LOGIN_ID_MANDATORY)
#Column(name = "LOGIN_ID", nullable = false, length = 100)
private String loginId;
#Email(message = MESSAGE_EMAIL_INVALID)
#Column(name = "EMAIL_ID", nullable = true, length = 255)
#Audited(withModifiedFlag = true)
private String emailId;
#Pattern(regexp = REGEX_PAYROLL_ID, message = MESSAGE_PAYROLL_ID_INVALID)
#Column(name = "PAYROLL_ID", nullable = true, length = 100)
#Audited(withModifiedFlag = true, modifiedColumnName = "PAYROLL_ID_MOD")
private String payrollId;
#NotNull
#Column(name = "NAME", nullable = false, length = 255)
#Audited(withModifiedFlag = true)
private String name;
#NotNull
#Enumerated(EnumType.STRING)
#Column(name = "GENDER", nullable = false, length = 10)
#Audited(withModifiedFlag = true)
private Gender gender;
#NotNull
#OneToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "DESIGNATION_ID", unique = false, nullable = false, foreignKey = #ForeignKey(name = FK_RESOURCES_DESIGNATION_ID))
#Audited(withModifiedFlag = true, targetAuditMode = RelationTargetAuditMode.NOT_AUDITED, modifiedColumnName = "DESIGNATION_ID_MOD")
private Designation designation;
#NotNull
#OneToOne(fetch = FetchType.EAGER, optional = false)
#JoinColumn(name = "EMP_TYPE_CODE", unique = false, nullable = false, foreignKey = #ForeignKey(name = FK_RESOURCES_EMP_TYPE_CODE))
#Audited(withModifiedFlag = true, targetAuditMode = RelationTargetAuditMode.NOT_AUDITED, modifiedColumnName = "EMP_TYPE_CODE_MOD")
private EmploymentType employmentType;
public boolean isFTE() {
return (this.employmentType.equals(EmploymentType.fullTimeEmployee()));
}
#Audited(withModifiedFlag = true, modifiedColumnName = "EMP_STATUS_ID_MOD")
#OneToOne(optional = false, cascade = CascadeType.PERSIST, orphanRemoval = true)
#JoinColumn(name = "emp_status_id", unique = false, foreignKey = #ForeignKey(name = FK_RESOURCES_EMP_STATUS_ID))
private EmploymentStatus employmentStatus;
When i'm creating the account, used the existing resource as account manager and created successfully. Then fetch the history successfully. But unfortunately deleted the resource record in resource_aud table, then fetch the history. It's throwing below error
javax.persistence.EntityNotFoundException: Unable to find com.gspann.itrack.domain.model.staff.Resource with id IN10000
at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl$JpaEntityNotFoundDelegate.handleEntityNotFound(EntityManagerFactoryBuilderImpl.java:159)
at org.hibernate.proxy.AbstractLazyInitializer.checkTargetState(AbstractLazyInitializer.java:244)
at org.hibernate.proxy.AbstractLazyInitializer.initialize(AbstractLazyInitializer.java:166)
at org.hibernate.proxy.AbstractLazyInitializer.getImplementation(AbstractLazyInitializer.java:268)
at org.hibernate.proxy.pojo.javassist.JavassistLazyInitializer.invoke(JavassistLazyInitializer.java:73)
at com.gspann.itrack.domain.model.staff.Resource_$$_jvst4e_12.name(Resource_$$_jvst4e_12.java)
at com.gspann.itrack.domain.model.business.Account.diff(Account.java:328)
at com.gspann.itrack.domain.model.business.Account.diff(Account.java:1)
at com.gspann.itrack.domain.model.common.audit.util.AuditQueryUtils.getAllRevisionById(AuditQueryUtils.java:66)
at com.gspann.itrack.domain.service.impl.AccountManagementServiceImpl.getAllRevisionByAccountCode(AccountManagementServiceImpl.java:268)
below is the query generated by hibernate envers
/* select
e__,
r
from
com.gspann.itrack.domain.model.business.Account_AUD e__,
com.gspann.itrack.audit.domain.CustomRevisionEntity r
where
e__.REVTYPE <> :_p0
and e__.originalId.code = :_p1
and e__.originalId.REV.id = r.id
order by
e__.originalId.REV.id asc */ select
account_au0_.code as code1_1_0_,
account_au0_.rev as rev2_1_0_,
customrevi1_.id as id1_49_1_,
account_au0_.revtype as revtype3_1_0_,
account_au0_.customer_entity as customer4_1_0_,
account_au0_.customer_entity_mod as customer5_1_0_,
account_au0_.customer_group as customer6_1_0_,
account_au0_.customer_group_mod as customer7_1_0_,
account_au0_.customer_name as customer8_1_0_,
account_au0_.customer_name_mod as customer9_1_0_,
account_au0_.customer_reporting_manager as custome10_1_0_,
account_au0_.customer_reporting_manager_mod as custome11_1_0_,
account_au0_.customer_time_tracking as custome12_1_0_,
account_au0_.customer_time_tracking_mod as custome13_1_0_,
account_au0_.account_manager_code as account14_1_0_,
account_au0_.account_manager_code_mod as account15_1_0_,
account_au0_.country_code as country16_1_0_,
account_au0_.country_code_mod as country17_1_0_,
customrevi1_.last_modified_on as last_mod2_49_1_,
customrevi1_.modified_by as modified3_49_1_,
customrevi1_.timestamp as timestam4_49_1_
from
accounts_aud account_au0_ cross
join
revinfo customrevi1_
where
account_au0_.revtype<>?
and account_au0_.code=?
and account_au0_.rev=customrevi1_.id
order by
account_au0_.rev asc
after calling getter method of resource it's generating another resource related query like below
/* select
e__
from
com.gspann.itrack.domain.model.staff.Resource_AUD e__
where
e__.originalId.REV.id = (
select
max(e2__.originalId.REV.id)
from
com.gspann.itrack.domain.model.staff.Resource_AUD e2__
where
e2__.originalId.REV.id <= :revision
and e__.originalId.code = e2__.originalId.code
)
and e__.REVTYPE <> :_p0
and e__.originalId.code = :_p1 */ select
resource_a0_.code as code1_48_,
resource_a0_.rev as rev2_48_,
resource_a0_.revtype as revtype3_48_,
resource_a0_.actual_joining_date as actual_j4_48_,
resource_a0_.actual_joining_date_mod as actual_j5_48_,
resource_a0_.email_id as email_id6_48_,
resource_a0_.email_id_mod as email_id7_48_,
resource_a0_.exit_date as exit_dat8_48_,
resource_a0_.exit_date_mod as exit_dat9_48_,
resource_a0_.gender as gender10_48_,
resource_a0_.gender_mod as gender_11_48_,
resource_a0_.name as name12_48_,
resource_a0_.name_mod as name_mo13_48_,
resource_a0_.payroll_id as payroll14_48_,
resource_a0_.payroll_id_mod as payroll15_48_,
resource_a0_.utilization as utiliza16_48_,
resource_a0_.utilization_mod as utiliza17_48_,
resource_a0_.utilization_type as utiliza18_48_,
resource_a0_.utilization_type_mod as utiliza19_48_,
resource_a0_.base_loc_id as base_lo20_48_,
resource_a0_.base_loc_id_mod as base_lo21_48_,
resource_a0_.deputed_loc_id as deputed22_48_,
resource_a0_.deputed_loc_id_mod as deputed23_48_,
resource_a0_.designation_id as designa24_48_,
resource_a0_.designation_id_mod as designa25_48_,
resource_a0_.emp_status_id as emp_sta26_48_,
resource_a0_.emp_status_id_mod as emp_sta27_48_,
resource_a0_.emp_type_code as emp_typ28_48_,
resource_a0_.emp_type_code_mod as emp_typ29_48_,
resource_a0_.image_id as image_i30_48_,
resource_a0_.image_id_mod as image_i31_48_
from
resources_aud resource_a0_
where
resource_a0_.rev=(
select
max(resource_a1_.rev)
from
resources_aud resource_a1_
where
resource_a1_.rev<=?
and resource_a0_.code=resource_a1_.code
)
and resource_a0_.revtype<>?
and resource_a0_.code=?
below is the code to fetch the revisions
AuditReader auditReader = this.getAuditReader();
return auditReader.createQuery().forRevisionsOfEntity(clazz, selectedEntitiesOnly, selectDeletedEntities);
My question is, why it's referring to audit table instead of main table?
Thank in advance
I want to persist an entity(MyEntity) with merge method. This entity have some beans validation.
public class MyEntity extends AbstractEntity {
#Basic(optional = false)
#Column(name = "city", length = 255, nullable = false)
#NotNull
#NotEmpty(message = "{myentity.validation.size.name}")
private String city;
private String number;
#Basic(optional = false)
#Column(name = "zipcode", length = 255, nullable = false)
#NotNull
private String zipcode;
private String phoneNumber;
#Email(message = "{myentity.validation.conform.email}")
#Size(min = 2, max = 100, message = "{myentity.validation.size.email}")
private String email;
private String website;
private String gpsLocation;
#ElementCollection()
#CollectionTable(name = "translation_poi", joinColumns = #JoinColumn(name = "point_id"))
#MapKeyJoinColumn(name = "locale")
#NotEmpty
private Map<Locale, MyEntityI18n> translations = new HashMap<>();
}
#Embeddable
public class MyEntityI18n implements java.io.Serializable {
#Basic(optional = false)
#Column(name = "name", length = 255, nullable = false)
#NotNull
#NotEmpty(message = "{myentity.validation.size.name}")
private String name;
#Column(name = "comment", length = 1200)
private String comment;
#Column(name = "short_description", length = 1200)
private String shortDescription;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
The merge succeeded on an existing entity value but with a new entity the merge failed despite the fact that the following validation succeeded.
private boolean validate(MyEntity poi) {
boolean result = true;
Set<ConstraintViolation<MyEntity>> constraintViolations = validator.validate(poi);
if (constraintViolations.size() > 0) {
result = false;
for (ConstraintViolation<MyEntity> constraints : constraintViolations) {
FacesContext context = FacesContext.getCurrentInstance();
String message = constraints.getPropertyPath() + " " + constraints.getMessage();
context.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN, constraints.getMessage(), message));
}
}
return result;
}
Try to add a #Valid to MyEntity.translations property. I think that your validation method hasn't take account the MyEntityI18n.name validation.
About merge fails, Do you have a not-null DB constraint on the MyEntityI18n.name field?
Good luck!
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.
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 + " ]";
}
}
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