I am trying to get rid of this error:
Exception Description: [class utilisateurs.modeles.Utilisateur] uses a non-entity [class java.util.Collection] as target entity in the relationship attribute [field adresses].
at org.eclipse.persistence.exceptions.ValidationException.nonEntityTargetInRelationship(ValidationException.java:1343)
.........
org.eclipse.persistence.internal.jpa.deployment.PersistenceUnitProcessor.processORMetadata(PersistenceUnitProcessor.java:526)
at org.eclipse.persistence.internal.jpa.EntityManagerSetupImpl.predeploy(EntityManagerSetupImpl.java:1320)
... 36 more
with the following entity:
utilisateurs.modeles;
import adresses.Adresse;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
#Entity(name="Utilisateur")
public class Utilisateur implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
public void setAdresses(Collection<Adresse> adresses) {
this.adresses = adresses;
}
private String firstname;
private String lastname;
private String login;
#ManyToOne(cascade=CascadeType.PERSIST)
private Collection<Adresse> adresses;
public Collection<Adresse> getAdresses() {
return adresses;
}
public Utilisateur() {
}
public Utilisateur(final String firstname, final String lastname, final String login) {
this.firstname = firstname;
this.lastname = lastname;
this.login = login;
}
//getters and setters here
#Override
public int hashCode() {
int hash = 0;
hash += (int) id;
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 Utilisateur)) {
return false;
}
Utilisateur other = (Utilisateur) object;
if (this.id != other.id) {
return false;
}
return true;
}
}
If you have any idea please.
Adresse is not an Entity, maybe you just forgot the #Entity annotation on that class?
The #ManyToOne annotation defines a relationship between entities.
Related
I'm using a One-To-One association between my Member and MemberRoles tables. I wanted them to share the same id as PK and FK in the database and did it. But I've got another problem. When I insert a Member, a MemberRole record is being inserted with it and Member record has the correct id in return response but MemberRole id is incorrect. It returns 0 like this:
{
"result": "Bulk user member saving is successfull. Members' informations are:",
"memberList": [
{
"id": 2,
"firstName": "Michael",
"lastName": "Schumacher",
"email": "ilkay.gune2l#kod5.org",
"enabled": false,
"memberLanguageCode": "tr",
"roleOfMember": {
"id": 0,
"email": "ilkay.gune2l#kod5.org",
"role": "ROLE_USER"
}
}
]
}
My Member Entity Class:
package com.ilkaygunel.entities;
import java.time.LocalDateTime;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.PrimaryKeyJoinColumn;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;
#Entity
#JsonInclude(Include.NON_NULL)
#NamedQueries({ #NamedQuery(name = "Member.findAll", query = "select m from Member m"),
#NamedQuery(name = "Member.findByFirstName", query = "select m from Member m where m.firstName =:firstName"),
#NamedQuery(name = "Member.findPasswordOfMember", query = "select m.password from Member m where m.id =:id"),
#NamedQuery(name = "Member.findByActivationToken", query = "select m from Member m where m.activationToken =:activationToken"),
#NamedQuery(name = "Member.findByEmail", query = "select m from Member m where m.email =:email") })
#Table(name = "MEMBER")
public class Member {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "MEMBER_ID")
private long id;
#Column(nullable = false)
private String firstName;
#Column(nullable = false)
private String lastName;
#Column(nullable = false, updatable = false)
private String email;
#Column(nullable = false, updatable = false)
private boolean enabled;
#Column(nullable = false)
private String password;
#Column(nullable = false)
private String memberLanguageCode;
#Column(updatable = false)
#JsonIgnore
private String activationToken;
#Column(updatable = false)
#JsonIgnore
private LocalDateTime activationTokenExpDate;
#OneToOne(cascade = CascadeType.ALL, mappedBy = "member", optional = false)
#PrimaryKeyJoinColumn(name = "MEMBER_ID")
private MemberRoles roleOfMember;
#Override
public String toString() {
return String.format("Member [id=%d, firstName='%s', lastName='%s', email='%s']", id, firstName, lastName,
email);
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
if (null != roleOfMember) {
roleOfMember.setId(id);
}
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public MemberRoles getRoleOfMember() {
return roleOfMember;
}
public void setRoleOfMember(MemberRoles roleOfMember) {
this.roleOfMember = roleOfMember;
}
public String getActivationToken() {
return activationToken;
}
public void setActivationToken(String activationToken) {
this.activationToken = activationToken;
}
public LocalDateTime getActivationTokenExpDate() {
return activationTokenExpDate;
}
public void setActivationTokenExpDate(LocalDateTime activationTokenExpDate) {
this.activationTokenExpDate = activationTokenExpDate;
}
public String getMemberLanguageCode() {
return memberLanguageCode;
}
public void setMemberLanguageCode(String memberLanguageCode) {
this.memberLanguageCode = memberLanguageCode;
}
}
And my MemberRoles Entity class:
package com.ilkaygunel.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.MapsId;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.OneToOne;
import javax.persistence.Table;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
#NamedQueries({
#NamedQuery(name = "MemberRoles.findByEmail", query = "select mr from MemberRoles mr where mr.email = :email") })
#Table(name = "MEMBERROLES")
public class MemberRoles {
#Id
#Column(name = "MEMBERROLES_ID")
private long id;
private String email;
private String role;
#MapsId
#OneToOne(optional = false)
#JoinColumn(name = "MEMBERROLES_ID", unique = true, nullable = false, updatable = false)
#JsonIgnore
private Member member;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Member getMember() {
return member;
}
public void setMember(Member member) {
this.member = member;
}
}
When I inserted a Member record, I check it on the database and see that Member and MemberRoles record have the same id. But why does MemberRoles area in response message has got id as 0?
My MemberSaveService class like this:
package com.ilkaygunel.service;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.mail.MessagingException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import com.ilkaygunel.constants.ConstantFields;
import com.ilkaygunel.entities.Member;
import com.ilkaygunel.entities.MemberRoles;
import com.ilkaygunel.exception.CustomException;
import com.ilkaygunel.exception.ErrorCodes;
import com.ilkaygunel.pojo.MemberOperationPojo;
#Service
public class MemberSaveService extends BaseService {
public MemberOperationPojo addUserMember(List<Member> memberList) {
return addBulkMember(memberList, ConstantFields.ROLE_USER.getConstantField());
}
public MemberOperationPojo addAdminMember(List<Member> memberList) {
return addBulkMember(memberList, ConstantFields.ROLE_ADMIN.getConstantField());
}
public MemberOperationPojo addBulkMember(List<Member> memberList, String role) {
Logger LOGGER = loggingUtil.getLoggerForMemberSaving(this.getClass());
LOGGER.log(Level.INFO, resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingMethod", "en"));
MemberOperationPojo memberOperationPojo = new MemberOperationPojo();
List<Member> savedMemberList = new ArrayList<>();
try {
memberUtil.checkEmailAddressAndLanguageOnMemberList(memberList, LOGGER);
for (Member member : memberList) {
addOneMember(member, role, LOGGER);
savedMemberList.add(member);
}
memberOperationPojo.setResult(
resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingSuccessfull", "en"));
memberOperationPojo.setMemberList(memberUtil.removeFieldsFromReturningMember(savedMemberList));
LOGGER.log(Level.INFO,
resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingSuccessfull", "en")
+ memberList);
} catch (CustomException customException) {
LOGGER.log(Level.SEVERE,
resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingFaled", "en")
+ customException.getErrorCode() + " " + customException.getErrorMessage());
memberOperationPojo.setErrorCode(customException.getErrorCode());
memberOperationPojo.setResult(customException.getErrorMessage());
} catch (Exception e) {
LOGGER.log(Level.SEVERE,
resourceBundleMessageManager.getValueOfProperty(role + "_bulkMemberAddingFaled", "en")
+ e.getMessage());
memberOperationPojo.setErrorCode(ErrorCodes.ERROR_10.getErrorCode());
memberOperationPojo.setResult(e.getMessage());
}
return memberOperationPojo;
}
private void addOneMember(Member member, String role, Logger LOGGER) throws MessagingException {
MemberOperationPojo memberOperationPojo = new MemberOperationPojo();
LOGGER.log(Level.INFO, resourceBundleMessageManager.getValueOfProperty(role + "_memberAddingMethod",
member.getMemberLanguageCode()));
member.setPassword(getHashedPassword(member.getPassword()));
member.setEnabled(false);
addMemberRolesObject(role, member);
addActivationToken(member);
memberFacade.create(member);
// mailUtil.sendActivationMail(member.getEmail(), member.getActivationToken());
memberOperationPojo.setResult(resourceBundleMessageManager.getValueOfProperty(role + "_memberAddingSuccessfull",
member.getMemberLanguageCode()));
LOGGER.log(Level.INFO, resourceBundleMessageManager.getValueOfProperty(role + "_memberAddingSuccessfull",
member.getMemberLanguageCode()) + member);
}
private String getHashedPassword(String rawPassword) {
return new BCryptPasswordEncoder().encode(rawPassword);
}
private void addMemberRolesObject(String role, Member member) {
MemberRoles rolesOfMember = new MemberRoles();
rolesOfMember.setRole(role);
rolesOfMember.setEmail(member.getEmail());
rolesOfMember.setMember(member);
member.setRoleOfMember(rolesOfMember);
}
private void addActivationToken(Member member) {
String activationToken = UUID.randomUUID().toString();
member.setActivationToken(activationToken);
LocalDateTime activationTokenExpDate = LocalDateTime.now().plusDays(1);
// LocalDateTime activationTokenExpDate = LocalDateTime.now();//Use for expire
// date test!
member.setActivationTokenExpDate(activationTokenExpDate);
}
}
My Web Service End Point Class like this:
package com.ilkaygunel.restservice;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import com.ilkaygunel.entities.Member;
import com.ilkaygunel.pojo.MemberOperationPojo;
import com.ilkaygunel.service.MemberSaveService;
#RestController
#RequestMapping("/memberPostWebServiceEndPoint")
public class MemberSaveWebServiceEndPoint {
#Autowired
private MemberSaveService memberSaveService;
#RequestMapping(value = "/saveUserMember", method = RequestMethod.POST)
public ResponseEntity<MemberOperationPojo> saveUserMember(#RequestBody List<Member> memberList) {
MemberOperationPojo memberOperationPojo = memberSaveService.addUserMember(memberList);
return new ResponseEntity<MemberOperationPojo>(memberOperationPojo, HttpStatus.OK);
}
#RequestMapping(value = "/saveAdminMember", method = RequestMethod.POST)
public ResponseEntity<MemberOperationPojo> saveAdminMember(#RequestBody List<Member> memberList) {
MemberOperationPojo memberOperationPojo = memberSaveService.addAdminMember(memberList);
return new ResponseEntity<MemberOperationPojo>(memberOperationPojo, HttpStatus.OK);
}
}
I'm working with many-to-one relationship between my two tables(Employee and Department) in which any Employee can work in more than one department. I used the #ManyToOne annotation on the Department object field which I created in Employee entity class. Now when I persist the Employee entity with a particular department, it works fine but when I try to persist another Employee entity with the same department, it creates a new Department entity with the same name and persists it with different id. What I expect it to do is that when I persist an Employee entity with already persisted department, it should just update the foriegn key of the Employee entity to point the id of that department. Sorry if I didnt got the many-to-one concept totally.
EMPLOYEE entity
package com.test.domain;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.TableGenerator;
#Entity
public class Employee {
#TableGenerator(name="Empl_Gen", table="ID_GEN",pkColumnName="GEN_NAME",valueColumnName="GEN_VALUE", initialValue=0, allocationSize=1)
#Id#GeneratedValue(generator="Empl_Gen",strategy=GenerationType.TABLE)
private Long id;
private String Name;
private String Country;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="DEPT_ID")
private Department department;
public Department getDepartment() {
return department;
}
public void setDepartment(Department department) {
this.department = department;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return Name;
}
public void setName(String name) {
Name = name;
}
public String getCountry() {
return Country;
}
public void setCountry(String country) {
Country = country;
}
}
DEPARTMENT entity
package com.test.domain;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.TableGenerator;
#Entity
public class Department {
#TableGenerator(name="DEP_GEN",table="ID_GEN",pkColumnName="GEN_NAME",valueColumnName="GEN_VALUE", pkColumnValue="DEP_GEN",initialValue=0,allocationSize=1)
#Id#GeneratedValue(strategy=GenerationType.TABLE,generator="DEP_GEN")
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
package com.test.controllers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.test.domain.Employee;
import com.test.service.EmployeeService;
/**
* Handles requests for the application home page.
*/
#Controller
#RequestMapping("/addEmployee")
public class HomeController {
#Autowired
EmployeeService service;
#RequestMapping(method=RequestMethod.GET)
public String getform(Model model)
{
model.addAttribute("employee",new Employee());
return "home";
}
#RequestMapping(method=RequestMethod.POST)
public String setform(Employee employee)
{
service.save(employee);
return"success";
}
}
package com.test.dao;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.test.domain.Employee;
#Repository
#Transactional
public class Employeedaoimpl implements Employeedao
{
#PersistenceContext
EntityManager manager;
#Override
public void save(Employee employee) {
manager.persist(employee);
}
}
Try this:
#TableGenerator(name="DEP_GEN",table="ID_GEN",pkColumnName="GEN_NAME",valueColumnName="GEN_VALUE", pkColumnValue="DEP_GEN",initialValue=0,allocationSize=1)
#Id#GeneratedValue(strategy=GenerationType.TABLE,generator="DEP_GEN")
#Column(name = "DEPT_ID")
private Long id;
I don't know how I can persist an entity(with enum) to the database.
When I fill my form like this;
form.setTypZamowienia(SlownikZamowienie.SENIOR)
then 666 is stored in the database. But when I try like this;
form.setTypZamowienia(SlownikZamowienie.valueOf(request.getParameter("typKlienta").trim()));
0 is stored in the database.
How do I make this work?
For any help I will be very grateful.
My enum :
public enum SlownikZamowienie
{
JUNIOR(42),
SENIOR(666),
PRINCIPAL(31416);
private final int wartosc;
SlownikZamowienie(int wartosc) {
this.wartosc = wartosc;
}
}
My Entity:
package test.jpa.domain;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import test.enums.SlownikZamowienie;
#Entity
#Table(name="Piess")
public class Pies implements Serializable {
private static final Long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="id")
int id;
#Column(name = "imie")
String imie;
#Enumerated
#Column(name = "rasa")
SlownikZamowienie typzamowienia;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getImie() {
return imie;
}
public void setImie(String imie) {
this.imie = imie;
}
public SlownikZamowienie getTypzamowienia() {
return typzamowienia;
}
public void setTypzamowienia(SlownikZamowienie typzamowienia) {
this.typzamowienia = typzamowienia;
}
}
As of JPA 2.1 you can use an attribute converter (known as a UserType in the Hibernate world). See these two articles for details on how to implement such a solution:
www.thoughts-on-java.org/jpa-21-type-converter-better-way-to/
www.thoughts-on-java.org/jpa-21-how-to-implement-type-converter/
so I followed this tutorial video (source)
to create a Java Enterprise Web Application and have ran into a problem. As this is pretty much the first time working with stuff like this for me I am clueless regarding how to solve this.
When trying to run the project I get an error saying "The module has not been deployed. See the server log for details." After some time trying to find out what was wrong I figured it is most likely the error I have in my "Student.java"-class. It says "cannot find symbol classTable. Create Subclass Create Test Class". What may be the problem here? I'm not sure what code would be relevant as I am a complete beginner to this, but all my files are exact copies of the source code-wise. Here is Student.java:
package com.joseph.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
/**
*
* #author Joseph
*/
#Entity
#Table
#NamedQueries({#NamedQuery(name="Student.getAll",query="SELECT e FROM Student e")})
public class Student implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column
private int studentId;
#Column
private String firstname;
#Column
private String lastname;
#Column
private int yearLevel;
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public int getYearLevel() {
return yearLevel;
}
public void setYearLevel(int yearLevel) {
this.yearLevel = yearLevel;
}
public Student(int studentId, String firstname, String lastname, int yearLevel) {
this.studentId = studentId;
this.firstname = firstname;
this.lastname = lastname;
this.yearLevel = yearLevel;
}
public Student(){}
}
I'm using Toplink Grid(Eclipselink) as the my JPA implementation framework.
I met a a exception as below while I tried to use Criteria to query a Embeddable object:
Exception [EclipseLink-6119] (Eclipse Persistence Services - 2.1.2.v20101206-r8635): org.eclipse.persistence.exceptions.QueryException
Exception Description: The join expression
Query Key conInfo
Base domain.de1003.Employee is not valid, or for a mapping type that does not support joining.
Query: ReportQuery(referenceClass=Employee )
at org.eclipse.persistence.exceptions.QueryException.mappingForExpressionDoesNotSupportJoining(QueryException.java:659)
at org.eclipse.persistence.internal.queries.JoinedAttributeManager.prepareJoinExpression(JoinedAttributeManager.java:851)
at org.eclipse.persistence.internal.queries.JoinedAttributeManager.prepareJoinExpressions(JoinedAttributeManager.java:778)
at org.eclipse.persistence.internal.queries.ReportItem.initialize(ReportItem.java:171)
at org.eclipse.persistence.queries.ReportQuery.prepare(ReportQuery.java:1035)
at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:509)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.checkPrepare(ObjectLevelReadQuery.java:822)
at org.eclipse.persistence.queries.DatabaseQuery.checkPrepare(DatabaseQuery.java:470)
at org.eclipse.persistence.queries.DatabaseQuery.execute(DatabaseQuery.java:710)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.execute(ObjectLevelReadQuery.java:1038)
at org.eclipse.persistence.queries.ReadAllQuery.execute(ReadAllQuery.java:381)
at org.eclipse.persistence.queries.ObjectLevelReadQuery.executeInUnitOfWork(ObjectLevelReadQuery.java:1124)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.internalExecuteQuery(UnitOfWorkImpl.java:2917)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1291)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1273)
at org.eclipse.persistence.internal.sessions.AbstractSession.executeQuery(AbstractSession.java:1247)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.executeReadQuery(EJBQueryImpl.java:479)
at org.eclipse.persistence.internal.jpa.EJBQueryImpl.getResultList(EJBQueryImpl.java:714)
And the code I tried are as below:
CriteriaBuilder cb = em.getCriteriaBuilder();
CriteriaQuery<ContactInfo> cq = cb.createQuery(ContactInfo.class);
Root<Employee> root = cq.from(Employee.class);
cq.select(root.<ContactInfo> get("conInfo"));
cq.where(cb.le(root.<Long> get("employId"), 3));
TypedQuery<ContactInfo> q = em.createQuery(cq);
List<ContactInfo> results = q.getResultList();
In Which ContactInfo is an embeddable class consisting of an address and set of phones. Phone is String filed.
Any help will be very appreciated.
I check the question related to this issue:
JPA - Criteria API and EmbeddedId
But it didn't solve my question.
And I can't find any example code.
TO James:
The entity code as below:
package domain.de1003;
import java.io.IOException;
import java.io.Serializable;
import java.util.List;
import javax.persistence.AttributeOverrides;
import javax.persistence.AttributeOverride;
import javax.persistence.CascadeType;
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Embedded;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import javax.persistence.Version;
import oracle.eclipselink.coherence.integrated.config.GridCacheCustomizer;
import org.eclipse.persistence.annotations.Customizer;
import com.tangosol.io.pof.PofReader;
import com.tangosol.io.pof.PofWriter;
import com.tangosol.io.pof.PortableObject;
#Entity(name="Employee")
#Table(name="EMPLOYEE")
#Customizer(oracle.eclipselink.coherence.integrated.config.GridCacheCustomizer.class)
public class Employee implements PortableObject,Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "EM_ID")
private long employId;
#Column(name = "FIRSTNAME")
private String firstName;
#Column(name = "LASTNAME")
private String lastName;
#Embedded
#AttributeOverrides({
#AttributeOverride(name="homePhone", column=#Column(name="HOMEPHONE")),
#AttributeOverride(name="workPhone", column=#Column(name="WORKPHONE"))
})
private ContactInfo conInfo;
#Version
private long version;
public long getEmployId() {
return employId;
}
public void setEmployId(long employId) {
this.employId = employId;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public ContactInfo getConInfo() {
return conInfo;
}
public void setConInfo(ContactInfo conInfo) {
this.conInfo = conInfo;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
#Override
public void readExternal(PofReader pofReader) throws IOException {
employId = pofReader.readLong(1);
firstName = pofReader.readString(2);
lastName = pofReader.readString(3);
version = pofReader.readLong(4);
}
#Override
public void writeExternal(PofWriter pofWriter) throws IOException {
pofWriter.writeLong(1, employId);
if(firstName != null) pofWriter.writeString(2, firstName);
if(lastName != null) pofWriter.writeString(3,lastName);
pofWriter.writeLong(4, version);
}
#Override
public String toString() {
return "["
+ "employId = " + employId
+ " firstName = " + firstName
+ " lastName = " + lastName
+ " contact inforamtion: " + conInfo
+ "]";
}
}
and Entity ContactInfo
package domain.de1003;
import java.io.IOException;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import oracle.eclipselink.coherence.integrated.config.GridCacheCustomizer;
import org.eclipse.persistence.annotations.Customizer;
import com.tangosol.io.pof.PofReader;
import com.tangosol.io.pof.PofWriter;
import com.tangosol.io.pof.PortableObject;
#Embeddable
#Customizer(oracle.eclipselink.coherence.integrated.config.GridCacheCustomizer.class)
public class ContactInfo implements PortableObject,Serializable{
private static final long serialVersionUID = 1L;
#Column(name = "ADDRESS")
private String address;
#Column(name = "HOMEPHONE")
private String homePhone;
#Column(name = "WORKPHONE")
private String workPhone;
#Column(name = "CELLPHONE")
private String cellPhone;
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getHomePhone() {
return homePhone;
}
public void setHomePhone(String homePhone) {
this.homePhone = homePhone;
}
public String getWorkPhone() {
return workPhone;
}
public void setWorkPhone(String workPhone) {
this.workPhone = workPhone;
}
public String getCellPhone() {
return cellPhone;
}
public void setCellPhone(String cellPhone) {
this.cellPhone = cellPhone;
}
#Override
public void readExternal(PofReader pofReader) throws IOException {
address = pofReader.readString(1);
homePhone = pofReader.readString(2);
workPhone = pofReader.readString(3);
cellPhone = pofReader.readString(4);
}
#Override
public void writeExternal(PofWriter pofWriter) throws IOException {
if(address != null) pofWriter.writeString(1, address);
if(homePhone != null) pofWriter.writeString(2, homePhone);
if(workPhone != null) pofWriter.writeString(3, workPhone);
if(cellPhone != null) pofWriter.writeString(4, cellPhone);
}
#Override
public String toString() {
return "["
+ "address = " + address
+ " homePhone = " + homePhone
+ " workPhone = " + workPhone
+ " cellPhone = " + cellPhone
+ "]";
}
}
For the equivalent JQPL
Query query = em.createQuery("SELECT e.conInfo FROM Employee e where e.employId < 3");
worked.
I tried reproducing this in the latest EclipseLink (a 2.5 nightly) but couldn't. I suspect it might be fixed with criteria API changes to add On support - can you give it a shot to confirm it? You might have to turn off the cache to use the latest version of EclipseLink to test with though.
Check if conInfo is the correct name of your attribute (include your entity code).
Does the equivalent JPQL work?