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
Please What did i wrong, and what should i do?
I have an org.hibernate.TransientPropertyValueException exeption during the compilation when i try to insert objects into my database:
Main class
public class Main {
public static void main(String[] args) {
SessionFactory sessionFactory = new HibernateUtil().getSessionFactory();
Session session = sessionFactory.openSession();
session.beginTransaction();
Role role = new Role();
role.setTitle("ex-president");
User user1 = new User(100,"Barack","Obama");
User user2 = new User(100,"Ronald","Reagan");
user1.setRole(role);
user2.setRole(role);
session.save(user1);
session.save(user2);
role.getUsers().add(user1);
role.getUsers().add(user2);
session.save(role);
session.getTransaction().commit();
session.close();
}}
HibernateUtil class
public class HibernateUtil {
private static SessionFactory sessionFactory;
static {
Configuration configuration = new Configuration();
configuration.configure("hibernate.cfg.xml");
StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(configuration.getProperties());
sessionFactory = configuration.buildSessionFactory(ssrb.build());
}
public SessionFactory getSessionFactory(){
return sessionFactory;
}}
Role class
#Entity
public class Role {
private Long role_id;
private String title;
private Set<User> users = new HashSet<User>();
public Role(){}
public Set<User> getUsers() {
return users;
}
public void addUser(User user){
users.add(user);
}
public void setUsers(Set<User> users) {
this.users = users;
}
public Long getRole_id() {
return role_id;
}
public void setRole_id(Long id) {
this.role_id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}}
User class
#Entity
public class User {
private long user_id;
private int age;
private String firstname;
private String lastname;
private Role role;
public User(){
}
public Role getRole() {
return role;
}
public void setRole(Role role) {
this.role = role;
}
public User(int age, String firstname, String lastname) {
this.age = age;
this.firstname = firstname;
this.lastname = lastname;
}
public long getUser_id() {
return user_id;
}
public void setUser_id(long id) {
this.user_id = id;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
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;
}}
hibernate.cfg.xml
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="connection.url">jdbc:mysql://localhost:3306/hibernate</property>
<property name="connection.username">root</property>
<property name="connection.password">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hbm2ddl.auto">create</property>
<property name="show_sql">true</property>
<property name="format_sql">true</property>
<mapping resource="user.cfg.xml"/>
<mapping resource="role.cfg.xml"/>
</session-factory>
</hibernate-configuration>
role.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Role" table="role">
<id name="role_id" column="id">
<generator class="native"/>
</id>
<property name="title" column="TITLE"/>
<set name="users" cascade="all"
inverse="true" lazy="true" fetch="select">
<key column="id" not-null="true"/>
<one-to-many class="User"/>
</set>
</class>
</hibernate-mapping>
user.cfg.xml
<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="User" table="user">
<id name="user_id" column="user_id">
<generator class="native"/>
</id>
<property name="firstname" column="firstname"/>
<property name="lastname" column="lastname"/>
<property name="age" column="age"/>
<many-to-one name="role" class="Role" fetch="select">
<column name="id" not-null="true"/>
</many-to-one>
</class>
</hibernate-mapping>
Error information in log:
Your program maybe has many mistakes. At least these mistakes what I can point out:
Role role = new Role();
role.setTitle("ex-president");
User user1 = new User(100, "Barack", "Obama");
User user2 = new User(100, "Ronald", "Reagan");
user1.setRole(role);
user2.setRole(role);
session.save(user1);
session.save(user2);
role.getUsers().add(user1);
role.getUsers().add(user2);
session.save(role);
(1) Object role (an instance of class Role) hasn't role_id.
(2) Object user1, user2 hasn't role_id
(3) Must have few record of Role before save user1, user2, because these objects need foreign key (role_id).
I use hibernate to create a rest api. I create a method to get all items in a table.
public List<Language> getAllLanguages(Session session) {
List<Language> languages=(List<Language>)session.createQuery("from Language").list();
return languages;
}
This is my Language.java
public class Language implements java.io.Serializable {
private Integer idlanguage;
private String language;
private Set<Patient> patients = new HashSet<Patient>(0);
public Language() {
}
public Language(String language) {
this.language = language;
}
public Language(String language, Set<Patient> patients) {
this.language = language;
this.patients = patients;
}
public Integer getIdlanguage() {
return this.idlanguage;
}
public void setIdlanguage(Integer idlanguage) {
this.idlanguage = idlanguage;
}
public String getLanguage() {
return this.language;
}
public void setLanguage(String language) {
this.language = language;
}
public Set<Patient> getPatients() {
return this.patients;
}
public void setPatients(Set<Patient> patients) {
this.patients = patients;
}
}
And this is my Patient.java
// Generated Sep 14, 2016 4:33:23 PM by Hibernate Tools 4.3.1
import beans.DiabetesType;
import beans.Illness;
import beans.Language;
import beans.Reminder;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* Patient generated by hbm2java
*/
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 userName;
private String password;
private Date dateCreated;
private Date lastUpdated;
private Set<Illness> illnesses = new HashSet<Illness>(0);
private Set<Reminder> reminders = new HashSet<Reminder>(0);
public Patient() {
}
public Patient(Integer idpatient, String password) {
this.idpatient = idpatient;
this.password = password;
}
public Patient(DiabetesType diabetesType, Language language, String customId, String firstName, String userName, String password, Date lastUpdated) {
this.diabetesType = diabetesType;
this.language = language;
this.customId = customId;
this.firstName = firstName;
this.userName = userName;
this.password = password;
this.lastUpdated = lastUpdated;
}
public Patient(DiabetesType diabetesType, Language language, String customId, String diabetesOther, String firstName, String lastName, String userName, String password, Date dateCreated, Date lastUpdated, Set<Illness> illnesses, Set<Reminder> reminders) {
this.diabetesType = diabetesType;
this.language = language;
this.customId = customId;
this.diabetesOther = diabetesOther;
this.firstName = firstName;
this.lastName = lastName;
this.userName = userName;
this.password = password;
this.dateCreated = dateCreated;
this.lastUpdated = lastUpdated;
this.illnesses = illnesses;
this.reminders = reminders;
}
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 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;
}
public Set<Illness> getIllnesses() {
return this.illnesses;
}
public void setIllnesses(Set<Illness> illnesses) {
this.illnesses = illnesses;
}
public Set<Reminder> getReminders() {
return this.reminders;
}
public void setReminders(Set<Reminder> reminders) {
this.reminders = reminders;
}
}
Important: The beans and mappings are reverse engineered from MySQL database, via NetBeans. I do not need to get any data related to patient when calling getAllLangauges. My language table has only 2 columns, idlanguage and language. Patient table has a foriegn key of language table
Before using this method in rest api , it worked perfectly without any exception. But when I used this in rest api, it created a complexity in there.
I am not using annotations in here. I used hibernate reverse engineering wizard to map above entities . This is my rest api method.
#Path("/language")
public class LanguageJSONService {
#GET
#Path("/getAllLanguages")
#Produces(MediaType.APPLICATION_JSON)
public List<Language> getAllLanguages(){
LanguageService languageService=new LanguageService();
List<Language> list = languageService.getAllLanguages();
return list;
}
}
This is the way how I call the method,
Client client = ClientBuilder.newClient();
List<Language> list = client.target("http://localhost:8080/simple_rest/rest")
.path("/language/getAllLanguages")
.request(MediaType.APPLICATION_JSON)
.get(new GenericType<List<Language>>() {
});
for (int i = 0; i < list.size(); i++) {
System.out.println("Id - " + list.get(i).getIdlanguage() + " Language - " + list.get(i).getLanguage());
}
When I call the method ,
failed to lazily initialize a collection of role: beans.Language.patients, could not initialize proxy - no Session (through reference chain: java.util.ArrayList[0]->beans.Language["patients"])
is occurred.
Interestingly, if I did not close the session, then I get an output like below which is totally something else, seems like it is trying to display its foreign key tables and their foreign key tables and so on...
[{"idlanguage":1,"language":"English","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":{"iddiabetesType":1,"type":"Sever","patients":
[{"idpatient":1,"diabetesType":
Have any ideas about this problem ?
Update
my configuration file
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="show_sql">true</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost:3306/*****</property>
<property name="hibernate.connection.username">*****</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.timeout">3000</property>
<property name="hibernate.c3p0.max_statements">50</property>
<property name="hibernate.c3p0.idle_test_period">300</property>
<property name="hibernate.c3p0.testConnectionOnCheckout">true</property>
<property name="hibernate.c3p0.preferredTestQuery">SELECT 1</property>
<property name="hibernate.connection.password">************</property>
<mapping resource="beans/Reminder.hbm.xml"/>
<mapping resource="beans/Food.hbm.xml"/>
<mapping resource="beans/Patient.hbm.xml"/>
<mapping resource="beans/Illness.hbm.xml"/>
<mapping resource="beans/Language.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Language.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 14, 2016 4:33:23 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="beans.Language" table="language" catalog="myglukose" optimistic-lock="version">
<id name="idlanguage" type="java.lang.Integer">
<column name="idlanguage" />
<generator class="identity" />
</id>
<property name="language" type="string">
<column name="language" length="45" not-null="true" />
</property>
<set name="patients" table="patient" inverse="true" lazy="true" fetch="select">
<key>
<column name="language_idlanguage" not-null="true" />
</key>
<one-to-many class="beans.Patient" />
</set>
</class>
</hibernate-mapping>
This is my patient mapping file,
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 14, 2016 4:33:23 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="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>
<set name="illnesses" table="illness" inverse="true" lazy="true" fetch="select">
<key>
<column name="patient_idpatient" not-null="true" />
</key>
<one-to-many class="beans.Illness" />
</set>
<set name="reminders" table="reminder" inverse="true" lazy="true" fetch="select">
<key>
<column name="patient_idpatient" not-null="true" />
</key>
<one-to-many class="beans.Reminder" />
</set>
</class>
</hibernate-mapping>
Your json converter tries to serialize the whole entity, which contains the list of all patients speaking each language. From what i understood, the list of patient in the json is not expected. So you have three options (ordered in which i would consider them) :
Remove the mapping to patients in Language entity. Do you need to get acces
s to patients from the language entity ? If not remove this mapping.
Create a Language DTO where you transfer your data before exiting the tx layer. This way whoever calls the service will never get a LazyInitException. No surprise : DTO fields are always set eagerly.
Configure your json converter to not serialize the patient fields. You've not said which json lib you're using. Some of them give you an annotation to ignore some fields (#JsonIgnore for Jackson for example), other requires java configuration.
To apply the first solution, update those files this way :
Language.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 14, 2016 4:33:23 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="beans.Language" table="language" catalog="myglukose" optimistic-lock="version">
<id name="idlanguage" type="java.lang.Integer">
<column name="idlanguage" />
<generator class="identity" />
</id>
<property name="language" type="string">
<column name="language" length="45" not-null="true" />
</property>
</class>
</hibernate-mapping>
Language.java
public class Language implements java.io.Serializable {
private Integer idlanguage;
private String language;
protected Language() {
}
public Language(String language) {
this.language = language;
}
public Integer getIdlanguage() {
return this.idlanguage;
}
protected void setIdlanguage(Integer idlanguage) {
this.idlanguage = idlanguage;
}
public String getLanguage() {
return this.language;
}
public void setLanguage(String language) {
this.language = language;
}
}
I've updated the no-arg constructor and setId method to protected. You can even update them to private : only hibernate should ever use them (and it can use private fields / methods).
When you try to access a lazy field you need to do that before the session of hibernate is closed.
When you exit from the context of the session is not possible for hibernate to access the database if needed, so a LazyInitializationException is thrown.
From javadoc:
Indicates access to unfetched data outside of a session context. For example, when an uninitialized proxy or collection is accessed after the session was closed.
From current explanation I am not able to see you are doing like : language.getPatients();
But if you are writing HQL query to access all patients form Language Entity then I think you should use join . As i can see the exception if related to LazyInitializationException in beans.Language.patients.
so i will suggest below code ...Check if it usefull to you or not..
public List<Language> getAllLanguages(Session session) {
List<Language> languages=(List<Language>)session.createQuery("from Language as l JOIN l.patients").list();
return languages;
}
I am trying to learn Hibernate and I am following this tutorial: http://www.visualcplusdotnet.com/javaopensource/javahibernateswingdesktopapp5.html except I am using my own sample database. I have reverse engineered the POJOs for my contact table which looks like this:
and Netbeans auto-generated a .java file that looked like this (Contact.java):
package model;
// Generated Mar 6, 2015 12:04:10 AM by Hibernate Tools 4.3.1
/**
* Contact generated by hbm2java
*/
public class Contact implements java.io.Serializable {
private Integer id;
private String firstname;
private String lastname;
private String email;
private String phone;
private boolean active;
public Contact() {
}
public Contact(String firstname, String lastname, boolean active) {
this.firstname = firstname;
this.lastname = lastname;
this.active = active;
}
public Contact(String firstname, String lastname, String email, String phone, boolean active) {
this.firstname = firstname;
this.lastname = lastname;
this.email = email;
this.phone = phone;
this.active = active;
}
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
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 String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public boolean isActive() {
return this.active;
}
public void setActive(boolean active) {
this.active = active;
}
}
and a .xml file that looks like this (Contact.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 Mar 6, 2015 12:04:12 AM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="model.Contact" table="contact" catalog="crmtool" optimistic-lock="version">
<id name="id" type="java.lang.Integer">
<column name="id" />
<generator class="identity" />
</id>
<property name="firstname" type="string">
<column name="firstname" length="100" not-null="true" />
</property>
<property name="lastname" type="string">
<column name="lastname" length="100" not-null="true" />
</property>
<property name="email" type="string">
<column name="email" length="100" />
</property>
<property name="phone" type="string">
<column name="phone" length="10" />
</property>
<property name="active" type="boolean">
<column name="active" not-null="true" />
</property>
</class>
</hibernate-mapping>
After a clean and build, when I run this HQL Query:
from Contact
I get this error:
org.hibernate.PropertyNotFoundException: Could not find a getter for id in class model.Contact
at org.hibernate.property.BasicPropertyAccessor.createGetter(BasicPropertyAccessor.java:310)
at org.hibernate.property.BasicPropertyAccessor.getGetter(BasicPropertyAccessor.java:304)
at org.hibernate.tuple.PropertyFactory.getGetter(PropertyFactory.java:497)
at org.hibernate.tuple.PropertyFactory.buildIdentifierAttribute(PropertyFactory.java:87)
at org.hibernate.tuple.entity.EntityMetamodel.<init>(EntityMetamodel.java:163)
at org.hibernate.persister.entity.AbstractEntityPersister.<init>(AbstractEntityPersister.java:520)
at org.hibernate.persister.entity.SingleTableEntityPersister.<init>(SingleTableEntityPersister.java:148)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:408)
at org.hibernate.persister.internal.PersisterFactoryImpl.create(PersisterFactoryImpl.java:163)
at org.hibernate.persister.internal.PersisterFactoryImpl.createEntityPersister(PersisterFactoryImpl.java:135)
at org.hibernate.internal.SessionFactoryImpl.<init>(SessionFactoryImpl.java:400)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1857)
at org.hibernate.cfg.Configuration.buildSessionFactory(Configuration.java:1928)
after reading the answers to these questions:
Hibernate - PropertyNotFoundException: Could not find a getter for
PropertyNotFoundException: Could not find a getter for lastMoveDate in class com.hib.objects.GameBoard
org.hibernate.PropertyNotFoundException: could not find getter for customerId in class Address
I figured the answer must be something wrong with the way id is being capitalized by the getter, so I tried:
public Integer getid() {
return this.id;
}
public int getId() {
return this.id;
}
public int getid() {
return this.id;
}
All kinds of things, but still nothing works.
Does anyone know why I'm receiving this error?
Here it is :
Your configuration looks correct. Can do a simple test just rename your id attribute to say contactId and create getters and setters,modify Contact.hbm.xml accordingly and see if hibernate complains of not being able to getter method for the new attribute. Getting this feeling there is some project cleaning up issue
Regards,
Don't try to solve. Change the name of id column to "cid" or "contact_id" or whatever you want.
i have a hibernate error wich sais :
15:32:48,554 DEBUG SQL:111 - insert into apurement.user (groupe_id, username, password, email) values (?, ?, ?, ?)
15:32:48,664 WARN JDBCExceptionReporter:100 - SQL Error: 1452, SQLState: 23000
15:32:48,664 ERROR JDBCExceptionReporter:101 -
Cannot add or update a child row: a foreign key constraint fails (apurement.user,
CONSTRAINT groupe_id FOREIGN KEY (groupe_id) REFERENCES groupe (groupe_id)
ON DELETE NO ACTION ON UPDATE NO ACTION)
the code is Logic.java for the session management:
package com.beans;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.*;
public class Logic {
protected Configuration cfg;
protected SessionFactory sfg;
protected Session s;
protected Transaction tx;
public Logic() {
this.init();
}
public void init() {
this.setCfg(new Configuration().configure());
this.setSfg(this.getCfg().buildSessionFactory());
this.setS(this.getSfg().openSession());
this.setTx(this.getS().beginTransaction());
}
public Configuration getCfg() {
return cfg;
}
public void setCfg(Configuration cfg) {
this.cfg = cfg;
}
public SessionFactory getSfg() {
return sfg;
}
public void setSfg(SessionFactory sfg) {
this.sfg = sfg;
}
public Session getS() {
return s;
}
public void setS(Session s) {
this.s = s;
}
public Transaction getTx() {
return tx;
}
public void setTx(Transaction tx) {
this.tx = tx;
}
}
the User class :
package com.beans;
// Generated 3 janv. 2013 12:07:19 by Hibernate Tools 3.4.0.CR1
/**
* User generated by hbm2java
*/
public class User implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer userId;
private Groupe groupe;
private String username;
private String password;
private String email;
public User() {
}
public User(Groupe groupe, String username, String password, String email) {
this.groupe = groupe;
this.username = username;
this.password = password;
this.email = email;
}
public Integer getUserId() {
return this.userId;
}
public void setUserId(Integer userId) {
this.userId = userId;
}
public Groupe getGroupe() {
return this.groupe;
}
public void setGroupe(Groupe groupe) {
this.groupe = groupe;
}
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 String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
}
the user.hbm :
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 3 janv. 2013 12:07:19 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="User" table="user" catalog="apurement">
<id name="userId" type="java.lang.Integer">
<column name="user_id" />
<generator class="identity" />
</id>
<many-to-one name="groupe" class="com.beans.Groupe" fetch="select">
<column name="groupe_id" not-null="true" />
</many-to-one>
<property name="username" type="string">
<column name="username" length="45" not-null="true" />
</property>
<property name="password" type="string">
<column name="password" length="45" not-null="true" />
</property>
<property name="email" type="string">
<column name="email" length="45" not-null="true" />
</property>
</class>
</hibernate-mapping>
groupe.java :
package com.beans;
// default package
// Generated 3 janv. 2013 12:07:19 by Hibernate Tools 3.4.0.CR1
import java.util.HashSet;
import java.util.Set;
/**
* Groupe generated by hbm2java
*/
public class Groupe implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Integer groupeId;
private String groupeName;
private String groupeRole;
private Set users = new HashSet(0);
public Groupe() {
}
public Groupe(String groupeName, String groupeRole) {
this.groupeName = groupeName;
this.groupeRole = groupeRole;
}
public Groupe(String groupeName, String groupeRole, Set users) {
this.groupeName = groupeName;
this.groupeRole = groupeRole;
this.users = users;
}
public Integer getGroupeId() {
return this.groupeId;
}
public void setGroupeId(Integer groupeId) {
this.groupeId = groupeId;
}
public String getGroupeName() {
return this.groupeName;
}
public void setGroupeName(String groupeName) {
this.groupeName = groupeName;
}
public String getGroupeRole() {
return this.groupeRole;
}
public void setGroupeRole(String groupeRole) {
this.groupeRole = groupeRole;
}
public Set getUsers() {
return this.users;
}
public void setUsers(Set users) {
this.users = users;
}
}
Groupe.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 3 janv. 2013 12:07:19 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="Groupe" table="groupe" catalog="apurement">
<id name="groupeId" type="java.lang.Integer">
<column name="groupe_id" />
<generator class="identity" />
</id>
<property name="groupeName" type="string">
<column name="groupe_name" length="100" not-null="true" />
</property>
<property name="groupeRole" type="string">
<column name="groupe_role" length="45" not-null="true" />
</property>
<set name="users" table="user" inverse="true" lazy="true" fetch="select">
<key>
<column name="groupe_id" not-null="true" />
</key>
<one-to-many class="com.beans.User" />
</set>
</class>
</hibernate-mapping>
hibernate.cfg:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC "-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate- configuration-3.0.dtd">
<hibernate-configuration>
<session-factory name="sf">
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">root</property>
<property name="hibernate.connection.url">jdbc:mysql://localhost/apurement</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<mapping class="com.beans.User" resource="com/beans/User.hbm.xml"/>
<mapping class="com.beans.Groupe" resource="com/beans/Groupe.hbm.xml"/>
</session-factory>
</hibernate-configuration>
i don't know what is going on.
You have a User that has a many-to-one mapping to a Groupe with not-null specified as true. You are trying to persist (insert) a User that does not have a Groupe.