No property 'birthDate' found for type 'person'! Did you mean ''birthdate''? in srping boot - sql

I am developing and rest api and i want to filter a data by birthday. I create birthday variable as birthday in every where and when i compile my code i get an error that " No property 'birthDate' found for type 'person'! Did you mean ''birthdate''?". But i haven't make a variable as birthDate
entity
public class person {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY )
private long id;
#Column(name="Name")
private String name ;
#Column(name="surname")
private String surname;
#Column(name="Birthdate")
#JsonFormat(pattern = "yyyy-MM-dd")
private Date birthdate;
#OneToMany(targetEntity = address.class, cascade = CascadeType.ALL)
#JoinColumn(name ="per_id", referencedColumnName = "id")
private List<address> address = new ArrayList<>();
}
repository
public interface personRepository extends JpaRepository<person,Long> {
public List<person> findByName(String Name);
public List<person> findByBirthDate(Date birthdate);
}
controller
#GetMapping()
public List filterall(#RequestParam(required = false) String name, #RequestParam(required = false) Date birthdate){
//return null;
var personsByName = repository.findByName(name);
var personsByBday= repository.findByBirthDate(birthdate);
return personsByBday;
}
error!

Related

Cannot add or update a child row: a foreign key constraint fails when i try send a post request

I want to send message for a list of users, I have a message class and user class and each user can receive many messages, and a message can be send to multiple users. but when I try to send a message, I get the error "Cannot add or update a child row: a foreign key constraint fails
this is the message class
#Entity
#Getter
#Setter
public class Message {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#JsonProperty("objet")
private String objet;
#JsonProperty("contenu")
private String contenu;
#JsonFormat(pattern = "yyyy-MM-dd" )
#CreationTimestamp
private LocalDate dateReclamation = LocalDate.now();
#Enumerated(EnumType.STRING)
private Statut statut;
#ManyToOne
#JsonIgnore
private User user;
#ManyToMany
#JoinTable(
name = "message_destinataire",
joinColumns = #JoinColumn(name = "message_id"),
inverseJoinColumns = #JoinColumn(name = "destinataire_id"))
Set<User> destinataires;
#OneToMany(cascade = CascadeType.ALL)
private List<Reponse> reponses = new ArrayList<>();
}
this is the user class
#Entity
#Getter
#Setter
public class User {
#Id
private int id;
private String firstName;
private String lastName;
#ManyToMany(mappedBy = "user")
Set<Message> messages;
}
and this is method
public Message createNewMessage(Message message, int id){
User user = userRepository.findById(id);
if (user == null)
{
user = new User();
user.setId(id);
user.setFirstName(gestionAccesService.firstName(id));
user.setLastName(gestionAccesService.lastName(id));
userRepository.save(user);
message.setStatut(ENVOYER);
message.setUser(user);
return messageRepository.save(message);
}
message.setStatut(ENVOYER);
message.setUser(user);
return messageRepository.save(message);
}
Can Any one help me

java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Enum

I get this error while trying to persist an entity 'UserAccount' into the database table.
#Entity
#Table(name = "user_account")
public class UserAccount extends BaseEntity {
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "useraccount_id")
#MapKeyEnumerated(EnumType.STRING)
private Map<PhoneType, PhoneNumber> phones = new HashMap<PhoneType, PhoneNumber>();
//... other attributes
//... default constructor, getters and setters
}
public enum PhoneType {
HOME("home"),
MOBILE("mobile"),
FAX("fax"),
WORK("work");
private String value;
PhoneType(String value) {
this.value = value;
}
#JsonValue
public String getValue() {
return value;
}
}
#Entity
#Table(name = "phone_number")
public class PhoneNumber extends BaseEntity {
private String areaCode;
private String number;
//... default constructor, getters and setters
}
and finally..
public class UserAccountRepository {
#Inject
EntityManager entityManager;
#Override
public UserAccount save(UserAccount userAccount) {
if (userAccount.getId() == null) {
entityManager.persist(userAccount);
} else {
userAccount = entityManager.merge(userAccount);
}
return userAccount;
}
//.. other methods
}
Caused by: java.lang.ClassCastException: java.lang.String cannot be cast to java.lang.Enum
at org.eclipse.persistence.mappings.converters.EnumTypeConverter.convertObjectValueToDataValue(EnumTypeConverter.java:165)
at org.eclipse.persistence.mappings.foundation.AbstractDirectMapping.extractIdentityFieldsForQuery(AbstractDirectMapping.java:568)
at org.eclipse.persistence.internal.queries.MappedKeyMapContainerPolicy.getKeyMappingDataForWriteQuery(MappedKeyMapContainerPolicy.java:145)
at org.eclipse.persistence.mappings.OneToManyMapping.updateTargetRowPostInsertSource(OneToManyMapping.java:1425)
at org.eclipse.persistence.mappings.OneToManyMapping.performDataModificationEvent(OneToManyMapping.java:936)
at org.eclipse.persistence.internal.sessions.CommitManager.commitAllObjectsWithChangeSet(CommitManager.java:162)
at org.eclipse.persistence.internal.sessions.AbstractSession.writeAllObjectsWithChangeSet(AbstractSession.java:4387)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabase(UnitOfWorkImpl.java:1493)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.commitToDatabaseWithChangeSet(UnitOfWorkImpl.java:1583)
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.issueSQLbeforeCompletion(UnitOfWorkImpl.java:3258)
at org.eclipse.persistence.internal.sessions.RepeatableWriteUnitOfWork.issueSQLbeforeCompletion(RepeatableWriteUnitOfWork.java:357)
at org.eclipse.persistence.transaction.AbstractSynchronizationListener.beforeCompletion(AbstractSynchronizationListener.java:160)
at org.eclipse.persistence.transaction.JTASynchronizationListener.beforeCompletion(JTASynchronizationListener.java:70)
at com.sun.enterprise.transaction.JavaEETransactionImpl.commit(JavaEETransactionImpl.java:452)
... 94 more
Other questions with same error suggest to add #Enumerated(EnumType.STRING) on the attribute of type Enum, I have used #MapKeyEnumerated(EnumType.STRING) on the phones Map, but I still see get this error. Any clues where am I wrong?
Please let me know if I haven't asked the question as per the SO guidance, I will correct it (as this is my 1st question).
I made a change to the PhoneNumber class as below
#Entity
#Table(name = "phone_number")
public class PhoneNumber extends BaseEntity {
private PhoneType type;
private String areaCode;
private String number;
//... default constructor, getters and setters
}
and then added #MapKey(name = "type") in the UserAccount as below.
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "useraccount_id")
#MapKeyEnumerated(EnumType.STRING)
#MapKey(name = "type")
private Map<PhoneType, PhoneNumber> phones = new HashMap<PhoneType, PhoneNumber>();
With these changes I am now able to save the UserAccount object successfully into the db tables.

Hibernate queryexception: could not resolve entity property during JPA query

I am trying to query my hibernate table for a RunEntity. The first where clause in the query searches for RunEntities where the testName = the passed value testname. In the stacktrace, it mentions that it cannot find a match for type testname in the RunEntity, but the RunEntity object explicitly has a string named testName with setters and getters and #Column notation.
Table setup
CREATE TABLE RunEntity (ID INTEGER IDENTITY,TestNumber INTEGER NOT NULL, TestName varchar(50) NOT NULL, ENVIRONMENT VARCHAR(50) NOT NULL, Source VARCHAR(50), Date TIMESTAMP, RESULTFILES BLOB);
Query
#Query("SELECT r FROM RunEntity r WHERE r.testName = :testname AND r.testNumber = :testnumber AND r.environment = :environment AND r.source = :source")
public List<RunEntity> findByNameNumberEnvironmentSource(
#Param("testname") String testname,
#Param("testnumber") int testnumber,
#Param("environment") String environment,
#Param("source") String source);
Entity
package com.web_application;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Lob;
#Entity
#Table(name = "TESTRUNS")
public class RunEntity {
private int ID;
private int testNumber;
private String testName;
private String environment;
private String source;
private String passOrFail;
private Timestamp date;
private byte[] resultFiles;
#Id
#Column(name = "ID")
#GeneratedValue
public int getID()
{
return this.ID;
}
public void setID(int ID){this.ID = ID;}
#Column(name="TestNumber")
public int getTestNumber()
{
return this.testNumber;
}
public void setTestNumber(int testNum){this.testNumber = testNum;}
#Column(name="TestName")
public String testName()
{
return this.testName;
}
public void setTestName(String testName){this.testName = testName;}
#Column(name="Environment")
public String getEnvironment()
{
return this.environment;
}
public void setEnvironment(String enviro){this.environment = enviro;}
#Column(name="Source")
public String getSource()
{
return this.source;
}
public void setSource(String src){this.source = src;}
#Column(name="PassOrFail")
public String getPassOrFail()
{
return this.passOrFail;
}
public void setPassOrFail(String pOrF){this.passOrFail = pOrF;}
#Column(name="Date")
public Timestamp getDate()
{
return this.date;
}
public void setDate(Timestamp dates){this.date = dates;}
#Lob
#Column(name="ResultFiles")
public byte[] getResultFiles()
{
return this.resultFiles;
}
public void setResultFiles(byte[] file){this.resultFiles = file;}
}
Part of stacktrace
Caused by: org.hibernate.QueryException: could not resolve property: testname of: com.web_application.RunEntity [SELECT r FROM com.web_application.RunEntity r WHERE r.testname = :testname AND r.testNumber = :testnumber AND r.environment = :environment AND r.source = :source]
at org.hibernate.QueryException.generateQueryException(QueryException.java:137)
at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:120)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:234)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:158)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:126)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:88)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:190)
at org.hibernate.internal.AbstractSessionImpl.getHQLQueryPlan(AbstractSessionImpl.java:301)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:236)
at org.hibernate.internal.SessionImpl.createQuery(SessionImpl.java:1800)
at org.hibernate.jpa.spi.AbstractEntityManagerImpl.createQuery(AbstractEntityManagerImpl.java:328)
... 66 more
Change this
#Column(name="TestName")
public String testName()
{
return this.testName;
}
to
#Column(name="TestName")
public String getTestName()
{
return this.testName;
}
Property access Naming convention is important.Try to use IDE for example (Eclipse Getter-Setter,instead using manually doing it)
Correct your testName() getter to getTestName(). You are using Property Access and have to stick to JavaBeans convention.

How to use hibernate lucene search for entity which have many to one relation

I am using Hibernate lucene for searching. Now I want to search with an entity which has a many to one relation
I have two class one is catalogueBase and another one is Subject, here subject has a many-to-one relation (it is one sided relation)
catalogueBase.java class :
#Indexed
#JsonAutoDetect
#Entity
#Table(name="catalogueBase")
public class CatalogueBase extends BaseObject implements Serializable {
// some entities
// ...
private Subject subject;
// setter and get methods
// ...
#Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES)
#ManyToOne
#NotFound(action= NotFoundAction.IGNORE)
#JoinColumn(name = "subject1", insertable = true, updatable=true, nullable = true)
#JsonProperty
public Subject getSubject() {
return subject;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
}
Subject.java (what ever i want to search regarding subject it will be stored in description column) :
#Indexed
#JsonAutoDetect
#Entity
#Table(name="subject")
public class Subject implements java.io.Serializable {
private String description;
// ...
#Column(name = "subjectname", nullable = false, length = 150)
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
// ....
}
this is my DAO method :
private List<CatalogueBase> searchTitle(String queryString) throws InterruptedException {
Session session = getSession();
FullTextSession fullTextSession = Search.getFullTextSession(session);
fullTextSession.createIndexer().startAndWait();
org.hibernate.Query fullTextQuery = null;
List<CatalogueBase> resultList = null;
try{
QueryBuilder queryBuilder = fullTextSession.getSearchFactory().buildQueryBuilder().forEntity(CatalogueBase.class).get();
org.apache.lucene.search.Query luceneQuery = queryBuilder.keyword().onFields("title","subject").matching(queryString).createQuery();
fullTextQuery = fullTextSession.createFullTextQuery(luceneQuery, CatalogueBase.class);
List<CatalogueBase> contactList = fullTextQuery.list();
resultList = new ArrayList<CatalogueBase>();;
for (CatalogueBase catalogueBase : contactList) {
catalogueBase.setNoOfCopiesBooks(getCopydetailsCount(catalogueBase.getId()));
catalogueBase.setIssuedCount(getIssuedCount(catalogueBase.getId()));
resultList.add(catalogueBase);
}
} catch(Exception e) {
e.printStackTrace();
}
return resultList;
}
But it's giving an error like: SearchException: Unable to find field subject in com.easylib.elibrary.model.CatalogueBase
And I did something like this post, but error was the same.
I got solution.
I will just post code...
#Indexed // must
#JsonAutoDetect
#Entity
#Table(name="subject")
public class Subject implements java.io.Serializable {
private String description;
#ContainedIn // must
#Field(index = Index.YES, analyze = Analyze.YES, store = Store.YES)
#Column(name = "subjectname", nullable = false, length = 150)
public String getDescription() {
return this.description;
}
}
In catalogue:
#ManyToOne
#NotFound(action= NotFoundAction.IGNORE)
#JoinColumn(name = "subject1", insertable = true, updatable=true, nullable = true)
#JsonProperty
#IndexedEmbedded // must
public Subject getSubject() {
return subject;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
And in the DAO, it must be:
org.apache.lucene.search.Query luceneQuery = queryBuilder.keyword().onFields("subject.description").matching(queryString).createQuery();

Why are the foreign keys in ejb declared as objects(entities)?

I'am developing a java web EE application using EJB, JPA and netbeans. I've created a table with sql named users for registration and login and another table named prescripts which has 3 foreign keys refering to the primary key idusers of users(docid, pharmid, patid).
I also created with net beans entity bean named users and a session bean named UsersFacade and for prescripts an entity bean: prescripts and session bean: PrescriptsFacade.
My question is this:
Why in users ejb all variables(columns) are declared as they are(string for string, integer for integer etc) and in prescripts are declared as users?
//users.java
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idusers")
private Integer idusers;
#Column(name = "user_type")
private String userType;
#Column(name = "name")
private String name;
#Column(name = "nickname")
private String nickname;
//prescripts.java
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idprescripts")
private Integer idprescripts;
#Column(name = "data")
private String data;
#JoinColumn(name = "pharm_id", referencedColumnName = "idusers")
#ManyToOne
private Users users;
#JoinColumn(name = "doc_id", referencedColumnName = "idusers")
#ManyToOne
private Users users1;
#JoinColumn(name = "pat_id", referencedColumnName = "idusers")
#ManyToOne
private Users users2;
For users i use this code in a servlet to insert a row in sql base:
Users currentUsers;
currentUsers = new Users();
String Type = request.getParameter("user_type");
String Name = request.getParameter("name");
String Nickname = request.getParameter("nickname");
currentUsers.setUserType(Type);
currentUsers.setName(Name);
currentUsers.setNickname(Nickname);
UsersFacade.create(currentUsers);
How am i supposed to insert a row in prescripts this way?
This doesn't work(it shows error null pointer exception):
currentPresc = new Prescripts();
String PatID = request.getParameter("pat_id");
String DocID = request.getParameter("doc_id");
String PharmID = request.getParameter("pharm_id");
String Data = request.getParameter("data");
int patid = Integer.parseInt(PatID);
int docid = Integer.parseInt(DocID);
int pharmid = Integer.parseInt(PharmID);
currentUsers = UsersFacade.find(patid);
currentPresc.setUsers(currentUsers);
currentUsers = UsersFacade.find(docid);
currentPresc.setUsers1(currentUsers);
currentUsers = UsersFacade.find(pharmid);
currentPresc.setUsers2(currentUsers);
currentPresc.setData(Data);
PrescriptsFacade.create(currentPresc);
I skipped the set and get methods and some variables for simplifying reasons. Please any help is really very appreciated, i am stucked with this 2 weeks now :'(
I send you the whole classes of users and prescripts:
Prescripts.java
package entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
#Entity
#Table(name = "prescripts")
#NamedQueries({
#NamedQuery(name = "Prescripts.findAll", query = "SELECT p FROM Prescripts p"),
#NamedQuery(name = "Prescripts.findByIdprescripts", query = "SELECT p FROM Prescripts p WHERE p.idprescripts = :idprescripts"),
#NamedQuery(name = "Prescripts.findByData", query = "SELECT p FROM Prescripts p WHERE p.presc = :presc")})
public class Prescripts implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idprescripts")
private Integer idprescripts;
#JoinColumn(name = "doc_id", referencedColumnName = "idusers")
#ManyToOne
private Users doc_id;
#JoinColumn(name = "pat_id", referencedColumnName = "idusers")
#ManyToOne
private Users pat_id;
#JoinColumn(name = "pharm_id", referencedColumnName = "idusers")
#ManyToOne
private Users pharm_id;
#Column(name = "presc")
private String presc;
public Prescripts() {
}
public Prescripts(Users pat_id, Users pharm_id, Users doc_id, String presc) {
this.pharm_id = pharm_id;
this.doc_id = doc_id;
this.pat_id = pat_id;
this.presc = presc;
}
public Integer getIdprescripts() {
return idprescripts;
}
public void setIdprescripts(Integer idprescripts) {
this.idprescripts = idprescripts;
}
public String getPresc() {
return presc;
}
public void setPresc(String presc) {
this.presc = presc;
}
public Users getPharmId() {
return pharm_id;
}
public void setPharmId(Users pharm_id) {
this.pharm_id = pharm_id;
}
public Users getDocId() {
return doc_id;
}
public void setDocId(Users doc_id) {
this.doc_id = doc_id;
}
public Users getPatId() {
return pat_id;
}
public void setPatId(Users pat_id) {
this.pat_id = pat_id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idprescripts != null ? idprescripts.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 Prescripts)) {
return false;
}
Prescripts other = (Prescripts) object;
if ((this.idprescripts == null && other.idprescripts != null) || (this.idprescripts != null && !this.idprescripts.equals(other.idprescripts))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.Prescripts[idprescripts=" + idprescripts + "]";
}
}
Users.java
package entities;
import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.persistence.*;
import javax.xml.bind.annotation.XmlTransient;
#Entity
#Table(name = "users")
#NamedQueries({
#NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u"),
#NamedQuery(name = "Users.findByIdusers", query = "SELECT u FROM Users u WHERE u.idusers = :idusers"),
#NamedQuery(name = "Users.findByUserType", query = "SELECT u FROM Users u WHERE u.userType = :userType"),
#NamedQuery(name = "Users.findByNickname", query = "SELECT u FROM Users u WHERE u.nickname = :nickname"),
#NamedQuery(name = "Users.findByName", query = "SELECT u FROM Users u WHERE u.name = :name"),
#NamedQuery(name = "Users.findByPassword", query = "SELECT u FROM Users u WHERE u.password = :password"),
#NamedQuery(name = "Users.findByEmail", query = "SELECT u FROM Users u WHERE u.email = :email"),
#NamedQuery(name = "Users.findByCity", query = "SELECT u FROM Users u WHERE u.city = :city"),
#NamedQuery(name = "Users.findByStreet", query = "SELECT u FROM Users u WHERE u.street = :street"),
#NamedQuery(name = "Users.findByAt", query = "SELECT u FROM Users u WHERE u.at = :at"),
#NamedQuery(name = "Users.findByAmka", query = "SELECT u FROM Users u WHERE u.amka = :amka"),
#NamedQuery(name = "Users.findByAfm", query = "SELECT u FROM Users u WHERE u.afm = :afm"),
#NamedQuery(name = "Users.findByVerify", query = "SELECT u FROM Users u WHERE u.verify = :verify")})
public class Users implements Serializable {
#OneToMany(mappedBy = "pat_id")
private List<Prescripts> prescriptsList;
#OneToMany(mappedBy = "doc_id")
private List<Prescripts> prescriptsList1;
#OneToMany(mappedBy = "pharm_id")
private List<Prescripts> prescriptsList2;
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idusers")
private Integer idusers;
#Column(name = "user_type")
private String userType;
#Column(name = "name")
private String name;
#Column(name = "nickname")
private String nickname;
#Column(name = "password")
private String password;
#Column(name = "email")
private String email;
#Column(name = "city")
private String city;
#Column(name = "street")
private String street;
#Column(name = "AT")
private String at;
#Column(name = "AMKA")
private String amka;
#Column(name = "AFM")
private String afm;
#Column(name = "verify")
private Boolean verify;
public Users() {
}
public Users( String userType,String name,String nickname, String password, String email, String city, String street, String at,
String amka, String afm, Boolean verify)
{
this.userType= userType;
this.name= name;
this.nickname= nickname;
this.password= password;
this.email = email;
this.city = city;
this.street = street;
this.at = at;
this.amka = amka;
this.afm = afm;
this.verify=verify;
}
public Integer getIdusers() {
return idusers;
}
public void setIdusers(Integer idusers) {
this.idusers = idusers;
}
public String getUserType() {
return userType;
}
public void setUserType(String userType) {
this.userType = userType;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getNickname() {
return nickname;
}
public void setNickname(String nickname) {
this.nickname = nickname;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getStreet() {
return street;
}
public void setStreet(String street) {
this.street = street;
}
public String getAt() {
return at;
}
public void setAt(String at) {
this.at = at;
}
public String getAmka() {
return amka;
}
public void setAmka(String amka) {
this.amka = amka;
}
public String getAfm() {
return afm;
}
public void setAfm(String afm) {
this.afm = afm;
}
public Boolean getVerify() {
return verify;
}
public void setVerify(Boolean verify) {
this.verify = verify;
}
#Override
public int hashCode() {
int hash = 0;
hash += (idusers != null ? idusers.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 Users)) {
return false;
}
Users other = (Users) object;
if ((this.idusers == null && other.idusers != null) || (this.idusers != null && !this.idusers.equals(other.idusers))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entities.Users[idusers=" + idusers + "]";
}
public List<Prescripts> getPrescriptsList() {
return prescriptsList;
}
public void setPrescriptsList(List<Prescripts> prescriptsList) {
this.prescriptsList = prescriptsList;
}
public List<Prescripts> getPrescriptsList1() {
return prescriptsList1;
}
public void setPrescriptsList1(List<Prescripts> prescriptsList1) {
this.prescriptsList1 = prescriptsList1;
}
public List<Prescripts> getPrescriptsList2() {
return prescriptsList2;
}
public void setPrescriptsList2(List<Prescripts> prescriptsList2) {
this.prescriptsList2 = prescriptsList2;
}
}
The main question seems to be why variables in the User-class is declared as Integer, but the "user_id-variable" in Prescript is declared as User.
This is simply the way EJB3 works. You are thinking to much in terms of sql and relational databases. You define the primary key of tables (e.g. Users.idusers) as if it was a column, but references to other objects (entities, to be precise) are defined using the natural object. Therefore the Prescripts.users is declared as a Users-object. The EJB platform will take care of transforming this into a database column (in this case probably named users_idusers), with the correct type (in this case Integer), but this is taken care of and you shouldn't need to care about that.
You should go through a EJB3 tutorial or two - there are plenty of these, and make sure you complete the tutorials. You seemed to have missed some of the basics. Also note that your code could have been much simpler. The "#Column"-annotations are usually not needed, mapped_by is usually not needed, column-names ditto, etc. Also use singular names (User instead of Users). The common standard for primarykeys is simply #Id Long id, making it easy to remember the name of the primary key for all entities (but some prefer distinct names).
To answer your actual problem we would need more information, including what is on TestServlet.java line 233. Your code seems more or less correct, but it is hard for others to verify that. Finding the Users-object from EntityManger/facade and then setting it into the Prescipts-object is the correct way to do it.
In java, relations between entities (in a entity-relationship model) is represented as references to objects, (one-to-one) or lists of references to objects (one-to-many)
A relational database implements relations between entities (rows in tables) as foreign keys, that matches the primary key for a row in another table.
(The word "relational" in a "relational database" does actually just mean that the columns (tuples) in a table is related to each other...The foreign key stuff is an addition.)
I generally considered smart to start with a proper entity-relationshop model before designing database tables all willy nilly...