I am using hibernate as a persistence layer, here is the sample of my code, but here my hql queries:
Query q = s.createQuery("from Login where name=:user and passw =:passw");
q.setParameter("user",username);
q.setParameter("passw", passw);
Query q = s.createSQLQuery("SELECT * from Good where Good.supplier =:supl AND Good.name =:gname AND Good.dates >=:sdate and Good.dates <=:fdate").addEntity(Good.class);
q.setParameter("supl",sup);
q.setParameter("gname", gname);
q.setParameter("sdate", sdate);
q.setParameter("fdate",fdate);
sdate and fdate parametrs are string, are they ok in this case? it throws this exception:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '.login login0_ where login0_.name='Tom'' at line 1
Login.hbm.xml
<hibernate-mapping>
<class name="kz.bimash.FoodSec.model.Login" table="login" catalog="foodsec">
<id name="id" type="java.lang.Integer">
<column name="Id" />
<generator class="increment" />
</id>
<property name="name" type="string">
<column name="name" length="50" not-null="true" unique="true" />
</property>
<property name="passw" type="string">
<column name="passw" length="50" not-null="true" />
</property>
<property name="type" type="string">
<column name="type" length="45" not-null="true" />
</property>
<property name="userId" type="int">
<column name="userId" not-null="true" />
</property>
</class>
Login pojo class
public class Login implements java.io.Serializable {
private Integer id;
private String name;
private String passw;
private String type;
private int userId;
public Login() {
}
public Login(String username, String password, String type, int userId) {
this.name = username;
this.passw = password;
this.type = type;
this.userId = userId;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String username) {
this.name = username;
}
public String getPassw() {
return this.passw;
}
public void setPassw(String password) {
this.passw = password;
}
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
public int getUserId() {
return this.userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
}
Login DAO class
#Repository
public class LoginDAO {
#Autowired
private SessionFactory sf;
#SuppressWarnings("empty-statement")
public String[] Authorise(String username, String passw){
Session s = sf.getCurrentSession();
s.beginTransaction();
Query q = s.createQuery("from Login where name=:user and passw =:passw");
q.setParameter("user",username);
q.setParameter("passw", passw);
q.setMaxResults(1);
String[] str = null;
Login login = null;
for(Iterator it = q.iterate(); it.hasNext();){
login = (Login)it.next();
}
if(login != null){
str = new String[]{login.getType(), String.valueOf(login.getUserId())};
}
s.getTransaction().commit();
return str;
}
public boolean checkLogin(String username){
Session s = sf.getCurrentSession();
s.beginTransaction();
// String s_sql ="SELECT * FROM Login WHERE NAME="+username;
Query q = s.createQuery("from Login where name = :usern");
q.setParameter("usern", username);
// Query q=s.createSQLQuery(s_sql);
List<Login> logins =null;
logins= (List<Login>)q.list();
s.getTransaction().commit();
if(logins !=null)
return true;
else
return false;
}
}
There's a problem with the following segment of the code:
Query q = s.createSQLQuery("SELECT * from Good where Good.supplier =:supl AND Good.name =:gname AND Good.dates >=:sdate and Good.dates <=:fdate").addEntity(Good.class);
You are writing an SQL & not an HQL. That is why you have used session.createSQLQuery(...) and not session.createQuery(...). createSQLQuery(...) always returns a reference of org.hibernate.SQLQuery, while you have assigned it to a variable of Query.
I'm surprised why didn't you get a Compile-time error.
Try to assign it to a SQLQuery variable & check whether it's working or not.
Related
I am trying to fire the following Hibernare quarry.
Query query = session.createSQLQuery("from Rating as rating where rating.organization.idorganization = :idorganization");
I always ended up with the error
hibernate.engine.jdbc.spi.SqlExceptionHelper.logExceptions You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'from Rating as rating where rating.organization.idorganization = 65' at line 1
org.hibernate.exception.SQLGrammarException: could not extract ResultSet
Below is my Rating bean
public class Rating implements java.io.Serializable {
private Integer idrating;
private Organization organization;
private User user;
private double rating;
private Date dateCreated;
private Date lastUpdated;
public Rating() {
}
public Rating(Organization organization, User user, double rating) {
this.organization = organization;
this.user = user;
this.rating = rating;
}
public Rating(Organization organization, User user, double rating, Date dateCreated, Date lastUpdated) {
this.organization = organization;
this.user = user;
this.rating = rating;
this.dateCreated = dateCreated;
this.lastUpdated = lastUpdated;
}
public Integer getIdrating() {
return this.idrating;
}
public void setIdrating(Integer idrating) {
this.idrating = idrating;
}
public Organization getOrganization() {
return this.organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
public User getUser() {
return this.user;
}
public void setUser(User user) {
this.user = user;
}
public double getRating() {
return this.rating;
}
public void setRating(double rating) {
this.rating = rating;
}
public Date getDateCreated() {
return this.dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public Date getLastUpdated() {
return this.lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
}
Below is the Rating.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 19, 2020 8:15:23 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="beans.Rating" table="rating" catalog="autocircle" optimistic-lock="version">
<id name="idrating" type="java.lang.Integer">
<column name="idrating" />
<generator class="identity" />
</id>
<many-to-one name="organization" class="beans.Organization" fetch="select">
<column name="idorganization" not-null="true" />
</many-to-one>
<many-to-one name="user" class="beans.User" fetch="select">
<column name="iduser" not-null="true" />
</many-to-one>
<property name="rating" type="double">
<column name="rating" precision="22" scale="0" not-null="true" />
</property>
<property name="dateCreated" type="timestamp">
<column name="date_created" length="0" />
</property>
<property name="lastUpdated" type="timestamp">
<column name="last_updated" length="0" />
</property>
</class>
</hibernate-mapping>
Why am I getting this error?
Since you are using createSQLQuery method, the SQL Statement should be used.
In this case, it should be
"select * from Rating as rating where
rating.organization.idorganization = :idorganization"
Or use the HQL Method and appropriate HQL Query
I am using hibernate in building a Restful Web Service (CRUD) in Java.
The problem is that when I return the data (GET) in some table that has some kind of relationship, I get the following error:
HTTP Status 500 - Internal Server Error
Type Exception Report
Message java.lang.UnsupportedOperationException: Attempted to serialize java.lang.Class: org.hibernate.proxy.HibernateProxy. Forgot to register a type adapter?
Description The server encountered an unexpected condition that prevented it from fulfilling the request.
When removing the bidirectional mapping created by hibernate on either side (table) the server returns to normal operation.
I use the Gson library to return and receive my requests in the JSON form.
Would anyone know how to solve this?
Thank you all for your help.
Here is a part of my controller code:
#GET
#Path("getConvenio")
#Produces(javax.ws.rs.core.MediaType.APPLICATION_JSON)
public String getConvenioList() {
Gson gson = new Gson();
List<Tbconveniado> l = new ArrayList();
try {
l = new ArrayList(op.getConveniadoList());
} catch (Exception ex) {
ex.printStackTrace();
}
return gson.toJson(l);
}
Following is the implementation of the "getConveniadoList" method that is present in the ConvenioOperations class:
public class ConvenioOperations {
public void setConvenio(Tbconveniado tb) {
Session s = HibernateUtil.getSessionFactory().openSession();
Transaction tx = s.beginTransaction();
s.saveOrUpdate(tb);
tx.commit();
s.close();
}
public List<Tbconveniado> getConveniadoList(){
Session s = HibernateUtil.getSessionFactory().openSession();
Transaction tx = s.beginTransaction();
List<Tbconveniado> l = null;
Query q = s.createQuery("from Tbconveniado c");
l = q.list();
tx.commit();
s.close();
return l;
}
}
Finally, the mapping and the class generated by hibernate to the table "Tbconveniado"
<hibernate-mapping>
<class name="pojos.Tbconveniado" table="tbconveniado" catalog="sindicatodb" optimistic-lock="version" >
<id name="idConveniado" type="int">
<column name="idConveniado" />
<generator class="assigned" />
</id>
<!-- foreign key -->
<many-to-one name="tbramo" class="pojos.Tbramo" fetch="select">
<column name="ramo" not-null="true" />
</many-to-one>
<property name="nome" type="string">
<column name="nome" length="100" />
</property>
<property name="dataConvenio" type="date">
<column name="dataConvenio" length="10" />
</property>
<property name="dataLimite" type="date">
<column name="dataLimite" length="10" />
</property>
<property name="endereco" type="string">
<column name="endereco" length="100" />
</property>
<property name="bairro" type="string">
<column name="bairro" length="100" />
</property>
<property name="cep" type="string">
<column name="cep" length="20" />
</property>
<property name="telefone" type="string">
<column name="telefone" length="20" />
</property>
<property name="cnpj" type="string">
<column name="cnpj" length="15" />
</property>
<property name="cidade" type="string">
<column name="cidade" length="100" />
</property>
<property name="status" type="java.lang.Integer">
<column name="status" />
</property>
<property name="email" type="string">
<column name="email" length="100" />
</property>
</class>
</hibernate-mapping>
Java Class for XML above:
public class Tbconveniado implements java.io.Serializable {
private int idConveniado;
private Tbramo tbramo;
private String nome;
private Date dataConvenio;
private Date dataLimite;
private String endereco;
private String bairro;
private String cep;
private String telefone;
private String cnpj;
private String cidade;
private Integer status;
private String email;
public Tbconveniado() {
}
public Tbconveniado(int idConveniado, Tbramo tbramo) {
this.idConveniado = idConveniado;
this.tbramo = tbramo;
}
public Tbconveniado(int idConveniado, Tbramo tbramo, String nome, Date dataConvenio, Date dataLimite, String endereco, String bairro, String cep, String telefone, String cnpj, String cidade, Integer status, String email) {
this.idConveniado = idConveniado;
this.tbramo = tbramo;
this.nome = nome;
this.dataConvenio = dataConvenio;
this.dataLimite = dataLimite;
this.endereco = endereco;
this.bairro = bairro;
this.cep = cep;
this.telefone = telefone;
this.cnpj = cnpj;
this.cidade = cidade;
this.status = status;
this.email = email;
}
public int getIdConveniado() {
return this.idConveniado;
}
public void setIdConveniado(int idConveniado) {
this.idConveniado = idConveniado;
}
public Tbramo getTbramo() {
return this.tbramo;
}
public void setTbramo(Tbramo tbramo) {
this.tbramo = tbramo;
}
public String getNome() {
return this.nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public Date getDataConvenio() {
return this.dataConvenio;
}
public void setDataConvenio(Date dataConvenio) {
this.dataConvenio = dataConvenio;
}
public Date getDataLimite() {
return this.dataLimite;
}
public void setDataLimite(Date dataLimite) {
this.dataLimite = dataLimite;
}
public String getEndereco() {
return this.endereco;
}
public void setEndereco(String endereco) {
this.endereco = endereco;
}
public String getBairro() {
return this.bairro;
}
public void setBairro(String bairro) {
this.bairro = bairro;
}
public String getCep() {
return this.cep;
}
public void setCep(String cep) {
this.cep = cep;
}
public String getTelefone() {
return this.telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public String getCnpj() {
return this.cnpj;
}
public void setCnpj(String cnpj) {
this.cnpj = cnpj;
}
public String getCidade() {
return this.cidade;
}
public void setCidade(String cidade) {
this.cidade = cidade;
}
public Integer getStatus() {
return this.status;
}
public void setStatus(Integer status) {
this.status = status;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
}
Note: Before anyone complain about this is a duplicate, make sure to go through the content without judging by title. Also make sure to read your reference question and the answer carefully to see whether it is duplicate. As of my experience now, the issue in this question can happen under different environments. For an example, the answer for someone using the below code in jsp will be different, for someone using Spring will be different and for someone whose DB is small and eager load is fine will be different. And no, my situation is not any of them.
I am writing a REST api using Hibernateand Jersey. Please have a look at the below code.
VerificationCodeJSONService.java - The JSON Service class
#Path("/verificaion_code")
public class VerificationCodeJSONService {
#GET
#Path("/getAllVerificationCodes")
#Produces(MediaType.APPLICATION_JSON)
public List<VerificaionCode> getAllVerificationCodes() {
VerificationCodeService verificationCodeService=new VerificationCodeService();
List<VerificaionCode> list = verificationCodeService.getAllVerificationCodes();
return list;
}
}
VerificationCodeService.java - The Service Layer
public class VerificationCodeService {
private static VerificationCodeDAOInterface verificationCodeDAOInterface;
public VerificationCodeService() {
verificationCodeDAOInterface = new VerificationCodeDAOImpl();
}
public List<VerificaionCode> getAllVerificationCodes() {
Session session = verificationCodeDAOInterface.openCurrentSession();
Transaction transaction = null;
List<VerificaionCode> verificaionCodes = new ArrayList<VerificaionCode>();
try {
transaction = verificationCodeDAOInterface.openTransaction(session);
verificaionCodes = verificationCodeDAOInterface.getAllVerificationCodes(session);
transaction.commit();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
session.close();
}
return verificaionCodes;
}
}
VerificationCodeDAOImpl.java - The database layer
public class VerificationCodeDAOImpl implements VerificationCodeDAOInterface{
private static final SessionFactoryBuilder sessionFactoryBuilder = SessionFactoryBuilder.getInstance();
#Override
public List<VerificaionCode> getAllVerificationCodes(Session session) {
List<VerificaionCode> verificaionCodes=(List<VerificaionCode>)session.createQuery("from VerificaionCode").list();
return verificaionCodes;
}
}
VerificationCode.java - The DAO layer
public class VerificaionCode implements java.io.Serializable {
private Integer idverificaionCode;
private Patient patient;
private String code;
private Date dateCreated;
private Date lastUpdated;
public VerificaionCode() {
}
public VerificaionCode(Patient patient, String code, Date lastUpdated) {
this.patient = patient;
this.code = code;
this.lastUpdated = lastUpdated;
}
public VerificaionCode(Patient patient, String code, Date dateCreated, Date lastUpdated) {
this.patient = patient;
this.code = code;
this.dateCreated = dateCreated;
this.lastUpdated = lastUpdated;
}
public Integer getIdverificaionCode() {
return this.idverificaionCode;
}
public void setIdverificaionCode(Integer idverificaionCode) {
this.idverificaionCode = idverificaionCode;
}
public Patient getPatient() {
return this.patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public String getCode() {
return this.code;
}
public void setCode(String code) {
this.code = code;
}
public Date getDateCreated() {
return this.dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public Date getLastUpdated() {
return this.lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
}
Patient.java - The DAO layer
public class Patient implements java.io.Serializable {
private Integer idpatient;
private DiabetesType diabetesType;
private Language language;
private String customId;
private String diabetesOther;
private String firstName;
private String lastName;
private String email;
private Date dob;
private String parentEmail;
private String gender;
private Date diagnosedDate;
private Double height;
private Double weight;
private String heightUnit;
private String weightUnit;
private String theme;
private String userName;
private String password;
private Date dateCreated;
private Date lastUpdated;
public Patient() {
}
public Patient(DiabetesType diabetesType, Language language, String customId, String firstName, String email, Date dob, String gender, String theme, String userName, String password, Date lastUpdated) {
this.diabetesType = diabetesType;
this.language = language;
this.customId = customId;
this.firstName = firstName;
this.email = email;
this.dob = dob;
this.gender = gender;
this.theme = theme;
this.userName = userName;
this.password = password;
this.lastUpdated = lastUpdated;
}
public Integer getIdpatient() {
return this.idpatient;
}
public void setIdpatient(Integer idpatient) {
this.idpatient = idpatient;
}
public DiabetesType getDiabetesType() {
return this.diabetesType;
}
public void setDiabetesType(DiabetesType diabetesType) {
this.diabetesType = diabetesType;
}
public Language getLanguage() {
return this.language;
}
public void setLanguage(Language language) {
this.language = language;
}
public String getCustomId() {
return this.customId;
}
public void setCustomId(String customId) {
this.customId = customId;
}
public String getDiabetesOther() {
return this.diabetesOther;
}
public void setDiabetesOther(String diabetesOther) {
this.diabetesOther = diabetesOther;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDob() {
return this.dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getParentEmail() {
return this.parentEmail;
}
public void setParentEmail(String parentEmail) {
this.parentEmail = parentEmail;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getDiagnosedDate() {
return this.diagnosedDate;
}
public void setDiagnosedDate(Date diagnosedDate) {
this.diagnosedDate = diagnosedDate;
}
public Double getHeight() {
return this.height;
}
public void setHeight(Double height) {
this.height = height;
}
public Double getWeight() {
return this.weight;
}
public void setWeight(Double weight) {
this.weight = weight;
}
public String getHeightUnit() {
return this.heightUnit;
}
public void setHeightUnit(String heightUnit) {
this.heightUnit = heightUnit;
}
public String getWeightUnit() {
return this.weightUnit;
}
public void setWeightUnit(String weightUnit) {
this.weightUnit = weightUnit;
}
public String getTheme() {
return this.theme;
}
public void setTheme(String theme) {
this.theme = theme;
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getDateCreated() {
return this.dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public Date getLastUpdated() {
return this.lastUpdated;
}
public void setLastUpdated(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
}
Below are my Hibernate mapping files for the above POJOs
VerificaionCode.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 23, 2016 3:21:00 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="beans.VerificaionCode" table="verificaion_code" catalog="myglukose" optimistic-lock="version">
<id name="idverificaionCode" type="java.lang.Integer">
<column name="idverificaion_code" />
<generator class="identity" />
</id>
<many-to-one name="patient" class="beans.Patient" fetch="select">
<column name="patient_idpatient" not-null="true" />
</many-to-one>
<property name="code" type="string">
<column name="code" length="45" not-null="true" />
</property>
<property name="dateCreated" type="timestamp">
<column name="date_created" length="19" />
</property>
<property name="lastUpdated" type="timestamp">
<column name="last_updated" length="19" not-null="true" />
</property>
</class>
</hibernate-mapping>
Patient.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 23, 2016 3:21:00 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="beans.Patient" table="patient" catalog="myglukose" optimistic-lock="version">
<id name="idpatient" type="java.lang.Integer">
<column name="idpatient" />
<generator class="identity" />
</id>
<many-to-one name="diabetesType" class="beans.DiabetesType" fetch="select">
<column name="diabetes_type_iddiabetes_type" not-null="true" />
</many-to-one>
<many-to-one name="language" class="beans.Language" fetch="select">
<column name="language_idlanguage" not-null="true" />
</many-to-one>
<property name="customId" type="string">
<column name="custom_id" length="45" not-null="true" />
</property>
<property name="diabetesOther" type="string">
<column name="diabetes_other" length="45" />
</property>
<property name="firstName" type="string">
<column name="first_name" length="100" not-null="true" />
</property>
<property name="lastName" type="string">
<column name="last_name" length="100" />
</property>
<property name="email" type="string">
<column name="email" length="45" not-null="true" />
</property>
<property name="dob" type="date">
<column name="dob" length="10" not-null="true" />
</property>
<property name="parentEmail" type="string">
<column name="parent_email" length="45" />
</property>
<property name="gender" type="string">
<column name="gender" length="45" not-null="true" />
</property>
<property name="diagnosedDate" type="date">
<column name="diagnosed_date" length="10" />
</property>
<property name="height" type="java.lang.Double">
<column name="height" precision="22" scale="0" />
</property>
<property name="weight" type="java.lang.Double">
<column name="weight" precision="22" scale="0" />
</property>
<property name="heightUnit" type="string">
<column name="height_unit" length="45" />
</property>
<property name="weightUnit" type="string">
<column name="weight_unit" length="45" />
</property>
<property name="theme" type="string">
<column name="theme" length="45" not-null="true" />
</property>
<property name="userName" type="string">
<column name="user_name" length="45" not-null="true" />
</property>
<property name="password" type="string">
<column name="password" length="45" not-null="true" />
</property>
<property name="dateCreated" type="timestamp">
<column name="date_created" length="19" />
</property>
<property name="lastUpdated" type="timestamp">
<column name="last_updated" length="19" not-null="true">
<comment>Stores the basic information of the patient</comment>
</column>
</property>
</class>
</hibernate-mapping>
However when I run this code via http://localhost:8080/example_rest/rest/verificaion_code/getAllVerificationCodes I am getting the below error.
could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->beans.VerificaionCode["patient"]->beans.Patient_$$_jvst40f_7["diabetesType"])
As you can see diabetesType is an Object (Foreign Key) in the patient's table and has nothing to do with VerificationCode. How can I fix this up?
Please note that this is a REST API. So I can't load these in a JSP like in a web app.
Update
As #Kayaman recommended, I made the updates by making null. Please check the below code. I noticed that verificaionCodes.get(i).getPatient().set...(null) makes the same error as above, so I tried below which started working fine.
VerificationCodeService.java
public List<VerificaionCode> getAllVerificationCodes() {
Session session = verificationCodeDAOInterface.openCurrentSession();
Transaction transaction = null;
List<VerificaionCode> verificaionCodes = new ArrayList<VerificaionCode>();
try {
transaction = verificationCodeDAOInterface.openTransaction(session);
verificaionCodes = verificationCodeDAOInterface.getAllVerificationCodes(session);
transaction.commit();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
session.close();
for(int i=0;i<verificaionCodes.size();i++)
{
Patient p = new Patient();
System.out.println(verificaionCodes.get(i).getPatient().getIdpatient());
Integer idpatient = verificaionCodes.get(i).getPatient().getIdpatient();
p.setIdpatient(idpatient);
verificaionCodes.get(i).setPatient(p);
}
}
return verificaionCodes;
}
I am writing REST services using Java RESTLET .
I have my User class here :
#Entity
#Table(name = "user")
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "idUser", nullable = false, unique = true, length = 255)
private Long idUser;
#Column(name = "name", nullable = true, length = 255)
private String name;
#Column(name = "username", nullable = false, length = 255)
private String username;
#Column(name = "password", nullable = false, length = 255)
private String password;
public Object setValue(Object input) {
Object fieldValue = ((input == null) ? JSONObject.NULL.toString()
: input);
return fieldValue;
}
public String getUserPassword() {
return password;
}
public void setUserPassword(String password) {
this.password = password;
}
public String getUserName() {
return username ;
}
public void setUserName(String userName) {
this.username = userName;
}
public Long getidUser() {
return idUser;
}
public void setIdUser(Long idUser) {
this.idUser = idUser;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getContactFirstName() {
return contactFirstName;
}
public void setContactFirstName(String contactFirstName) {
this.contactFirstName = contactFirstName;
}
public String getContactLastName() {
return contactLastName;
}
public void setContactLastName(String contactLastName) {
this.contactLastName = contactLastName;
}
public String getContactEmail() {
return contactEmail;
}
public void setContactEmail(String contactEmail) {
this.contactEmail = contactEmail;
}
public String getContactMobile() {
return contactMobile;
}
public void setContactMobile(String contactMobile) {
this.contactMobile = contactMobile;
}
public String getContactPhone() {
return contactPhone;
}
public void setContactPhone(String contactPhone) {
this.contactPhone = contactPhone;
}
public String getContactAddress() {
return contactAddress;
}
public void setContactAddress(String contactAddress) {
this.contactAddress = contactAddress;
}
public Integer getStatus() {
return status;
}
public void setStatus(Integer status) {
this.status = status;
}
public Integer getType() {
return type;
}
public void setType(Integer type) {
this.type = type;
}
public Timestamp getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Timestamp createdDate) {
this.createdDate = createdDate;
}
public Timestamp getUpdatedDate() {
return updatedDate;
}
public void setUpdatedDate(Timestamp updatedDate) {
this.updatedDate = updatedDate;
}
}
My User.hbm.xml files looks like .
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="persistence.entity.User" table="user">
<id name="idUser" type="long" unsaved-value="null">
<column name="idUser" not-null="true"/>
<generator class="identity"/>
</id>
<property name="userName">
<column name="username" not-null="true" />
</property>
<property name="password">
<column name="password" not-null="true" />
</property>
<property name="status">
<column name="status" not-null="true" />
</property>
<property name="type">
<column name="type" not-null="true" />
</property>
<property name="createdDate">
<column name="createdDT" not-null="true" />
</property>
<property name="updatedDate">
<column name="updatedDT" not-null="false" />
</property>
<property name="name">
<column name="name" length="255" not-null="false" />
</property>
<property name="contactFirstName">
<column name="contactFirstName" length="255" not-null="false" />
</property>
<property name="contactLastName">
<column name="contactLastName" length="255" not-null="false" />
</property>
<property name="contactEmail">
<column name="contactEmail" length="255" not-null="false" />
</property>
<property name="contactMobile">
<column name="contactMobile" length="32" not-null="false" />
</property>
<property name="contactPhone">
<column name="contactPhone" length="32" not-null="false" />
</property>
<property name="contactAddress">
<column name="contactAddress" not-null="false" />
</property>
</class>
</hibernate-mapping>
I have clerly defined the getter ans setter in my User.java file .
But when I am running this code I am getting the error
Could not find a getter for password in class tecd.persistenc.entity.User
I don't know what I am missing plz help me out
You have declared getter and setter for password like this:
public String getUserPassword() {
return password;
}
public void setUserPassword(String password) {
this.password = password;
}
I think it should be like this (no "User" in it):
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
Those are the standard "bean"-style names for a password field.
I'm developing an application using Hibernate, Spring and GWT in Java. I used reverse engineering under Hibernate (JBoss Developer Studio used) to obtain POJOs and configuration files from an existing MySQL database. It's very simple database with only two entities: Country and Citizen. They have OneToMany relationship between.
Here is the code:
app entry point:
...
Country country = new Country();
country.setName("NameOfCountry"+i);
country.setPopulation(10000);
Citizen ctz = new Citizen();
ctz.setName("John");
ctz.setSurname("Smith");
ctz.setCountry(country);
country.getCitizens().add(ctz);
service.saveCitizen(ctz, new AsyncCallback<Boolean>(){
#Override
public void onFailure(Throwable caught) {
System.out.println("Problem saving citizen");
}
#Override
public void onSuccess(Boolean result) {
System.out.println("Citizen successfully saved");
}
});
service.saveCountry(country, new AsyncCallback<Boolean>(){
#Override
public void onFailure(Throwable caught) {
System.out.println("Problem saving country");
}
#Override
public void onSuccess(Boolean result) {
System.out.println("Country successfully saved");
}
});
...
-- service provides simple GWT-RPC call to server
Service on server:
#Service("componentService")
public class ComponentServiceImpl implements ComponentService{
#Autowired
private CountryDAO daoCnt;
#Autowired
private CitizenDAO daoCtz;
#Transactional(readOnly=false)
#Override
public boolean saveCitizen(Citizen citizen) {
daoCtz.saveOrUpdate(citizen);
return true;
}
#Transactional(readOnly=false)
#Override
public boolean saveCountry(Country country) {
daoCnt.saveOrUpdate(country);
return true;
}
}
Now SpringDAOs:
CitizenDAO:
#Repository
public class CitizenDAO {
...
public void saveOrUpdate(Citizen citizen){
sessionFactory.getCurrentSession().saveOrUpdate(citizen);
}
...
CountryDAO:
#Repository
public class CountryDAO {
...
public void saveOrUpdate(Country country){
sessionFactory.getCurrentSession().saveOrUpdate(country);
}
...
Finally
Citizen.hbm.xml:
<hibernate-mapping>
<class name="sk.jakub.mod.shared.model.Citizen" table="citizen" catalog="modeldb">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<many-to-one name="country" class="sk.jakub.mod.shared.model.Country" fetch="select">
<column name="Country_id" not-null="true" />
</many-to-one>
<property name="name" type="string">
<column name="name" length="45" not-null="true" />
</property>
<property name="surname" type="string">
<column name="surname" length="45" not-null="true" />
</property>
</class>
</hibernate-mapping>
Country.hbm.xml:
<hibernate-mapping>
<class name="sk.jakub.mod.shared.model.Country" table="country" catalog="modeldb">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="name" type="string">
<column name="name" length="45" not-null="true" />
</property>
<property name="population" type="int">
<column name="population" not-null="true" />
</property>
<set name="citizens" table="citizen" inverse="true" lazy="true" fetch="select">
<key>
<column name="Country_id" not-null="true" />
</key>
<one-to-many class="sk.jakub.mod.shared.model.Citizen" />
</set>
</class>
</hibernate-mapping>
I havent listed Citizen.java and Country.java because they are only basic POJOs (if necessary I'll provide them).
When I launch my app and I want to save my data into database I obtain following error:
org.hibernate.PropertyValueException: not-null property references a null or transient value: sk.jakub.mod.shared.model.Citizen.country
I can't figure out where is the problem. I was trying also instead of saveOrUpdate method, persist method. Or also to change the order of saving into database. Nothing seemed to work.
Thank you very much for help :) If needed, I can post more code from my application.
EDIT:
code for Citizen.java:
public class Citizen implements java.io.Serializable {
private static final long serialVersionUID = -3102863479088406293L;
private Integer id;
private Country country;
private String name;
private String surname;
public Citizen() {
}
public Citizen(Country country, String name, String surname) {
this.country = country;
this.name = name;
this.surname = surname;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public Stat getCountry() {
return this.country;
}
public void setCountry(Country country) {
this.country = country;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return this.surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
}
Country.java:
public class Country implements java.io.Serializable {
private static final long serialVersionUID = -4085805854508658303L;
private Integer id;
private String name;
private int population;
private Set<Citizen> citizens = new HashSet<Citizen>();
public Country() {
}
public Country(String name, int population) {
this.name = name;
this.population = population;
}
public Country(String name, int population, Set<Citizen> citizens) {
this.name = name;
this.population = population;
this.citizens = citizens;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public int getPopulation() {
return this.population;
}
public void setPopulation(int population) {
this.population = population;
}
public Set<Citizen> getCitizens() {
return this.citizens;
}
public void setCitizens(Set<Citizen> citizens) {
this.citizens = citizens;
}
}
Furthermore, I've checked the database manually and Country is saved but citizen is not.
I am seeing that you are creating a Citizen before you create a country. Also both the service calls should be in same transaction for the whole operation to be atomic. The COUNTRY_ID seems to be a self generated id i believe. So once you create the country you can attach that to a citizen but you call stack shows you are creating a citizen which has a Country object which doesnt have an id. This is just my guess. You can try putting both the calls under same transaction and also try creating a Country and attach that country instance to the Citizen.
Please check if you have implemented the equals, hashcode and compareTo (if applicable) methods properly. I have recently faced this problem and resolved it by proper implemetation of these.