I am new to hibernate. My goal is to get query results to an ArrayList but I keep getting the ERROR: HHH000091: Expected type: int, actual value: org.hibernate.collection.internal.PersistentSet
I strongly believe the problem is in my mapping, any help is appreciated.
Errors
ERROR: HHH000123: IllegalArgumentException in class: com.mycompany.mavenproject1.Medicamento, setter method of property: labJoin
Apr 07, 2017 10:23:10 AM org.hibernate.property.BasicPropertyAccessor$BasicSetter set
ERROR: HHH000091: Expected type: int, actual value: org.hibernate.collection.internal.PersistentSet
My HQL query:
from Medicamento as m left join from Laboratorio as l where l.codigoLab=m.codigoLab
Mapping XML:
<class name="com.mycompany.mavenproject1.Medicamento" table="MEDICAMENTO" schema="ADMINFARMACIA" optimistic-lock="version">
<id name="codigoMed" type="long">
<column name="CODIGO_MED" not-null="true"/>
<generator class="assigned" />
</id>
<property name="nombreComercial" type="string">
<column name="NOMBRE_COMERCIAL" length="100" not-null="true" />
</property>
<property name="codigoPrincipio" type="string">
<column name="CODIGO_PRINCIPIO" length="50" not-null="true" />
</property>
<property name="stockMinimo" type="java.lang.Integer">
<column name="STOCK_MINIMO" />
</property>
<property name="codigoLab" type="java.lang.Integer">
<column name="CODIGO_LAB" />
</property>
<property name="comentario" type="string">
<column name="COMENTARIO" length="1000" />
</property>
<property name="existencias" type="java.lang.Integer">
<column name="EXISTENCIAS"/>
</property>
<set name="labJoin" fetch="join">
<key column="CODIGO_LAB" />
<one-to-many class="com.mycompany.mavenproject1.Laboratorio"/>
</set>
</class>
Laboratorio.java:
public class Laboratorio implements java.io.Serializable{
private int codigoLab;
private String nombreLab;
public Laboratorio(){
}
public int getCodigoLab() {
return codigoLab;
}
public void setCodigoLab(int codigoLab) {
this.codigoLab = codigoLab;
}
public String getNombreLab() {
return nombreLab;
}
public void setNombreLab(String nombreLab) {
this.nombreLab = nombreLab;
}
}
Medicamento.java - in this one labJoin and labName are the fields on "Laboratorio" table
public class Medicamento implements java.io.Serializable{
private Long codigoMed;
private String nombreComercial;
private String codigoPrincipio;
private int stockMinimo;
private int codigoLab;
private String comentario;
private int existencias;
private int labJoin;
private String labName;
public Medicamento(){
}
public Long getCodigoMed() {
return codigoMed;
}
public void setCodigoMed(Long codigoMed) {
this.codigoMed = codigoMed;
}
public String getNombreComercial() {
return nombreComercial;
}
public void setNombreComercial(String nombreComercial) {
this.nombreComercial = nombreComercial;
}
public String getCodigoPrincipio() {
return codigoPrincipio;
}
public void setCodigoPrincipio(String codigoPrincipio) {
this.codigoPrincipio = codigoPrincipio;
}
public int getStockMinimo() {
return stockMinimo;
}
public void setStockMinimo(int stockMinimo) {
this.stockMinimo = stockMinimo;
}
public int getCodigoLab() {
return codigoLab;
}
public void setCodigoLab(int codigoLab) {
this.codigoLab = codigoLab;
}
public int getLabJoin() {
return labJoin;
}
public void setLabJoin(int labJoin) {
this.labJoin = labJoin;
}
public String getLabName() {
return labName;
}
public void setLabJoin(String labName) {
this.labName= labName;
}
public String getComentario() {
return comentario;
}
public void setComentario(String comentario) {
this.comentario = comentario;
}
public int getExistencias() {
return existencias;
}
public void setExistencias(int existencias) {
this.existencias = existencias;
}
}
Calling method
private void displayResult(List rl){
ArrayList<Object> oneRow = new ArrayList<Object>();
for (Object o: rl){
Medicamento medList = (Medicamento)o;
System.out.println(labList.getCodigoLab());
oneRow.add(medList.getCodigoMed());
oneRow.add(medList.getExistencias());
oneRow.add(medList.getNombreComercial());
oneRow.add(medList.getLabJoin());
}
LowStockTableModel model = new LowStockTableModel(oneRow);
try{
jTable1.setModel(model);
}
catch (Exception e){
JOptionPane.showMessageDialog(null, e.getLocalizedMessage(),"Error",JOptionPane.ERROR_MESSAGE);
jTextField1.setText("");
}
}
In your mapping, you have this
<set name="labJoin" fetch="join">
<key column="CODIGO_LAB" />
<one-to-many class="com.mycompany.mavenproject1.Laboratorio"/>
</set>
But property labJoin has type int. The type of this property has to be Set<Laboratorio>.
Related
How to resolve this issue org.hibernate.AssertionFailure: null id in com.xxxxxx.Profiles entry (don't flush the Session after an exception occurs)
I'm using hibernate and Mysql, I want to insert the data into a table of my database but I was unable to do it.
Thanks.
This is my Dao:
public class ProfilesDao {
public void addProfile(Profiles profile){
Transaction tx = null;
Session session = HibernateUtil.getSessionFactory().openSession();
try{
tx = session.beginTransaction();
session.save(profile);
session.getTransaction().commit();
} catch (Exception e){
e.printStackTrace();
if(tx != null){
tx.rollback();
}
} finally {
session.flush();
session.close();
}
}
}
This is my Bean:
public void addProfile(){
Profiles profiles = new Profiles(getProfileName(),getProfileDescription());
ProfilesDao profilesDao = new ProfilesDao();
profilesDao.addProfile(profiles);
}
This is my POJO:
#Entity
#Table(name="profiles"
,catalog="metaestudiante_project_v1"
, uniqueConstraints = #UniqueConstraint(columnNames="profile_name")
)
public class Profiles implements java.io.Serializable {
private Short profileId;
private String profileName;
private String profileDescription;
private Set userses = new HashSet(0);
public Profiles() {
}
public Profiles(String profileName, String profileDescription) {
this.profileName = profileName;
this.profileDescription = profileDescription;
}
public Profiles(String profileName, String profileDescription, Set userses) {
this.profileName = profileName;
this.profileDescription = profileDescription;
this.userses = userses;
}
#Id #GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="profile_id", unique=true, nullable=false)
public Short getProfileId() {
return this.profileId;
}
public void setProfileId(Short profileId) {
this.profileId = profileId;
}
#Column(name="profile_name", unique=true, nullable=false, length=15)
public String getProfileName() {
return this.profileName;
}
public void setProfileName(String profileName) {
this.profileName = profileName;
}
#Column(name="profile_description", nullable=false, length=140)
public String getProfileDescription() {
return this.profileDescription;
}
public void setProfileDescription(String profileDescription) {
this.profileDescription = profileDescription;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="profiles")
public Set getUserses() {
return this.userses;
}
public void setUserses(Set userses) {
this.userses = userses;
}
}
And this is my hbm.xml
<hibernate-mapping>
<class name="com.besolapp.model.pojos.Profiles" table="profiles" catalog="metaestudiante_project_v1" optimistic-lock="version">
<id name="profileId" type="java.lang.Byte">
<column name="profile_id" />
<generator class="identity" />
</id>
<property name="profileName" type="string">
<column name="profile_name" length="15" not-null="true" unique="true" />
</property>
<property name="profileDescription" type="string">
<column name="profile_description" length="140" not-null="true" />
</property>
<set name="userses" table="users" inverse="true" lazy="true" fetch="select">
<key>
<column name="profile_id" not-null="true" />
</key>
<one-to-many class="com.besolapp.model.pojos.Users" />
</set>
</class>
</hibernate-mapping>
All this looks like easy but I am getting an error:
org.hibernate.AssertionFailure: null id in com.besolapp.model.pojos.Profiles entry (don't flush the Session after an exception occurs)
Can anybody help me please?
I am new to hibernate. I used MYSQL database. there is date field in my table. its type is DATE. There is a value 1989-08-13. When I get value using hibernate it gives that date as 6189498000000. I want to get value as real date (1989-08-13). Please help me
This is my xml file
<?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 Aug 27, 2013 1:03:09 AM by Hibernate Tools 4.0.0 -->
<hibernate-mapping>
<class name="core.classes.Staff" table="staff" catalog="surgercare">
<id name="staffId" type="int">
<column name="staff_ID" />
<generator class="assigned" />
</id>
<property name="staffName" type="string">
<column name="staff_Name" length="150" />
</property>
<property name="staffDesignation" type="string">
<column name="staff_designation" length="50" />
</property>
<property name="createDate" type="timestamp">
<column name="CreateDate" length="19" />
</property>
<property name="createUser" type="string">
<column name="CreateUser" length="200" />
</property>
<property name="lastUpDate" type="timestamp">
<column name="LastUpDate" length="19" />
</property>
<property name="lastUpDateUser" type="string">
<column name="LastUpDateUser" length="200" />
</property>
</class>
</hibernate-mapping>
My class file
import java.util.Date;
public class Staff implements java.io.Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private int staffId;
private String staffName;
private String staffDesignation;
private Date createDate;
private String createUser;
private Date lastUpDate;
private String lastUpDateUser;
public Staff() {
}
public Staff(int staffId) {
this.staffId = staffId;
}
public Staff(int staffId, String staffName, String staffDesignation,
Date createDate, String createUser, Date lastUpDate,
String lastUpDateUser) {
this.staffId = staffId;
this.staffName = staffName;
this.staffDesignation = staffDesignation;
this.createDate = createDate;
this.createUser = createUser;
this.lastUpDate = lastUpDate;
this.lastUpDateUser = lastUpDateUser;
}
public int getStaffId() {
return this.staffId;
}
public void setStaffId(int staffId) {
this.staffId = staffId;
}
public String getStaffName() {
return this.staffName;
}
public void setStaffName(String staffName) {
this.staffName = staffName;
}
public String getStaffDesignation() {
return this.staffDesignation;
}
public void setStaffDesignation(String staffDesignation) {
this.staffDesignation = staffDesignation;
}
public Date getCreateDate() {
return this.createDate;
}
public void setCreateDate(Date createDate) {
this.createDate = createDate;
}
public String getCreateUser() {
return this.createUser;
}
public void setCreateUser(String createUser) {
this.createUser = createUser;
}
public Date getLastUpDate() {
return this.lastUpDate;
}
public void setLastUpDate(Date lastUpDate) {
this.lastUpDate = lastUpDate;
}
public String getLastUpDateUser() {
return this.lastUpDateUser;
}
public void setLastUpDateUser(String lastUpDateUser) {
this.lastUpDateUser = lastUpDateUser;
}
}
this is my controller
tx = ses.beginTransaction();
Query query = ses.createQuery("select s from Staff as s where s.staffId = :ID");
query.setString("ID", docID);
List<Staff> DocDetailsList = castlist(Staff.class,query.list());
tx.commit();
return DocDetailsList;
In your hbm file, there are "timestamp" column type. Let hibernate guess the column type:
<property name="createDate" column="CreateDate" />
In other words, if you have the following property:
java.util.Date createDate;
hibernate3-maven-plugin hibernate3:hbm2ddl goal will create the following column in MySql:
`CreateDate` datetime DEFAULT NULL
Note: datetime and timestamp have different ranges. Same for Java Long (timestamp) and java.util.Date.
Good evening all,
I am trying to update a field in my page and keep getting an exception thrown.
I have a main object "car" that has a foreign key to "Model"
when I built my page I created a select box to list all the models. So now when I choose a model and submit the form I get the exception thrown below. All of the fields that are in the Car table update fine as long as I do not include the model field. Once I try to include the model field, code breaks on submitting.
org.apache.jasper.JasperException: An exception occurred processing JSP page /WEB-INF/jsp/sellcar.jsp at line 28
25: <c:forEach items="${cars}" var="car">
26: <option
27: value='<c:out value="${car.model.modId}"/>'
28: <c:if test="${car.model.model == status.value.model}">SELECTED</c:if>>
29: <c:out value="${car.model.model}" />
30: </option>
31: </c:forEach>
**Stacktrace:**
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:521)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:430)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:111)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1045)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:810)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:723)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:396)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:360)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
root cause
javax.el.PropertyNotFoundException: Property 'model' not found on type java.lang.String
javax.el.BeanELResolver$BeanProperties.get(BeanELResolver.java:214)
javax.el.BeanELResolver$BeanProperties.access$400(BeanELResolver.java:191)
javax.el.BeanELResolver.property(BeanELResolver.java:300)
javax.el.BeanELResolver.getValue(BeanELResolver.java:81)
javax.el.CompositeELResolver.getValue(CompositeELResolver.java:54)
org.apache.el.parser.AstValue.getValue(AstValue.java:123)
org.apache.el.parser.AstEqual.getValue(AstEqual.java:38)
org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:186)
org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:938)
org.apache.jsp.WEB_002dINF.jsp.sellcar_jsp._jspx_meth_c_005fif_005f0(sellcar_jsp.java:847)
org.apache.jsp.WEB_002dINF.jsp.sellcar_jsp._jspx_meth_c_005fforEach_005f0(sellcar_jsp.java:791)
org.apache.jsp.WEB_002dINF.jsp.sellcar_jsp._jspService(sellcar_jsp.java:107)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:111)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:250)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1045)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:810)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:723)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:396)
org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:360)
javax.servlet.http.HttpServlet.service(HttpServlet.java:637)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
</b>
My Models:
Car:
package com.usedcarsearch.domain;
// Generated Feb 19, 2013 10:31:37 PM by Hibernate Tools 3.4.0.CR1
import java.math.BigDecimal;
import java.util.HashSet;
import java.util.Set;
/**
* Car generated by hbm2java
*/
public class Car implements java.io.Serializable {
private Integer carId;
private Make make;
private State state;
private Model model;
private City city;
private String vin;
private int year;
private String image;
private String engine;
private String trans;
private String mileage;
private BigDecimal price;
private String color;
private BigDecimal hwyMpg;
private BigDecimal cityMpg;
private String address;
private String accessories;
private String comments;
private Set buyers = new HashSet(0);
private Set ownerships = new HashSet(0);
private Set carSearchLists = new HashSet(0);
public Car() {
}
public Car(Make make, State state, Model model, City city, int year,
String engine, String trans, String mileage) {
this.make = make;
this.state = state;
this.model = model;
this.city = city;
this.year = year;
this.engine = engine;
this.trans = trans;
this.mileage = mileage;
}
public Car(Make make, State state, Model model, City city, String vin,
int year, String image, String engine, String trans,
String mileage, BigDecimal price, String color, BigDecimal hwyMpg,
BigDecimal cityMpg, String address, String accessories,
String comments, Set buyers, Set ownerships, Set carSearchLists) {
this.make = make;
this.state = state;
this.model = model;
this.city = city;
this.vin = vin;
this.year = year;
this.image = image;
this.engine = engine;
this.trans = trans;
this.mileage = mileage;
this.price = price;
this.color = color;
this.hwyMpg = hwyMpg;
this.cityMpg = cityMpg;
this.address = address;
this.accessories = accessories;
this.comments = comments;
this.buyers = buyers;
this.ownerships = ownerships;
this.carSearchLists = carSearchLists;
}
public Integer getCarId() {
return this.carId;
}
public void setCarId(Integer carId) {
this.carId = carId;
}
public Make getMake() {
return this.make;
}
public void setMake(Make make) {
this.make = make;
}
public State getState() {
return this.state;
}
public void setState(State state) {
this.state = state;
}
public Model getModel() {
return this.model;
}
public void setModel(Model model) {
this.model = model;
}
public City getCity() {
return this.city;
}
public void setCity(City city) {
this.city = city;
}
public String getVin() {
return this.vin;
}
public void setVin(String vin) {
this.vin = vin;
}
public int getYear() {
return this.year;
}
public void setYear(int year) {
this.year = year;
}
public String getImage() {
return this.image;
}
public void setImage(String image) {
this.image = image;
}
public String getEngine() {
return this.engine;
}
public void setEngine(String engine) {
this.engine = engine;
}
public String getTrans() {
return this.trans;
}
public void setTrans(String trans) {
this.trans = trans;
}
public String getMileage() {
return this.mileage;
}
public void setMileage(String mileage) {
this.mileage = mileage;
}
public BigDecimal getPrice() {
return this.price;
}
public void setPrice(BigDecimal price) {
this.price = price;
}
public String getColor() {
return this.color;
}
public void setColor(String color) {
this.color = color;
}
public BigDecimal getHwyMpg() {
return this.hwyMpg;
}
public void setHwyMpg(BigDecimal hwyMpg) {
this.hwyMpg = hwyMpg;
}
public BigDecimal getCityMpg() {
return this.cityMpg;
}
public void setCityMpg(BigDecimal cityMpg) {
this.cityMpg = cityMpg;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getAccessories() {
return this.accessories;
}
public void setAccessories(String accessories) {
this.accessories = accessories;
}
public String getComments() {
return this.comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public Set getBuyers() {
return this.buyers;
}
public void setBuyers(Set buyers) {
this.buyers = buyers;
}
public Set getOwnerships() {
return this.ownerships;
}
public void setOwnerships(Set ownerships) {
this.ownerships = ownerships;
}
public Set getCarSearchLists() {
return this.carSearchLists;
}
public void setCarSearchLists(Set carSearchLists) {
this.carSearchLists = carSearchLists;
}
}
Model:
package com.usedcarsearch.domain;
// Generated Feb 19, 2013 10:31:37 PM by Hibernate Tools 3.4.0.CR1
import java.util.HashSet;
import java.util.Set;
/**
* Model generated by hbm2java
*/
public class Model implements java.io.Serializable {
private Integer modId;
private String model;
private Set cars = new HashSet(0);
public Model() {
}
public Model(String model) {
this.model = model;
}
public Model(String model, Set cars) {
this.model = model;
this.cars = cars;
}
public Integer getModId() {
return this.modId;
}
public void setModId(Integer modId) {
this.modId = modId;
}
public String getModel() {
return this.model;
}
public void setModel(String model) {
this.model = model;
}
public Set getCars() {
return this.cars;
}
public void setCars(Set cars) {
this.cars = cars;
}
}
Car.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 Feb 19, 2013 10:31:37 PM by Hibernate Tools 3.4.0.CR1 -->
<hibernate-mapping default-lazy="false">
<class name="com.usedcarsearch.domain.Car" table="Car">
<id name="carId" type="java.lang.Integer">
<column name="carId"/>
<generator class="identity"/>
</id>
<many-to-one class="com.usedcarsearch.domain.Make"
fetch="select" name="make">
<column name="fkMakeId" not-null="true"/>
</many-to-one>
<many-to-one class="com.usedcarsearch.domain.State"
fetch="select" name="state">
<column name="fkStateId" not-null="true"/>
</many-to-one>
<many-to-one class="com.usedcarsearch.domain.Model"
fetch="select" name="model">
<column name="fkModelId" not-null="true"/>
</many-to-one>
<many-to-one class="com.usedcarsearch.domain.City"
fetch="select" name="city">
<column name="fkZipCode" not-null="true"/>
</many-to-one>
<property generated="never" lazy="false" name="vin" type="string">
<column length="25" name="vin"/>
</property>
<property generated="never" lazy="false" name="year" type="int">
<column name="year" not-null="true"/>
</property>
<property generated="never" lazy="false" name="image" type="string">
<column length="100" name="image"/>
</property>
<property generated="never" lazy="false" name="engine" type="string">
<column length="45" name="engine" not-null="true"/>
</property>
<property generated="never" lazy="false" name="trans" type="string">
<column length="45" name="trans" not-null="true"/>
</property>
<property generated="never" lazy="false" name="mileage" type="string">
<column length="20" name="mileage" not-null="true"/>
</property>
<property generated="never" lazy="false" name="price" type="big_decimal">
<column name="price" precision="11"/>
</property>
<property generated="never" lazy="false" name="color" type="string">
<column length="20" name="color"/>
</property>
<property generated="never" lazy="false" name="hwyMpg" type="big_decimal">
<column name="hwyMpg" precision="3" scale="1"/>
</property>
<property generated="never" lazy="false" name="cityMpg" type="big_decimal">
<column name="cityMpg" precision="3" scale="1"/>
</property>
<property generated="never" lazy="false" name="address" type="string">
<column length="50" name="address"/>
</property>
<property generated="never" lazy="false" name="accessories" type="string">
<column length="100" name="accessories"/>
</property>
<property generated="never" lazy="false" name="comments" type="string">
<column length="100" name="comments"/>
</property>
<set fetch="select" inverse="true" lazy="false" name="buyers"
sort="unsorted" table="Buyer">
<key>
<column name="fkCarId" not-null="true"/>
</key>
<one-to-many class="com.usedcarsearch.domain.Buyer"/>
</set>
<set fetch="select" inverse="true" lazy="false" name="ownerships"
sort="unsorted" table="Ownership">
<key>
<column name="fkCarId" not-null="true"/>
</key>
<one-to-many class="com.usedcarsearch.domain.Ownership"/>
</set>
<set fetch="select" inverse="true" lazy="false" name="carSearchLists"
sort="unsorted" table="Car_Search_List">
<key>
<column name="fkCarId" not-null="true"/>
</key>
<one-to-many class="com.usedcarsearch.domain.CarSearchList"/>
</set>
</class>
</hibernate-mapping>
JSP code: (I did not include all but only what is necessary)
<spring:bind path="command.model">
<select name='<c:out value="${status.expression}"/>'>
<option value=""></option>
<c:forEach items="${cars}" var="car">
<option value='<c:out value="${car.model.modId}"/>'
<c:if test="${car.model.model == status.value.model}">SELECTED</c:if>>
<c:out value="${car.model.model}" />
</option>
</c:forEach>
</select>
I got it fixed. It seems I had to add the foreign key property in the Car.hbm along with adding the foreign keys variables, getters and setters to Car.
Based on the error message you might want to change line 28 from:
status.value.model
to
status.value
I am using hibernate to insert objects of the class meal in a hsql DB It works fine if I only insert 1 object but as soon as I try to insert a second it gives me an error. Here is my code and the error:
public static void main(String[] args) {
Main obj = new Main();
Long mealId1 = obj.saveMeal("Pommes");
Long mealId2 = obj.saveMeal("Doener1");
}
public Long saveMeal(String mealName)
{
Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
Long mealId = null;
try {
transaction = session.beginTransaction();
Meal meal = new Meal(mealName);
mealId = (Long) session.save(meal);
transaction.commit();
} catch (HibernateException e) {
transaction.rollback();
e.printStackTrace();
} finally {
session.close();
}
return mealId;
}
package data;
import java.util.List;
import java.util.LinkedList;
public class Meal implements java.io.Serializable {
private long id;
private String name;
private List<Image> images;
private List<Review> reviews;
private Grouping grouping;
public Meal() {
}
public Meal(String mealName) {
name = mealName;
}
public Meal(long mealId, String mealName) {
id = mealId;
name = mealName;
}
public long getId() {
return id;
}
public void setId(long mealId) {
id = mealId;
}
public String getMealName() {
return name;
}
public void setMealName(String mealName) {
name = mealName;
}
public float getAvg() {
float avg = 0;
for (int i = 0; i < reviews.size(); i++)
{
avg = avg + reviews.get(i).getReviewPoints();
}
return avg;
}
public List<Image> getNumberImages(int number) {
assert (number >= 0);
return images.subList(0, number) ;
}
public List<Image> getImages() {
return images;
}
public void setImages(LinkedList<Image> images) {
this.images = images;
}
public List<Review> getReviews(int number) {
assert (number >= 0);
return reviews.subList(0, number) ;
}
public LinkedList<String> getAltNames() {
LinkedList<String> altNames = new LinkedList<String>();
LinkedList<Meal> altNameMeals = grouping.getMeals();
for (int i = 0; i < altNameMeals.size(); i++)
{
altNames.add(altNameMeals.get(i).getMealName());
}
return altNames;
}
public void addReview(Review review) {
if (!reviews.contains(review)) {
reviews.add(review);
}
}
public Grouping getGrouping() {
return grouping;
}
public void setGrouping(Grouping grouping) {
this.grouping = grouping;
}
public void addImage(Image image) {
if (!images.contains(image)) {
images.add(image);
}
}<hibernate-mapping>
<class name="data.Meal" table="MEAL">
<id name="id" type="long" access="field">
<column name="ID" />
<generator class="assigned" />
</id>
<property name="name" type="java.lang.String" access="field">
<column name="NAME" />
</property>
<list name="images" inverse="false" table="IMAGE" lazy="true" access="field">
<key>
<column name="ID" />
</key>
<list-index column="column_name" />
<one-to-many class="data.Image" />
</list>
<list name="reviews" inverse="false" table="REVIEW" lazy="true" access="field">
<key>
<column name="ID" />
</key>
<list-index></list-index>
<one-to-many class="data.Review" />
</list>
<many-to-one name="grouping" class="data.Grouping" fetch="join">
<column name="GROUPING" />
</many-to-one>
</class>
First is the main method 2nd the class to be persitet and 3rd the hibernate mapping for the class. This is the error message:
843 [main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: -104, SQLState: 23505
843 [main] ERROR org.hibernate.util.JDBCExceptionReporter - integrity constraint violation: unique constraint or index violation; SYS_PK_10585 table: MEAL
843 [main] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
You declared that you want to assign values to id property manually (<generator class="assigned" />), but don't actually assign it.
So, you need to assign the value manually or declare different id generation strategy.
The hibernate mapping of my hbm.xml is:
<class name="UserCalendar" table="user_calendar">
<id name="userCalendarId" column="user_calendar_id" type="long">
<generator class="native" />
</id>
<property name="userId" column="user_id" type="long" not-null="true"/>
<property name="userLoginName" column="user_login_name" type="string" not-null="true" length="32000" />
<property name="userName" column="user_name" type="string" not-null="true" length="32000" />
<list name="userDates" cascade="all" lazy="false">
<key column="user_calendar_id"/>
<index column="idx"/>
<one-to-many class="UserDate"/>
</list>
</class>
<class name="UserDate" table="user_date">
<id name="userDateId" column="user_date_id" type="long">
<generator class="native" />
</id>
<property name="date" column="date" type="date"/>
<list name="userItems" cascade="all" lazy="false">
<key column="user_date_id"/>
<index column="idx"/>
<one-to-many class="UserItem"/>
</list>
</class>
<class name="UserItem" table="user_item">
<id name="userItemId" column="user_item_id" type="long">
<generator class="native"/>
</id>
<property name="spaceId" column="space_id" type="long"/>
<property name="spaceName" column="space_name" type="string"/>
<property name="itemRefId" column="item_ref_id" type="string"/>
<property name="itemId" column="item_id" type="long"/>
<property name="allocation" column="allocation" type="double"/>
<property name="scheduledStrategy" column="scheduled_strategy" type="integer"/>
<property name="utilization" column="utilization" type="double"/>
<property name="deadline" column="deadline" type="date"/>
<property name="ticketType" column="ticket_type" type="integer"/>
<property name="isCurrentlyAssigned" column="is_currently_assigned" type="boolean"/>
</class>
The UserCalendar.java:
public class UserCalendar implements Serializable {
private static final long serialVersionUID = 10172L;
private long userCalendarId;
private long userId;
private String userLoginName;
private String userName;
private List<UserDate> userDates;
public UserCalendar() {
}
public long getUserCalendarId() {
return userCalendarId;
}
public void setUserCalendarId(long userCalendarId) {
this.userCalendarId = userCalendarId;
}
public long getUserId() {
return userId;
}
public void setUserId(long userId) {
this.userId = userId;
}
public String getUserLoginName() {
return userLoginName;
}
public void setUserLoginName(String userLoginName) {
this.userLoginName = userLoginName;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public List<UserDate> getUserDates() {
return userDates;
}
public void setUserDates(List<UserDate> userDates) {
this.userDates = userDates;
}
}
The UserDate.java:
public class UserDate implements Serializable {
private static final long serialVersionUID = 10173L;
private long userDateId;
private Date date;
private List<UserItem> userItems;
public UserDate() {
}
public long getUserDateId() {
return userDateId;
}
public void setUserDateId(long userDateId) {
this.userDateId = userDateId;
}
public void setDate(Date date) {
this.date = date;
}
public Date getDate() {
return date;
}
public List<UserItem> getUserItems() {
return userItems;
}
public void setUserItems(List<UserItem> userItems) {
this.userItems = userItems;
}
}
And the UserItem.java:
public class UserItem implements Serializable {
private static final long serialVersionUID = 10174L;
public static final int AUTO = 1;
public static final int EQUAL = 2;
public static final int CUSTOM = 3;
public static final int CUSTOM_EQUAL = 4;
public static final int GENERAL_TICKET = 5;
public static final int SPECIAL_TICKET_HALF = 6;
public static final int SPECIAL_TICKET_FULL = 7;
private long userItemId;
private long spaceId;
private String spaceName;
private long itemId;
private String itemRefId;
private double allocation;
private int scheduledStrategy;
private double utilization;
private Date deadline;
private int ticketType;
private boolean isCurrentlyAssigned;
public UserItem() {
}
public long getUserItemId() {
return userItemId;
}
public void setUserItemId(long userItemId) {
this.userItemId = userItemId;
}
public long getSpaceId() {
return spaceId;
}
public void setSpaceId(long spaceId) {
this.spaceId = spaceId;
}
public long getItemId() {
return itemId;
}
public void setItemId(long itemId) {
this.itemId = itemId;
}
public double getAllocation() {
return allocation;
}
public void setAllocation(double allocation) {
this.allocation = allocation;
}
public int getScheduledStrategy() {
return scheduledStrategy;
}
public void setScheduledStrategy(int scheduledStrategy) {
this.scheduledStrategy = scheduledStrategy;
}
public double getUtilization() {
return utilization;
}
public void setUtilization(double utilization) {
this.utilization = utilization;
}
public Date getDeadline() {
return deadline;
}
public void setDeadline(Date deadline) {
this.deadline = deadline;
}
public int getTicketType() {
return ticketType;
}
public void setTicketType(int ticketType) {
this.ticketType = ticketType;
}
public String getSpaceName() {
return spaceName;
}
public void setSpaceName(String spaceName) {
this.spaceName = spaceName;
}
public String getItemRefId() {
return itemRefId;
}
public void setItemRefId(String itemRefId) {
this.itemRefId = itemRefId;
}
public boolean isCurrentlyAssigned() {
return isCurrentlyAssigned;
}
public void setCurrentlyAssigned(boolean isCurrentlyAssigned) {
this.isCurrentlyAssigned = isCurrentlyAssigned;
}
}
Now I want to select those UserCalendar object which has a specific itemId. In my thought if I insert userCalendarId in UserItem and execute
SELECT USERCALENDAR
FROM USER_CALENDAR
WHERE USERCALENDAR.USERCALENDARID IN
(SELECT USERCALENDARID
FROM USERITEM
WHERE USERITEM.ITEMID=ID)
then it might be possible.
Am I right?
How can I insert userCalendarId in UserItem? What is the mapping needed for this?
Thanks and regards.
To have one-to-many you will need column in UserDate that refers to UserCalendar.userCalendarId and column in UserItem to refer to UserDate.userDateId. You will need to specify those columns via many-to-one in those classes.
Then you can use join
SELECT * FROM user_calendar uc
JOIN user_date ud ON ud.user_calendar_id=uc.user_calendar_id
JOIN user_item ui ON ui.user_date_id=ud.user_date_id
WHERE ui.user_item_id=<your value>
Assuming that you have those new columns user_calendar_id and user_date_id in user_date and user_item.
In HQL it will be simpler but I don't remember on top of my head. Check docs.
It could be something like
select ui.userDate.userCaledar from UserItem ui where ui.userItemId=:id
Provided that you added properties userDate and userCalendar via many-to-one