Error executing DDL via JDBC Statement - java

I really need some help in hibernate, and i search all questions,but it didn't work.
My question is strange,at least I think so. In my project, i want to use entity class, hibernate xml mapping file(*.hbm.xml) and hibernate configuration file(hibernate.cfg.xml) to create table in mysql database. Strange that I have only one table can not be created, and other tables can be created successfully.
OK,These are my project code, i think these information might be used.
cart.java
import java.io.Serializable;
import java.util.HashMap;
import java.util.Map;
/**
* #author Ning
*
*/
public class Cart implements Serializable{
private Integer id;
private User user;
private Map<Integer, Integer> shopItems = new HashMap<>();
public Cart() {}
public Cart(User user, Map<Integer, Integer> shopItems) {
super();
this.user = user;
this.shopItems = shopItems;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Map<Integer, Integer> getShopItems() {
return shopItems;
}
public void setShopItems(Map<Integer, Integer> shopItems) {
this.shopItems = shopItems;
}
#Override
public String toString() {
return "Cart [id=" + id + ", user=" + user + ", shopItems=" + shopItems + "]";
}
}
<!------cart.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 2017-4-30 9:23:54 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.eshop.design.model.Cart" table="CART">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="native" />
</id>
<many-to-one name="user" class="com.eshop.design.model.User" fetch="join">
<column name="USER" />
</many-to-one>
<map name="shopItems">
<key column="CART_ID"></key>
<index column="PRODUCT_ID" type="java.lang.Integer"></index>
<element column="NUMBER" type="java.lang.Integer"></element>
</map>
</class>
</hibernate-mapping>
Order.java
import java.io.Serializable;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class Order implements Serializable{
private Integer id;
private User user;
private Map<Integer, Integer> shopItems = new HashMap<>();
private Date date;
private Status status;
private String remark;
public Order() {}
public Order(User user, Map<Integer, Integer> shopItems, Date date, Status status, String remark) {
super();
this.user = user;
this.shopItems = shopItems;
this.date = date;
this.status = status;
this.remark = remark;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Map<Integer, Integer> getShopItems() {
return shopItems;
}
public void setShopItems(Map<Integer, Integer> shopItems) {
this.shopItems = shopItems;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public Status getStatus() {
return status;
}
public void setStatus(Status status) {
this.status = status;
}
public String getRemark() {
return remark;
}
public void setRemark(String remark) {
this.remark = remark;
}
#Override
public String toString() {
return "Order [id=" + id + ", user=" + user + ", shopItems=" + shopItems + ", date=" + date + ", status="
+ status + ", remark=" + remark + "]";
}
}
<!-------order.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 2017-4-30 9:23:54 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.eshop.design.model.Order" table="ORDER">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="native" />
</id>
<many-to-one name="user" class="com.eshop.design.model.User" fetch="join">
<column name="USER" />
</many-to-one>
<map name="shopItems">
<key column="ORDER_ID"></key>
<index column="PRODUCT_ID" type="java.lang.Integer"></index>
<element column="NUMBER" type="java.lang.Integer"></element>
</map>
<property name="date" type="java.util.Date">
<column name="DATE" />
</property>
<many-to-one name="status" class="com.eshop.design.model.Status" fetch="join">
<column name="STATUS" />
</many-to-one>
<property name="remark" type="java.lang.String">
<column name="REMARK" />
</property>
</class>
</hibernate-mapping>
<!-----user.java------>
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
public class User implements Serializable{
private Integer id;
private String login;
private String pass;
private String name;
private String phone;
private String address;
private Double assets;
// Constructors
/** default constructor */
public User() {}
/** full constructor */
public User( String login, String pass, String name, String phone, String address, Double assets) {
super();
this.login = login;
this.pass = pass;
this.name = name;
this.phone = phone;
this.address = address;
this.assets = assets;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public String getPass() {
return pass;
}
public void setPass(String pass) {
this.pass = pass;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Double getAssets() {
return assets;
}
public void setAssets(Double assets) {
this.assets = assets;
}
#Override
public String toString() {
return "User [id=" + id + ", login=" + login + ", pass=" + pass + ", name=" + name + ", phone=" + phone
+ ", address=" + address + ", assets=" + assets + "]";
}
}
<!-----user.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 2017-4-30 9:23:54 by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping>
<class name="com.eshop.design.model.User" table="USER">
<id name="id" type="java.lang.Integer">
<column name="ID" />
<generator class="native" />
</id>
<property name="login" type="java.lang.String">
<column name="LOGIN" />
</property>
<property name="pass" type="java.lang.String">
<column name="PASS" />
</property>
<property name="name" type="java.lang.String">
<column name="NAME" />
</property>
<property name="phone" type="java.lang.String">
<column name="PHONE" />
</property>
<property name="address" type="java.lang.String">
<column name="ADDRESS" />
</property>
<property name="assets" type="java.lang.Double">
<column name="ASSETS" />
</property>
</class>
</hibernate-mapping>
<!-- I config the data source and session factory in the spring's configuration file applicationContext.xml-->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="user" value="${user}"></property>
<property name="password" value="${password}"></property>
<property name="driverClass" value="${driverClass}"></property>
<property name="jdbcUrl" value="${jdbcUrl}"></property>
<property name="minPoolSize" value="${minPoolSize}" />
<property name="maxPoolSize" value="${maxPoolSize}" />
<property name="initialPoolSize" value="${initialPoolSize}" />
</bean>
<!-- SessionFactory config -->
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<property name="configLocation" value="classpath:hibernate.cfg.xml"></property>
<property name="mappingLocations" value="classpath:com/eshop/design/model/*.hbm.xml"></property>
</bean>
<!----hibernate.cfg.xml--->
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</property>
<property name="hibernate.show_sql">true</property>
<property name="hibernate.format_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
</session-factory>
</hibernate-configuration>
This is the first time I have asked questions here, some formats may be unsatisfactory.
Thanks in advance and forget my poor English.

Related

Hibernate: could not initialize proxy - no Session (through reference chain....)

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;
}

Hibernate- failed to lazily initialize a collection of role: beans.Language.patients, could not initialize proxy - no Session

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;
}

How to insert data to multiple table at once in hibernate using java

Hi I am using hibernate to save data into two tables on a database .Also, I am using mysql .
These are my POJO classes,
Patient.java
public class Patient implements java.io.Serializable {
private Integer idPatient;
private String title;
private String firstName;
private String lastName;
private String middleName;
private Date dob;
private Boolean martitalStatus;
private String gender;
private String nic;
private Date dateCreated;
private Date lastUpdated;
private Set<Contact> contacts = new HashSet<Contact>(0);
public Patient() {
}
public Patient(Date lastUpdated) {
this.lastUpdated = lastUpdated;
}
public Patient(String title, String firstName, String lastName, String middleName, Date dob, Boolean martitalStatus, String gender, String nic, Date dateCreated, Date lastUpdated, Set<Contact> contacts) {
this.title = title;
this.firstName = firstName;
this.lastName = lastName;
this.middleName = middleName;
this.dob = dob;
this.martitalStatus = martitalStatus;
this.gender = gender;
this.nic = nic;
this.dateCreated = dateCreated;
this.lastUpdated = lastUpdated;
this.contacts = contacts;
}
public Integer getIdPatient() {
return this.idPatient;
}
public void setIdPatient(Integer idPatient) {
this.idPatient = idPatient;
}
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
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 getMiddleName() {
return this.middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public Date getDob() {
return this.dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public Boolean getMartitalStatus() {
return this.martitalStatus;
}
public void setMartitalStatus(Boolean martitalStatus) {
this.martitalStatus = martitalStatus;
}
public String getGender() {
return this.gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getNic() {
return this.nic;
}
public void setNic(String nic) {
this.nic = nic;
}
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<Contact> getContacts() {
return this.contacts;
}
public void setContacts(Set<Contact> contacts) {
this.contacts = contacts;
}
}
Contact.java
public class Contact implements java.io.Serializable {
private Integer idContact;
private Patient patient;
private String telephone;
private String address;
public Contact() {
}
public Contact(Patient patient) {
this.patient = patient;
}
public Contact(Patient patient, String telephone, String address) {
this.patient = patient;
this.telephone = telephone;
this.address = address;
}
public Integer getIdContact() {
return this.idContact;
}
public void setIdContact(Integer idContact) {
this.idContact = idContact;
}
public Patient getPatient() {
return this.patient;
}
public void setPatient(Patient patient) {
this.patient = patient;
}
public String getTelephone() {
return this.telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
}
Also I am not using annotations in here.
Patient patient=new Patient();
Contact contact=new Contact();
Set<Contact> contacts=new HashSet<Contact>();
contact.setTelephone("0358965458");
contact.setAddress("Horana");
contacts.add(contact);
patient.setFirstName("Wajira");
patient.setLastName("Dahanushka");
patient.setDateCreated(Common.getSQLCurrentTimeStamp());
patient.setLastUpdated(Common.getSQLCurrentTimeStamp());
patient.setGender("Male");
patient.setTitle("Mr");
patient.setNic("9115580466v");
patient.setContacts(contacts);
SessionFactory sessionFactory=new HibernateUtil().getSessionFactory();
Session session=sessionFactory.openSession();
session.beginTransaction();
session.persist(patient);
session.getTransaction().commit();
HibernateUtil.shutdown();
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 8, 2016 9:56:01 AM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="db.Patient" table="patient" catalog="example_hibernate" optimistic-lock="version">
<id name="idPatient" type="java.lang.Integer">
<column name="idPatient" />
<generator class="identity" />
</id>
<property name="title" type="string">
<column name="title" length="45" />
</property>
<property name="firstName" type="string">
<column name="firstName" length="45" />
</property>
<property name="lastName" type="string">
<column name="lastName" length="45" />
</property>
<property name="middleName" type="string">
<column name="middleName" length="45" />
</property>
<property name="dob" type="date">
<column name="dob" length="10" />
</property>
<property name="martitalStatus" type="java.lang.Boolean">
<column name="martitalStatus" />
</property>
<property name="gender" type="string">
<column name="gender" length="45" />
</property>
<property name="nic" type="string">
<column name="nic" length="45" />
</property>
<property name="dateCreated" type="timestamp">
<column name="dateCreated" length="19" />
</property>
<property name="lastUpdated" type="timestamp">
<column name="lastUpdated" length="19" not-null="true" />
</property>
<set name="contacts" table="contact" inverse="true" lazy="true" fetch="select">
<key>
<column name="idPatient" not-null="true" />
</key>
<one-to-many class="db.Contact" />
</set>
</class>
</hibernate-mapping>
Contact.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<!-- Generated Sep 8, 2016 9:56:01 AM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="db.Contact" table="contact" catalog="example_hibernate" optimistic-lock="version">
<id name="idContact" type="java.lang.Integer">
<column name="idContact" />
<generator class="identity" />
</id>
<many-to-one name="patient" class="db.Patient" fetch="select">
<column name="idPatient" not-null="true" />
</many-to-one>
<property name="telephone" type="string">
<column name="telephone" length="45" />
</property>
<property name="address" type="string">
<column name="address" length="45" />
</property>
</class>
</hibernate-mapping>
Contact table has a foreign key which is the primary key of the patient table.
When I run above code , A new patient record could see in patient table but couldn't see any new contact record in contact table .
Is there anything wrong.
Have any ideas .
You need to tell Hibernate that you have a one to many relationship betweens patients and their contacts. After you have done this, persisting a Patient object should also persist the entire graph of that patient. If you were using annotations, then something like this should work:
#Entity
#Table(name="Patient")
public class Patient {
#OneToMany(mappedBy="patient")
private Set<Contact> contacts;
}
#Entity
#Table(name="Contact")
public class Contact {
#ManyToOne
private Patient patient;
}
in Patient.hbm.xml
while mentioning the set for contacts, use the following cascade property
<set name="contacts" table="contact" cascade="save-update" inverse="true" lazy="true" fetch="select">
<key>
<column name="idPatient" not-null="true" />
</key>
<one-to-many class="db.Contact" />
</set>
By mentioning cascade as save-update, you just have to invoke session.save(patientObj), and contact details will automatically get persisted.
Check this link for complete reference of cascading updates/inserts/delete operation in hibernate associations.

Hibernate query stopped working after switching to maven

I wanted an easier way to manage libraries so I decided to work on adding maven to my project. Basically copied the code into the folders, added all the cfg and hbm files to the resources folder. My project was working as intended before maven with the same code. I even reverted back from Hibernate 5.0 to 4.2 to try and solve the problem. It appears to be a mapping problem, I get the following error on start:
01:21:49.184 [AWT-EventQueue-0] ERROR org.hibernate.engine.jdbc.spi.SqlExceptionHelper - 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 where (inplay=true )and(bin<30 ) order by bin ASC' at line 1
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:63)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:109)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:95)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.extract(ResultSetReturnImpl.java:79)
at org.hibernate.loader.Loader.getResultSet(Loader.java:2116)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1899)
at org.hibernate.loader.Loader.executeQueryStatement(Loader.java:1875)
at org.hibernate.loader.Loader.doQuery(Loader.java:919)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:336)
at org.hibernate.loader.Loader.doList(Loader.java:2611)
at org.hibernate.loader.Loader.doList(Loader.java:2594)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2423)
at org.hibernate.loader.Loader.list(Loader.java:2418)
at org.hibernate.hql.internal.classic.QueryTranslatorImpl.list(QueryTranslatorImpl.java:957)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:226)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1268)
at org.hibernate.internal.QueryImpl.list(QueryImpl.java:87)
at dao.TicketDAO.get30Tickets(TicketDAO.java:88)
at gui.SellingMain.reloadGameButtons(SellingMain.java:98)
at gui.SellingMain.<init>(SellingMain.java:78)
at gui.SellingMain$39.run(SellingMain.java:2029)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:756)
at java.awt.EventQueue.access$500(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:709)
at java.awt.EventQueue$3.run(EventQueue.java:703)
at java.security.AccessController.doPrivileged(Native Method)
The code:
public List<Tickets> get30Tickets(){
List ts = new ArrayList<Tickets>();
session = HibernateUtil.getSessionFactory().openSession();
try{
trns = session.beginTransaction();
ts = session.createQuery("from Tickets as t where t.inplay = true and t.bin < 30 ORDER BY t.bin ASC").list();
} catch (RuntimeException e){
e.printStackTrace();
} finally {
releaseResources();
}
return ts;
}
tickets entity:
<?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 Oct 11, 2015 7:57:00 PM by Hibernate Tools 4.3.1 -->
<hibernate-mapping>
<class name="entity.Tickets" table="tickets" catalog="fire_tickets" optimistic-lock="version">
<composite-id name="id" class="entity.TicketsId">
<key-property name="serial" type="string">
<column name="Serial" length="12" />
</key-property>
<key-property name="gameTemplatesPartNum" type="string">
<column name="game_templates_part_num" length="12" />
</key-property>
</composite-id>
<property name="datePlaced" type="date">
<column name="Date_placed" length="10" />
</property>
<property name="dateRemoved" type="date">
<column name="Date_removed" length="10" />
</property>
<property name="unsoldAmt" type="java.lang.Integer">
<column name="Unsold_amt" />
</property>
<property name="actualGross" type="java.lang.Integer">
<column name="Actual_gross" />
</property>
<property name="actualPrizes" type="java.lang.Integer">
<column name="Actual_prizes" />
</property>
<property name="actualNet" type="java.lang.Integer">
<column name="Actual_net" />
</property>
<property name="bin" type="java.lang.Integer">
<column name="Bin" />
</property>
<property name="inplay" type="java.lang.Boolean">
<column name="Inplay" />
</property>
<property name="closed" type="java.lang.Integer">
<column name="Closed" />
</property>
<property name="unsoldTickets" type="java.lang.Integer">
<column name="Unsold_tickets" />
</property>
<property name="lastSaleRem" type="java.lang.Byte">
<column name="Last_sale_rem" />
</property>
<property name="prizeRem1" type="java.lang.Integer">
<column name="Prize_rem1" />
</property>
<property name="prizeRem2" type="java.lang.Integer">
<column name="Prize_rem2" />
</property>
<property name="prizeRem3" type="java.lang.Integer">
<column name="Prize_rem3" />
</property>
<property name="prizeRem4" type="java.lang.Integer">
<column name="Prize_rem4" />
</property>
<property name="prizeRem5" type="java.lang.Integer">
<column name="Prize_rem5" />
</property>
<property name="prizeRem6" type="java.lang.Integer">
<column name="Prize_rem6" />
</property>
<property name="prizeRem7" type="java.lang.Integer">
<column name="Prize_rem7" />
</property>
<property name="prizeRem8" type="java.lang.Integer">
<column name="Prize_rem8" />
</property>
<property name="prizeRem9" type="java.lang.Integer">
<column name="Prize_rem9" />
</property>
<property name="prizeRem10" type="java.lang.Integer">
<column name="Prize_rem10" />
</property>
<property name="prizeRem11" type="java.lang.Integer">
<column name="Prize_rem11" />
</property>
<property name="prizeRem12" type="java.lang.Integer">
<column name="Prize_rem12" />
</property>
<property name="prizeRem13" type="java.lang.Integer">
<column name="Prize_rem13" />
</property>
<property name="prizeRem14" type="java.lang.Integer">
<column name="Prize_rem14" />
</property>
<property name="prizeRem15" type="java.lang.Integer">
<column name="Prize_rem15" />
</property>
<property name="datePurch" type="date">
<column name="date_purch" length="10" />
</property>
<property name="invoiceNum" type="string">
<column name="invoice_num" length="10" />
</property>
<property name="type" type="java.lang.Integer">
<column name="type" />
</property>
</class>
</hibernate-mapping>
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="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://192.168.1.2:3306/fire_tickets</property>
<property name="hibernate.connection.username">-</property>
<property name="hibernate.connection.password">-</property>
<property name="hibernate.query.factory_class">org.hibernate.hql.internal.classic.ClassicQueryTranslatorFactory</property>
<property name="show_sql">false</property>
<property name="hibernate.jdbc.batch_size">20</property>
<mapping resource="entity/Users.hbm.xml"/>
<mapping resource="entity/SaleSessions.hbm.xml"/>
<mapping resource="entity/GameTemplates.hbm.xml"/>
<mapping resource="entity/MfgId.hbm.xml"/>
<mapping resource="entity/Customers.hbm.xml"/>
<mapping resource="entity/BigWinners.hbm.xml"/>
<mapping resource="entity/Locations.hbm.xml"/>
<mapping resource="entity/Sessions.hbm.xml"/>
<mapping resource="entity/TillTape.hbm.xml"/>
<mapping resource="entity/DistsId.hbm.xml"/>
<mapping resource="entity/Tickets.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Tickets.java
package entity;
// Generated Oct 11, 2015 7:56:58 PM by Hibernate Tools 4.3.1
import javax.persistence.*;
import java.util.Date;
/**
* Tickets generated by hbm2java
*/
#Entity
#Table(name="tickets"
,catalog="fire_tickets"
, uniqueConstraints = #UniqueConstraint(columnNames="Serial")
)
public class Tickets implements java.io.Serializable {
private TicketsId id;
private Date datePlaced;
private Date dateRemoved;
private Integer unsoldAmt;
private Integer actualGross;
private Integer actualPrizes;
private Integer actualNet;
private Integer bin;
private Boolean inplay;
private Integer closed;
private Integer unsoldTickets;
private Byte lastSaleRem;
private Integer prizeRem1;
private Integer prizeRem2;
private Integer prizeRem3;
private Integer prizeRem4;
private Integer prizeRem5;
private Integer prizeRem6;
private Integer prizeRem7;
private Integer prizeRem8;
private Integer prizeRem9;
private Integer prizeRem10;
private Integer prizeRem11;
private Integer prizeRem12;
private Integer prizeRem13;
private Integer prizeRem14;
private Integer prizeRem15;
private Date datePurch;
private String invoiceNum;
private Integer type;
public Tickets() {
}
public Tickets(TicketsId id) {
this.id = id;
}
public Tickets(TicketsId id, Date datePlaced, Date dateRemoved, Integer unsoldAmt, Integer actualGross, Integer actualPrizes, Integer actualNet, Integer bin, Boolean inplay, Integer closed, Integer unsoldTickets, Byte lastSaleRem, Integer prizeRem1, Integer prizeRem2, Integer prizeRem3, Integer prizeRem4, Integer prizeRem5, Integer prizeRem6, Integer prizeRem7, Integer prizeRem8, Integer prizeRem9, Integer prizeRem10, Integer prizeRem11, Integer prizeRem12, Integer prizeRem13, Integer prizeRem14, Integer prizeRem15, Date datePurch, String invoiceNum, Integer type) {
this.id = id;
this.datePlaced = datePlaced;
this.dateRemoved = dateRemoved;
this.unsoldAmt = unsoldAmt;
this.actualGross = actualGross;
this.actualPrizes = actualPrizes;
this.actualNet = actualNet;
this.bin = bin;
this.inplay = inplay;
this.closed = closed;
this.unsoldTickets = unsoldTickets;
this.lastSaleRem = lastSaleRem;
this.prizeRem1 = prizeRem1;
this.prizeRem2 = prizeRem2;
this.prizeRem3 = prizeRem3;
this.prizeRem4 = prizeRem4;
this.prizeRem5 = prizeRem5;
this.prizeRem6 = prizeRem6;
this.prizeRem7 = prizeRem7;
this.prizeRem8 = prizeRem8;
this.prizeRem9 = prizeRem9;
this.prizeRem10 = prizeRem10;
this.prizeRem11 = prizeRem11;
this.prizeRem12 = prizeRem12;
this.prizeRem13 = prizeRem13;
this.prizeRem14 = prizeRem14;
this.prizeRem15 = prizeRem15;
this.datePurch = datePurch;
this.invoiceNum = invoiceNum;
this.type = type;
}
#EmbeddedId
#AttributeOverrides( {
#AttributeOverride(name="serial", column=#Column(name="Serial", unique=true, nullable=false, length=12) ),
#AttributeOverride(name="gameTemplatesPartNum", column=#Column(name="game_templates_part_num", nullable=false, length=12) ) } )
public TicketsId getId() {
return this.id;
}
public void setId(TicketsId id) {
this.id = id;
}
#Temporal(TemporalType.DATE)
#Column(name="Date_placed", length=10)
public Date getDatePlaced() {
return this.datePlaced;
}
public void setDatePlaced(Date datePlaced) {
this.datePlaced = datePlaced;
}
#Temporal(TemporalType.DATE)
#Column(name="Date_removed", length=10)
public Date getDateRemoved() {
return this.dateRemoved;
}
public void setDateRemoved(Date dateRemoved) {
this.dateRemoved = dateRemoved;
}
#Column(name="Unsold_amt")
public Integer getUnsoldAmt() {
return this.unsoldAmt;
}
public void setUnsoldAmt(Integer unsoldAmt) {
this.unsoldAmt = unsoldAmt;
}
#Column(name="Actual_gross")
public Integer getActualGross() {
return this.actualGross;
}
public void setActualGross(Integer actualGross) {
this.actualGross = actualGross;
}
#Column(name="Actual_prizes")
public Integer getActualPrizes() {
return this.actualPrizes;
}
public void setActualPrizes(Integer actualPrizes) {
this.actualPrizes = actualPrizes;
}
#Column(name="Actual_net")
public Integer getActualNet() {
return this.actualNet;
}
public void setActualNet(Integer actualNet) {
this.actualNet = actualNet;
}
#Column(name="Bin")
public Integer getBin() {
return this.bin;
}
public void setBin(Integer bin) {
this.bin = bin;
}
#Column(name="Inplay")
public Boolean getInplay() {
return this.inplay;
}
public void setInplay(Boolean inplay) {
this.inplay = inplay;
}
#Column(name="Closed")
public Integer getClosed() {
return this.closed;
}
public void setClosed(Integer closed) {
this.closed = closed;
}
#Column(name="Unsold_tickets")
public Integer getUnsoldTickets() {
return this.unsoldTickets;
}
public void setUnsoldTickets(Integer unsoldTickets) {
this.unsoldTickets = unsoldTickets;
}
#Column(name="Last_sale_rem")
public Byte getLastSaleRem() {
return this.lastSaleRem;
}
public void setLastSaleRem(Byte lastSaleRem) {
this.lastSaleRem = lastSaleRem;
}
#Column(name="Prize_rem1")
public Integer getPrizeRem1() {
return this.prizeRem1;
}
public void setPrizeRem1(Integer prizeRem1) {
this.prizeRem1 = prizeRem1;
}
#Column(name="Prize_rem2")
public Integer getPrizeRem2() {
return this.prizeRem2;
}
public void setPrizeRem2(Integer prizeRem2) {
this.prizeRem2 = prizeRem2;
}
#Column(name="Prize_rem3")
public Integer getPrizeRem3() {
return this.prizeRem3;
}
public void setPrizeRem3(Integer prizeRem3) {
this.prizeRem3 = prizeRem3;
}
#Column(name="Prize_rem4")
public Integer getPrizeRem4() {
return this.prizeRem4;
}
public void setPrizeRem4(Integer prizeRem4) {
this.prizeRem4 = prizeRem4;
}
#Column(name="Prize_rem5")
public Integer getPrizeRem5() {
return this.prizeRem5;
}
public void setPrizeRem5(Integer prizeRem5) {
this.prizeRem5 = prizeRem5;
}
#Column(name="Prize_rem6")
public Integer getPrizeRem6() {
return this.prizeRem6;
}
public void setPrizeRem6(Integer prizeRem6) {
this.prizeRem6 = prizeRem6;
}
#Column(name="Prize_rem7")
public Integer getPrizeRem7() {
return this.prizeRem7;
}
public void setPrizeRem7(Integer prizeRem7) {
this.prizeRem7 = prizeRem7;
}
#Column(name="Prize_rem8")
public Integer getPrizeRem8() {
return this.prizeRem8;
}
public void setPrizeRem8(Integer prizeRem8) {
this.prizeRem8 = prizeRem8;
}
#Column(name="Prize_rem9")
public Integer getPrizeRem9() {
return this.prizeRem9;
}
public void setPrizeRem9(Integer prizeRem9) {
this.prizeRem9 = prizeRem9;
}
#Column(name="Prize_rem10")
public Integer getPrizeRem10() {
return this.prizeRem10;
}
public void setPrizeRem10(Integer prizeRem10) {
this.prizeRem10 = prizeRem10;
}
#Column(name="Prize_rem11")
public Integer getPrizeRem11() {
return this.prizeRem11;
}
public void setPrizeRem11(Integer prizeRem11) {
this.prizeRem11 = prizeRem11;
}
#Column(name="Prize_rem12")
public Integer getPrizeRem12() {
return this.prizeRem12;
}
public void setPrizeRem12(Integer prizeRem12) {
this.prizeRem12 = prizeRem12;
}
#Column(name="Prize_rem13")
public Integer getPrizeRem13() {
return this.prizeRem13;
}
public void setPrizeRem13(Integer prizeRem13) {
this.prizeRem13 = prizeRem13;
}
#Column(name="Prize_rem14")
public Integer getPrizeRem14() {
return this.prizeRem14;
}
public void setPrizeRem14(Integer prizeRem14) {
this.prizeRem14 = prizeRem14;
}
#Column(name="Prize_rem15")
public Integer getPrizeRem15() {
return this.prizeRem15;
}
public void setPrizeRem15(Integer prizeRem15) {
this.prizeRem15 = prizeRem15;
}
#Temporal(TemporalType.DATE)
#Column(name="date_purch", length=10)
public Date getDatePurch() {
return this.datePurch;
}
public void setDatePurch(Date datePurch) {
this.datePurch = datePurch;
}
#Column(name="invoice_num", length=10)
public String getInvoiceNum() {
return this.invoiceNum;
}
public void setInvoiceNum(String invoiceNum) {
this.invoiceNum = invoiceNum;
}
#Column(name="type")
public Integer getType() {
return this.type;
}
public void setType(Integer type) {
this.type = type;
}
}
The query where there is a syntax error looks different in the log than in the code.
It is possible that since you switched to maven your project is not compiling, and when you start your server, Eclipse (I assume) just deploy the last successfull build ".class"
Check if you have no error in your pom (esclamation mark) and try to clean everything.

Hibernate and mysql error : Cannot add or update a child row

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.

Categories

Resources