Property nulled in the response from Spring/Hibernate - java

I have a Javascript application that uses Java as a backend with Hibernate, Spring and MySQL DB . When reading data everything works fine and as expected but when trying to edit it on the client side I can see strange behaviour. Even though my server request looks like this :
{"data":{"Draggable":true,"Resizable":true,"StartDate":"2012-09-13T18:00:00+02:00","EndDate":"2012-09-14T04:00:00+02:00","Cls":"","Name":"Secret task","Id":10,"ResourceId":15}}
server responds with :
{"data":[{"Name":"Secret task","Id":10,"StartDate":"2012-09-13T18:00:00+02:00","EndDate":"2012-09-14T04:00:00+02:00","ResourceId":15,"Resizable":null,"Draggable":null,"Cls":""}]}
in which the boolean properties are nulled. I've tried ignoring the setter for this field but without any luck. I also had to remove nullable=false as with this included I was getting an error :
org.springframework.dao.DataIntegrityViolationException: not-null property references a null or transient value: model.Event.draggable; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value: model.Event.draggable
This is my MySQL table definition :
CREATE TABLE IF NOT EXISTS `events` (
`Id` int(11) NOT NULL AUTO_INCREMENT,
`Name` varchar(255) DEFAULT NULL,
`StartDate` varchar(50) DEFAULT NULL,
`EndDate` varchar(50) DEFAULT NULL,
`ResourceId` int(11) DEFAULT NULL,
`Resizable` tinyint(1) DEFAULT NULL,
`Draggable` tinyint(1) DEFAULT NULL,
`Cls` varchar(255) DEFAULT NULL,
PRIMARY KEY (`Id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=12 ;
And this is the model code :
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import org.codehaus.jackson.annotate.JsonAutoDetect;
import org.codehaus.jackson.annotate.JsonProperty;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
import org.codehaus.jackson.annotate.JsonIgnore;
#JsonAutoDetect
#JsonIgnoreProperties(ignoreUnknown = true)
#Entity
#Table(name="events")
public class Event {
#Id
#GeneratedValue
#Column(name="Id")
private int id;
#Column(name="Name", nullable=false)
private String name;
#Column(name="StartDate", nullable=false)
private String startDate;
#Column(name="EndDate", nullable=false)
private String endDate;
#Column(name="ResourceId", nullable=false)
private int resourceId;
#Column(name="Resizable")
private Boolean resizable;
#Column(name="Draggable")
private Boolean draggable;
#Column(name="Cls", nullable=false)
private String cls;
#JsonProperty("Id")
public int getId() {
return id;
}
#JsonProperty("Id")
public void setId(int id) {
this.id = id;
}
#JsonProperty("Name")
public String getName() {
return name;
}
#JsonProperty("Name")
public void setName(String name) {
this.name = name;
}
#JsonProperty("StartDate")
public String getStartDate() {
return startDate;
}
#JsonProperty("StartDate")
public void setStartDate(String start) {
this.startDate = start;
}
#JsonProperty("EndDate")
public String getEndDate() {
return endDate;
}
#JsonProperty("EndDate")
public void setEndDate(String end) {
this.endDate = end;
}
#JsonProperty("ResourceId")
public int getResourceId() {
return resourceId;
}
#JsonProperty("ResourceId")
public void setResourceId(int id) {
this.resourceId = id;
}
#JsonProperty("Resizable")
public Boolean getResizable() {
return resizable;
}
#JsonIgnore
public void setResizable(Boolean resizable) {
this.resizable = resizable;
}
#JsonProperty("Draggable")
public Boolean getDraggable() {
return draggable;
}
#JsonIgnore
public void setDraggable(Boolean draggable) {
this.draggable = draggable;
}
#JsonProperty("Cls")
public String getCls() {
return cls;
}
#JsonProperty("Cls")
public void setCls(String cls) {
this.cls = cls;
}
}
Is there anything I can do to prevent this behaviour ?

You are explicitly telling Jackson to ignore the two properties you mentioned, when deserializing your object from its JSON representation. This:
#JsonIgnore
public void setDraggable(Boolean draggable) {
this.draggable = draggable;
}
#JsonIgnore
public void setResizable(Boolean resizable) {
this.resizable = resizable;
}
Basically means, ignore these properties when deserializing from my JSON data. So, consequently when you save your object those properties are null in the database.

You can simply do this:
public boolean getResizable() {
return resizable != null && resizable;
}

Related

OneToOne with Composite Key

Trying to create a one to one on a table with a composite key.
I'm unable to get it to work and getting this error:
Error creating bean with name 'sessionFactory' defined in class path resource [applicationContext-dao.xml]: Invocation of init method failed; nested exception is org.hibernate.MappingException: broken column mapping for: compensation.id of: com.ciwise.model.Focus
Compensation.java:
package com.ciwise.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name = "commissions")
public class Compensation implements Serializable {
private static final long serialVersionUID = 1L;
/**
* Composite key
*/
private CompensationPK compensationPK;
/**
* This year monthly net sales
*/
private double tYMonthlyNetSales;
/**
* Last year monthly net sales
*/
private double lYMonthlyNetSales;
/**
* This year YTD net sales
*/
private double tYYTDNetSales;
private Focus focus;
/**
* Getters and Setters
*/
#OneToOne( mappedBy = "compensation", fetch = FetchType.EAGER)
#JoinColumn(name = "FOCUS_ID")
public Focus getFocus() {
return focus;
}
public void setFocus(Focus focus) {
this.focus = focus;
}
#EmbeddedId
public CompensationPK getCompensationPK() {
return compensationPK;
}
public void setCompensationPK(CompensationPK compensationPK) {
this.compensationPK = compensationPK;
}
#Column(name = "TY_MONTHLY_NET_SALES")
public double gettYMonthlyNetSales() {
return tYMonthlyNetSales;
}
public void settYMonthlyNetSales(double tYMonthlyNetSales) {
this.tYMonthlyNetSales = tYMonthlyNetSales;
}
#Column(name = "LY_MONTHLY_NET_SALES")
public double getlYMonthlyNetSales() {
return lYMonthlyNetSales;
}
public void setlYMonthlyNetSales(double lYMonthlyNetSales) {
this.lYMonthlyNetSales = lYMonthlyNetSales;
}
#Column(name = "TY_YTD_NET_SALES")
public double gettYYTDNetSales() {
return tYYTDNetSales;
}
public void settYYTDNetSales(double tYYTDNetSales) {
this.tYYTDNetSales = tYYTDNetSales;
}
}
CompensationPK.java
package com.ciwise.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
#Embeddable
public class CompensationPK implements Serializable {
private String divisionId;
private String repId;
private int focusId;
private int repTypeId;
private int commissionYear;
private int commissionMonth;
#Column(name = "DIVISION_ID")
public String getDivisionId() {
return divisionId;
}
#Column(name = "REP_ID")
public String getRepId() {
return repId;
}
#Column(name = "FOCUS_ID")
public int getFocusId() {
return focusId;
}
#Column(name = "REPTYPE_ID")
public int getRepTypeId() {
return repTypeId;
}
#Column(name = "COMMISSION_YEAR")
public int getCommissionYear() {
return commissionYear;
}
#Column(name = "COMMISSION_MONTH")
public int getCommissionMonth() {
return commissionMonth;
}
public void setDivisionId(String divisionId) {
this.divisionId = divisionId;
}
public void setRepId(String repId) {
this.repId = repId;
}
public void setFocusId(int focusId) {
this.focusId = focusId;
}
public void setRepTypeId(int repTypeId) {
this.repTypeId = repTypeId;
}
public void setCommissionYear(int commissionYear) {
this.commissionYear = commissionYear;
}
public void setCommissionMonth(int commissionMonth) {
this.commissionMonth = commissionMonth;
}
#Override
public boolean equals(Object o) {
return false;
}
#Override
public int hashCode() {
return 0;
}
}
Focus.java:
package com.ciwise.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "CT_FOCUS")
public class Focus implements Serializable {
private int focusId;
private String focusDesc;
private String focusYN;
private Compensation compensation;
#OneToOne
#PrimaryKeyJoinColumn
public Compensation getCompensation() {
return compensation;
}
public void setCompensation(Compensation compensation) {
this.compensation = compensation;
}
public Focus() {
};
#Id
#Column(name = "FOCUS_ID")
public int getFocusId() {
return focusId;
}
public void setFocusId(int focusId) {
this.focusId = focusId;
}
#Column(name = "FOCUS_DESC", length = 16)
public String getFocusDesc() {
return focusDesc;
}
public void setFocusDesc(String focusDesc) {
this.focusDesc = focusDesc;
}
#Column(name = "FOCUS_YN", length = 1)
public String getFocusYN() {
return focusYN;
}
public void setFocusYN(String focusYN) {
this.focusYN = focusYN;
}
}
Since you used an embeddable type (CompositionPK) as your primary key for Composition entity, you should annotate the corresponding primary key field in your Composition entity with #EmbeddedId.
#EmbeddedId
private CompensationPK compensationPK;
On the Focus entity, you need not specify a #PrimaryKeyJoinColumn on the one-to-one mapping. It will just use the default join column names for the foreign keys.
So this code should be fine without the #PrimaryKeyJoinColumn:
#OneToOne
public Compensation getCompensation() {
return compensation;
}
This is a sample Hibernate generated schema based on your mappings (target DB is MySQL):
Hibernate:
create table CT_FOCUS (
FOCUS_ID integer not null,
FOCUS_DESC varchar(16),
FOCUS_YN varchar(1),
compensation_COMMISSION_MONTH integer,
compensation_COMMISSION_YEAR integer,
compensation_DIVISION_ID varchar(255),
compensation_FOCUS_ID integer,
compensation_REP_ID varchar(255),
compensation_REPTYPE_ID integer,
primary key (FOCUS_ID)
)
Hibernate:
create table commissions (
COMMISSION_MONTH integer not null,
COMMISSION_YEAR integer not null,
DIVISION_ID varchar(255) not null,
FOCUS_ID integer not null,
REP_ID varchar(255) not null,
REPTYPE_ID integer not null,
LY_MONTHLY_NET_SALES double precision,
TY_MONTHLY_NET_SALES double precision,
TY_YTD_NET_SALES double precision,
primary key (COMMISSION_MONTH, COMMISSION_YEAR, DIVISION_ID, FOCUS_ID, REP_ID, REPTYPE_ID)
)
Hibernate:
alter table CT_FOCUS
add constraint FK_d6d2c9n91dlw59uiuqswfueg5
foreign key (compensation_COMMISSION_MONTH, compensation_COMMISSION_YEAR, compensation_DIVISION_ID, compensation_FOCUS_ID, compensation_REP_ID, compensation_REPTYPE_ID)
references commissions (COMMISSION_MONTH, COMMISSION_YEAR, DIVISION_ID, FOCUS_ID, REP_ID, REPTYPE_ID)
#PrimaryKeyJoinColumn can be used on a #OneToOne mapping, if you want the primary keys of Focus entity to be referencing the primary keys of Commission entity. However, you already have defined a primary key for your Focus entity, which the focusId annotated by #Id. So there's no need to specify a #PrimaryKeyJoinColumn.

Hibernate manyToOne mapping with multiple underscores not working

I am trying to create a mapping in Hibernate on an Entity with ManyToOne relationship. I am trying this:
CampaignItemSlot class:
package models;
import java.sql.Timestamp;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
#Entity
#Table(name = "campaign_item_slots")
public class CampaignItemSlot {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
#JoinColumn(name = "advert_slot_id")
#ManyToOne
private AdvertSlot advertSlot;
private boolean active;
private Timestamp date_created;
private Timestamp date_updated;
public CampaignItemSlot() {
super();
// TODO Auto-generated constructor stub
}
}
However I get this in the log file:
Caused by: org.hibernate.HibernateException: Missing column: advertSlot_id in text_advertising.campaign_item_slots
This is my table SQL:
CREATE TABLE IF NOT EXISTS `text_advertising`.`campaign_item_slots` (
`id` BIGINT NOT NULL AUTO_INCREMENT,
`campaign_item_id` BIGINT NOT NULL,
`advert_slot_id` BIGINT NOT NULL,
`active` TINYINT(1) NOT NULL DEFAULT TRUE,
`date_created` DATETIME NOT NULL,
`date_updated` DATETIME NOT NULL,
PRIMARY KEY (`id`),
INDEX `fk_campaignitems_1_idx` (`campaign_item_id` ASC),
INDEX `fk_campaignitems_2_idx` (`advert_slot_id` ASC),
CONSTRAINT `fk_campaign_item_slots_1`
FOREIGN KEY (`campaign_item_id`)
REFERENCES `text_advertising`.`campaignitems` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_campaign_item_slots_2`
FOREIGN KEY (`advert_slot_id`)
REFERENCES `text_advertising`.`advert_slots` (`id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8
COLLATE = utf8_general_ci;
AdvertSlot class:
package models;
import java.sql.Timestamp;
import javax.persistence.Entity;
import javax.persistence.EnumType;
import javax.persistence.Enumerated;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity
#Table(name = "advert_slots")
public class AdvertSlot {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private long id;
#ManyToOne
private Publication publication;
private String name;
private String description;
private boolean active;
private Timestamp date_created;
private Timestamp date_updated;
public AdvertSlot() {
super();
// TODO Auto-generated constructor stub
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public Publication getPublication() {
return publication;
}
public void setPublication(Publication publication) {
this.publication = publication;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public boolean isActive() {
return active;
}
public void setActive(boolean active) {
this.active = active;
}
public Timestamp getDate_created() {
return date_created;
}
public void setDate_created(Timestamp date_created) {
this.date_created = date_created;
}
public Timestamp getDate_updated() {
return date_updated;
}
public void setDate_updated(Timestamp date_updated) {
this.date_updated = date_updated;
}
}
Somehow Hibernate is not seeing my advert_slot_id, help please?
The answer here is to create a custom naming strategy by extending org.hibernate.cfg.DefaultNamingStrategy and then referencing it via hibernate config: hibernate.ejb.naming_strategy
Here is an example:
#Override
public String foreignKeyColumnName(String propertyName, String propertyEntityName, String propertyTableName, String referencedColumnName) {
String changed = CaseFormat.UPPER_CAMEL.to(CaseFormat.LOWER_UNDERSCORE, propertyName) + "_id";
return changed;
}
It will work.Try this way:
First table:
#Table(name = "buyer_city")
public class BuyerCity{
//other fields
.....
#OneToMany(mappedBy="buyerCity", fetch = FetchType.LAZY)
#JsonManagedReference
private Set<BuyerCityMapping> buyerCityMapping = new HashSet<>();
}
Second table:
#Table(name = "buyer_city_mapping")
public class BuyerCityMapping{
//other fields
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JsonBackReference
#JoinColumn(name = "buyer_city_id")
private BuyerCity buyerCity;
}

Unable to build Hibernate SessionFactory, Caused by: org.hibernate.AnnotationException:

I have this issue with my mysql database and the classes generated by hibernate-tools, all was working well until I made a change in the db involving 4 tables.
This are the tables:
--
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=2;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
-- -----------------------------------------------------
-- Table `profile`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fairtime`.`profile` (
`profile_id` INT(11) NOT NULL AUTO_INCREMENT,
`created_at` DATETIME NOT NULL,
`updated_at` DATETIME NULL DEFAULT NULL,
`app_user_id` INT(11) NOT NULL,
`address` VARCHAR(45) NOT NULL,
`phone` VARCHAR(45) NOT NULL,
`city_id` INT(11) NOT NULL,
PRIMARY KEY (`profile_id`),
INDEX `fk_profile_app_user1_idx` (`app_user_id` ASC),
INDEX `fk_profile_city1_idx` (`city_id` ASC),
CONSTRAINT `fk_profile_app_user1`
FOREIGN KEY (`app_user_id`)
REFERENCES `fairtime`.`app_user` (`app_user_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_profile_city1`
FOREIGN KEY (`city_id`)
REFERENCES `fairtime`.`city` (`city_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `profile_option`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fairtime`.`profile_option` (
`profile_option_id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`hidden_for_user` TINYINT(1) NOT NULL DEFAULT '0' COMMENT 'Specify if a target option is readable by Advertiser interface or not',
`hidden_for_advertiser` TINYINT(1) NOT NULL DEFAULT '0' COMMENT 'Specify if a target option is readable by Advertiser interface or not',
`hidden_for_offer` TINYINT(1) NOT NULL DEFAULT '0' COMMENT 'Specify if a target option is readable by Advertiser interface or not',
`type` VARCHAR(45) NULL DEFAULT NULL,
`is_unique_for_profile` TINYINT(1) NULL DEFAULT '0',
`is_unique_for_target` TINYINT(1) NULL DEFAULT '0',
PRIMARY KEY (`profile_option_id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `profile_option_element`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fairtime`.`profile_option_element` (
`profile_option_element_id` INT(11) NOT NULL AUTO_INCREMENT,
`profile_option_id` INT(11) NOT NULL,
`name` VARCHAR(255) NOT NULL,
`hidden_for_user` TINYINT(1) NOT NULL DEFAULT '0' COMMENT 'Specify if a target option is readable by Advertiser interface or not',
`hidden_for_advertiser` TINYINT(1) NOT NULL DEFAULT '0' COMMENT 'Specify if a target option is readable by Advertiser interface or not',
`hidden_for_offer` TINYINT(1) NOT NULL DEFAULT '0' COMMENT 'Specify if a target option is readable by Advertiser interface or not',
`type` VARCHAR(45) NULL DEFAULT NULL,
`app_user_id` INT(11) NULL DEFAULT NULL COMMENT 'When a user creates a brand in their MyFairTime',
`approved` TINYINT(1) NOT NULL DEFAULT '0',
`created_at` DATETIME NULL DEFAULT NULL,
`boolean_value` TINYINT(1) NULL DEFAULT NULL,
PRIMARY KEY (`profile_option_element_id`, `profile_option_id`),
INDEX `fk_target_option_element_target_option1_idx` (`profile_option_id` ASC),
INDEX `fk_profile_option_element_app_user1_idx` (`app_user_id` ASC),
CONSTRAINT `fk_target_option_element_target_option1`
FOREIGN KEY (`profile_option_id`)
REFERENCES `fairtime`.`profile_option` (`profile_option_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_profile_option_element_app_user1`
FOREIGN KEY (`app_user_id`)
REFERENCES `fairtime`.`app_user` (`app_user_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `profile_has_profile_option_element`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fairtime`.`profile_has_profile_option_element` (
`profile_profile_id` INT(11) NOT NULL,
`profile_option_element_profile_option_element_id` INT(11) NOT NULL,
`profile_option_element_profile_option_id` INT(11) NOT NULL,
PRIMARY KEY (`profile_profile_id`, `profile_option_element_profile_option_element_id`, `profile_option_element_profile_option_id`),
INDEX `fk_profile_has_profile_option_element_profile_option_elemen_idx` (`profile_option_element_profile_option_element_id` ASC, `profile_option_element_profile_option_id` ASC),
INDEX `fk_profile_has_profile_option_element_profile1_idx` (`profile_profile_id` ASC),
CONSTRAINT `fk_profile_has_profile_option_element_profile1`
FOREIGN KEY (`profile_profile_id`)
REFERENCES `fairtime`.`profile` (`profile_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_profile_has_profile_option_element_profile_option_element1`
FOREIGN KEY (`profile_option_element_profile_option_element_id` , `profile_option_element_profile_option_id`)
REFERENCES `fairtime`.`profile_option_element` (`profile_option_element_id` , `profile_option_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
--
The schema with workbench is this:
This are the classes involved in hibernate:
Profile.java:
--
package models.classes_hibernate;
// Generated 02/07/2014 10:54:27 by Hibernate Tools 3.6.0
import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import static javax.persistence.GenerationType.IDENTITY;
/**
* Profile generated by hbm2java
*/
#Entity
#Table(name="profile"
,catalog="fairtime"
)
public class Profile implements java.io.Serializable {
private Integer profileId;
private AppUser appUser;
private City city;
private Date createdAt;
private Date updatedAt;
private String address;
private String phone;
private Set<ProfileHasCampaign> profileHasCampaigns = new HashSet<ProfileHasCampaign>(0);
private Set<ProfileOptionElement> profileOptionElements = new HashSet<ProfileOptionElement>(0);
private Set<Offer> offers = new HashSet<Offer>(0);
public Profile() {
}
public Profile(AppUser appUser, City city, Date createdAt, String address, String phone) {
this.appUser = appUser;
this.city = city;
this.createdAt = createdAt;
this.address = address;
this.phone = phone;
}
public Profile(AppUser appUser, City city, Date createdAt, Date updatedAt, String address, String phone, Set<ProfileHasCampaign> profileHasCampaigns, Set<ProfileOptionElement> profileOptionElements, Set<Offer> offers) {
this.appUser = appUser;
this.city = city;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
this.address = address;
this.phone = phone;
this.profileHasCampaigns = profileHasCampaigns;
this.profileOptionElements = profileOptionElements;
this.offers = offers;
}
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="profile_id", unique=true, nullable=false)
public Integer getProfileId() {
return this.profileId;
}
public void setProfileId(Integer profileId) {
this.profileId = profileId;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="app_user_id", nullable=false)
public AppUser getAppUser() {
return this.appUser;
}
public void setAppUser(AppUser appUser) {
this.appUser = appUser;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="city_id", nullable=false)
public City getCity() {
return this.city;
}
public void setCity(City city) {
this.city = city;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name="created_at", nullable=false, length=19)
public Date getCreatedAt() {
return this.createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name="updated_at", length=19)
public Date getUpdatedAt() {
return this.updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
#Column(name="address", nullable=false, length=45)
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
#Column(name="phone", nullable=false, length=45)
public String getPhone() {
return this.phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="profile")
public Set<ProfileHasCampaign> getProfileHasCampaigns() {
return this.profileHasCampaigns;
}
public void setProfileHasCampaigns(Set<ProfileHasCampaign> profileHasCampaigns) {
this.profileHasCampaigns = profileHasCampaigns;
}
#ManyToMany(fetch=FetchType.LAZY)
#JoinTable(name="profile_has_profile_option_element", catalog="fairtime", joinColumns = {
#JoinColumn(name="profile_profile_id", nullable=false, updatable=false) }, inverseJoinColumns = {
#JoinColumn(name="profile_option_element_profile_option_element_id", nullable=false, updatable=false) })
public Set<ProfileOptionElement> getProfileOptionElements() {
return this.profileOptionElements;
}
public void setProfileOptionElements(Set<ProfileOptionElement> profileOptionElements) {
this.profileOptionElements = profileOptionElements;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="profile")
public Set<Offer> getOffers() {
return this.offers;
}
public void setOffers(Set<Offer> offers) {
this.offers = offers;
}
}
--
ProfileOptionElement.java:
--
package models.classes_hibernate;
// Generated 02/07/2014 10:54:27 by Hibernate Tools 3.6.0
import javax.persistence.*;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
/**
* ProfileOptionElement generated by hbm2java
*/
#Entity
#Table(name="profile_option_element"
,catalog="fairtime"
)
public class ProfileOptionElement implements java.io.Serializable {
private ProfileOptionElementId id;
private AppUser appUser;
private ProfileOption profileOption;
private String name;
private boolean hiddenForUser;
private boolean hiddenForAdvertiser;
private boolean hiddenForOffer;
private String type;
private boolean approved;
private Date createdAt;
private Boolean booleanValue;
private Set<Profile> profiles = new HashSet<Profile>(0);
private Set<TargetHasProfileOptionElement> targetHasProfileOptionElements = new HashSet<TargetHasProfileOptionElement>(0);
public ProfileOptionElement() {
}
public ProfileOptionElement(ProfileOptionElementId id, ProfileOption profileOption, String name, boolean hiddenForUser, boolean hiddenForAdvertiser, boolean hiddenForOffer, boolean approved) {
this.id = id;
this.profileOption = profileOption;
this.name = name;
this.hiddenForUser = hiddenForUser;
this.hiddenForAdvertiser = hiddenForAdvertiser;
this.hiddenForOffer = hiddenForOffer;
this.approved = approved;
}
public ProfileOptionElement(ProfileOptionElementId id, AppUser appUser, ProfileOption profileOption, String name, boolean hiddenForUser, boolean hiddenForAdvertiser, boolean hiddenForOffer, String type, boolean approved, Date createdAt, Boolean booleanValue, Set<Profile> profiles, Set<TargetHasProfileOptionElement> targetHasProfileOptionElements) {
this.id = id;
this.appUser = appUser;
this.profileOption = profileOption;
this.name = name;
this.hiddenForUser = hiddenForUser;
this.hiddenForAdvertiser = hiddenForAdvertiser;
this.hiddenForOffer = hiddenForOffer;
this.type = type;
this.approved = approved;
this.createdAt = createdAt;
this.booleanValue = booleanValue;
this.profiles = profiles;
this.targetHasProfileOptionElements = targetHasProfileOptionElements;
}
#EmbeddedId
#AttributeOverrides( {
#AttributeOverride(name="profileOptionElementId", column=#Column(name="profile_option_element_id", nullable=false) ),
#AttributeOverride(name="profileOptionId", column=#Column(name="profile_option_id", nullable=false) ) } )
public ProfileOptionElementId getId() {
return this.id;
}
public void setId(ProfileOptionElementId id) {
this.id = id;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="app_user_id")
public AppUser getAppUser() {
return this.appUser;
}
public void setAppUser(AppUser appUser) {
this.appUser = appUser;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="profile_option_id", nullable=false, insertable=false, updatable=false)
public ProfileOption getProfileOption() {
return this.profileOption;
}
public void setProfileOption(ProfileOption profileOption) {
this.profileOption = profileOption;
}
#Column(name="name", nullable=false)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="hidden_for_user", nullable=false)
public boolean isHiddenForUser() {
return this.hiddenForUser;
}
public void setHiddenForUser(boolean hiddenForUser) {
this.hiddenForUser = hiddenForUser;
}
#Column(name="hidden_for_advertiser", nullable=false)
public boolean isHiddenForAdvertiser() {
return this.hiddenForAdvertiser;
}
public void setHiddenForAdvertiser(boolean hiddenForAdvertiser) {
this.hiddenForAdvertiser = hiddenForAdvertiser;
}
#Column(name="hidden_for_offer", nullable=false)
public boolean isHiddenForOffer() {
return this.hiddenForOffer;
}
public void setHiddenForOffer(boolean hiddenForOffer) {
this.hiddenForOffer = hiddenForOffer;
}
#Column(name="type", length=45)
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
#Column(name="approved", nullable=false)
public boolean isApproved() {
return this.approved;
}
public void setApproved(boolean approved) {
this.approved = approved;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name="created_at", length=19)
public Date getCreatedAt() {
return this.createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
#Column(name="boolean_value")
public Boolean getBooleanValue() {
return this.booleanValue;
}
public void setBooleanValue(Boolean booleanValue) {
this.booleanValue = booleanValue;
}
#ManyToMany(fetch=FetchType.LAZY)
#JoinTable(name="profile_has_profile_option_element", catalog="fairtime", joinColumns = {
#JoinColumn(name="profile_option_element_profile_option_element_id", nullable=false, updatable=false),
#JoinColumn(name="profile_option_element_profile_option_id", nullable=false, updatable=false) }, inverseJoinColumns = {
#JoinColumn(name="profile_profile_id", nullable=false, updatable=false) })
public Set<Profile> getProfiles() {
return this.profiles;
}
public void setProfiles(Set<Profile> profiles) {
this.profiles = profiles;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="profileOptionElement")
public Set<TargetHasProfileOptionElement> getTargetHasProfileOptionElements() {
return this.targetHasProfileOptionElements;
}
public void setTargetHasProfileOptionElements(Set<TargetHasProfileOptionElement> targetHasProfileOptionElements) {
this.targetHasProfileOptionElements = targetHasProfileOptionElements;
}
}
--
ProfileOption.java:
--
package models.classes_hibernate;
// Generated 02/07/2014 10:54:27 by Hibernate Tools 3.6.0
import javax.persistence.*;
import java.util.HashSet;
import java.util.Set;
import static javax.persistence.GenerationType.IDENTITY;
/**
* ProfileOption generated by hbm2java
*/
#Entity
#Table(name="profile_option"
,catalog="fairtime"
)
public class ProfileOption implements java.io.Serializable {
private Integer profileOptionId;
private String name;
private boolean hiddenForUser;
private boolean hiddenForAdvertiser;
private boolean hiddenForOffer;
private String type;
private Boolean isUniqueForProfile;
private Boolean isUniqueForTarget;
private Set<Offer> offers = new HashSet<Offer>(0);
private Set<ProfileOptionElement> profileOptionElements = new HashSet<ProfileOptionElement>(0);
public ProfileOption() {
}
public ProfileOption(String name, boolean hiddenForUser, boolean hiddenForAdvertiser, boolean hiddenForOffer) {
this.name = name;
this.hiddenForUser = hiddenForUser;
this.hiddenForAdvertiser = hiddenForAdvertiser;
this.hiddenForOffer = hiddenForOffer;
}
public ProfileOption(String name, boolean hiddenForUser, boolean hiddenForAdvertiser, boolean hiddenForOffer, String type, Boolean isUniqueForProfile, Boolean isUniqueForTarget, Set<Offer> offers, Set<ProfileOptionElement> profileOptionElements) {
this.name = name;
this.hiddenForUser = hiddenForUser;
this.hiddenForAdvertiser = hiddenForAdvertiser;
this.hiddenForOffer = hiddenForOffer;
this.type = type;
this.isUniqueForProfile = isUniqueForProfile;
this.isUniqueForTarget = isUniqueForTarget;
this.offers = offers;
this.profileOptionElements = profileOptionElements;
}
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="profile_option_id", unique=true, nullable=false)
public Integer getProfileOptionId() {
return this.profileOptionId;
}
public void setProfileOptionId(Integer profileOptionId) {
this.profileOptionId = profileOptionId;
}
#Column(name="name", nullable=false)
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="hidden_for_user", nullable=false)
public boolean isHiddenForUser() {
return this.hiddenForUser;
}
public void setHiddenForUser(boolean hiddenForUser) {
this.hiddenForUser = hiddenForUser;
}
#Column(name="hidden_for_advertiser", nullable=false)
public boolean isHiddenForAdvertiser() {
return this.hiddenForAdvertiser;
}
public void setHiddenForAdvertiser(boolean hiddenForAdvertiser) {
this.hiddenForAdvertiser = hiddenForAdvertiser;
}
#Column(name="hidden_for_offer", nullable=false)
public boolean isHiddenForOffer() {
return this.hiddenForOffer;
}
public void setHiddenForOffer(boolean hiddenForOffer) {
this.hiddenForOffer = hiddenForOffer;
}
#Column(name="type", length=45)
public String getType() {
return this.type;
}
public void setType(String type) {
this.type = type;
}
#Column(name="is_unique_for_profile")
public Boolean getIsUniqueForProfile() {
return this.isUniqueForProfile;
}
public void setIsUniqueForProfile(Boolean isUniqueForProfile) {
this.isUniqueForProfile = isUniqueForProfile;
}
#Column(name="is_unique_for_target")
public Boolean getIsUniqueForTarget() {
return this.isUniqueForTarget;
}
public void setIsUniqueForTarget(Boolean isUniqueForTarget) {
this.isUniqueForTarget = isUniqueForTarget;
}
#ManyToMany(fetch=FetchType.LAZY)
#JoinTable(name="offer_has_profile_option", catalog="fairtime", joinColumns = {
#JoinColumn(name="profile_option_profile_option_id", nullable=false, updatable=false) }, inverseJoinColumns = {
#JoinColumn(name="offer_offer_id", nullable=false, updatable=false) })
public Set<Offer> getOffers() {
return this.offers;
}
public void setOffers(Set<Offer> offers) {
this.offers = offers;
}
#OneToMany(fetch=FetchType.LAZY, mappedBy="profileOption")
public Set<ProfileOptionElement> getProfileOptionElements() {
return this.profileOptionElements;
}
public void setProfileOptionElements(Set<ProfileOptionElement> profileOptionElements) {
this.profileOptionElements = profileOptionElements;
}
}
--
When I tried to use hibernate I get the following exception:
Unexpected exception[PersistenceException: [PersistenceUnit: fairtimePersistenceUnit] Unable to build Hibernate SessionFactory]
Caused by: org.hibernate.AnnotationException: A Foreign key refering models.classes_hibernate.ProfileOptionElement from models.classes_hibernate.Profile has the wrong number of column. should be 2
I cannot find the problem, thanks in advance for your help
The relational table profile_has_profile_option_element has more than one foreign key referencing the profile option element, this results in the generated class having references to this table's entries instead of referring to items in profile in a many to many manner which is what I think you want. To remove the extra foreign key field, change the relation between profile_option and profile_option_element to non identifying and then recreate the many to many relationship to profile
SET #OLD_UNIQUE_CHECKS=##UNIQUE_CHECKS, UNIQUE_CHECKS=0;
SET #OLD_FOREIGN_KEY_CHECKS=##FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;
SET #OLD_SQL_MODE=##SQL_MODE, SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';
CREATE SCHEMA IF NOT EXISTS `fairtime` ;
USE `fairtime` ;
-- -----------------------------------------------------
-- Table `fairtime`.`profile`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fairtime`.`profile` (
`profile_id` INT(11) NOT NULL AUTO_INCREMENT,
`created_at` DATETIME NOT NULL,
`updated_at` DATETIME NULL DEFAULT NULL,
`app_user_id` INT(11) NOT NULL,
`address` VARCHAR(45) NOT NULL,
`phone` VARCHAR(45) NOT NULL,
`city_id` INT(11) NOT NULL,
PRIMARY KEY (`profile_id`),
INDEX `fk_profile_app_user1_idx` (`app_user_id` ASC),
INDEX `fk_profile_city1_idx` (`city_id` ASC),
CONSTRAINT `fk_profile_app_user1`
FOREIGN KEY (`app_user_id`)
REFERENCES `fairtime`.`app_user` (`app_user_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_profile_city1`
FOREIGN KEY (`city_id`)
REFERENCES `fairtime`.`city` (`city_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `fairtime`.`profile_option`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fairtime`.`profile_option` (
`profile_option_id` INT(11) NOT NULL AUTO_INCREMENT,
`name` VARCHAR(255) NOT NULL,
`hidden_for_user` TINYINT(1) NOT NULL DEFAULT '0' COMMENT 'Specify if a target option is readable by Advertiser interface or not',
`hidden_for_advertiser` TINYINT(1) NOT NULL DEFAULT '0' COMMENT 'Specify if a target option is readable by Advertiser interface or not',
`hidden_for_offer` TINYINT(1) NOT NULL DEFAULT '0' COMMENT 'Specify if a target option is readable by Advertiser interface or not',
`type` VARCHAR(45) NULL DEFAULT NULL,
`is_unique_for_profile` TINYINT(1) NULL DEFAULT '0',
`is_unique_for_target` TINYINT(1) NULL DEFAULT '0',
PRIMARY KEY (`profile_option_id`))
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
-- -----------------------------------------------------
-- Table `fairtime`.`profile_option_element`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fairtime`.`profile_option_element` (
`profile_option_element_id` INT(11) NOT NULL AUTO_INCREMENT,
`profile_option_id` INT(11) NOT NULL,
`name` VARCHAR(255) NOT NULL,
`hidden_for_user` TINYINT(1) NOT NULL DEFAULT '0' COMMENT 'Specify if a target option is readable by Advertiser interface or not',
`hidden_for_advertiser` TINYINT(1) NOT NULL DEFAULT '0' COMMENT 'Specify if a target option is readable by Advertiser interface or not',
`hidden_for_offer` TINYINT(1) NOT NULL DEFAULT '0' COMMENT 'Specify if a target option is readable by Advertiser interface or not',
`type` VARCHAR(45) NULL,
`app_user_id` INT(11) NULL DEFAULT NULL COMMENT 'When a user creates a brand in their MyFairTime',
`approved` TINYINT(1) NOT NULL DEFAULT '0',
`created_at` DATETIME NULL,
`boolean_value` TINYINT(1) NULL DEFAULT NULL,
PRIMARY KEY (`profile_option_element_id`),
INDEX `fk_profile_option_element_app_user1_idx` (`app_user_id` ASC),
INDEX `fk_profile_option_element_profile_option1_idx` (`profile_option_id` ASC),
CONSTRAINT `fk_profile_option_element_app_user1`
FOREIGN KEY (`app_user_id`)
REFERENCES `fairtime`.`app_user` (`app_user_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_profile_option_element_profile_option1`
FOREIGN KEY (`profile_option_id`)
REFERENCES `fairtime`.`profile_option` (`profile_option_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB;
-- -----------------------------------------------------
-- Table `fairtime`.`profile_has_profile_option_element`
-- -----------------------------------------------------
CREATE TABLE IF NOT EXISTS `fairtime`.`profile_has_profile_option_element` (
`profile_profile_id` INT(11) NOT NULL,
`profile_option_element_profile_option_element_id` INT(11) NOT NULL,
PRIMARY KEY (`profile_profile_id`, `profile_option_element_profile_option_element_id`),
INDEX `fk_profile_has_profile_option_element_profile_option_elemen_idx` (`profile_option_element_profile_option_element_id` ASC),
INDEX `fk_profile_has_profile_option_element_profile1_idx` (`profile_profile_id` ASC),
CONSTRAINT `fk_profile_has_profile_option_element_profile1`
FOREIGN KEY (`profile_profile_id`)
REFERENCES `fairtime`.`profile` (`profile_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION,
CONSTRAINT `fk_profile_has_profile_option_element_profile_option_element1`
FOREIGN KEY (`profile_option_element_profile_option_element_id`)
REFERENCES `fairtime`.`profile_option_element` (`profile_option_element_id`)
ON DELETE NO ACTION
ON UPDATE NO ACTION)
ENGINE = InnoDB
DEFAULT CHARACTER SET = utf8;
SET SQL_MODE=#OLD_SQL_MODE;
SET FOREIGN_KEY_CHECKS=#OLD_FOREIGN_KEY_CHECKS;
SET UNIQUE_CHECKS=#OLD_UNIQUE_CHECKS;
Unfortunately I don't have enough rep to post an image

JPA find() does not load Entity #Id

I'm starting to use JPA with the OpenJPA API, and i'm having a problem with the find().
Here are the tables:
CREATE TABLE compania (
ID int(11) NOT NULL,
NOMBRE varchar(45) DEFAULT NULL,
PRIMARY KEY (ID)
)
CREATE TABLE modelo (
ID int(11) NOT NULL,
ID_COMPANIA int(11) DEFAULT NULL,
NOMBRE_MODELO varchar(45) DEFAULT NULL,
PRIMARY KEY (ID),
KEY MODELO_COMPANIA_FK_idx (ID_COMPANIA),
CONSTRAINT MODELO_COMPANIA_FK FOREIGN KEY (ID_COMPANIA) REFERENCES compania (ID)
)
and here are my Entities:
#Entity
public class Compania extends EntityJPA{
private static final long serialVersionUID = 1L;
#Id
private int id;
#Column
private String nombre;
#OneToMany(mappedBy="compania",cascade={CascadeType.ALL})
#JoinColumn(name="ID_COMPANIA", nullable=false)
private List<Modelo> listaModelos;
public Compania() {
}
public int getId() {
return id;
}
public void setId(int idCompania) {
this.id = idCompania;
}
public String getNombre() {
return nombre;
}
public void setNombre(String nombreCompania) {
this.nombre = nombreCompania;
}
public List<Modelo> getListaModelos() {
return listaModelos;
}
public void setListaModelos(List<Modelo> listaModelos) {
this.listaModelos = listaModelos;
}
}
#Entity
public class Modelo extends EntityJPA{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name="NOMBRE_MODELO")
private String nombreModelo;
#ManyToOne
#JoinColumn(name="ID_COMPANIA", referencedColumnName="ID")
private Compania compania;
public Modelo() {
}
public Compania getCompania() {
return compania;
}
public void setCompania(Compania compania) {
this.compania = compania;
}
public int getId() {
return id;
}
public void setId(int idModelo) {
this.id = idModelo;
}
public String getNombre() {
return nombreModelo;
}
public void setNombre(String nombreModelo) {
this.nombreModelo = nombreModelo;
}
}
At the moment I make the
Compania cia = getEntityManager().find(Compania.class, idCompania);
the cia object does not have the value of the #Id attribute, it has the value of nombre but not of id. I mean:
cia.getId() = 0
and it must be 1 or 2 , etc. Not 0.
Thank you very much for your help.
I do not have the code to persist because It was already persisted.
the code for the find is
public static Compania findCompania(int idCompania){
try {
Compania cia = getEntityManager().find(Compania.class, idCompania);
return cia;
} finally {
closeEntityManager();
}
}
And if I activate the log, this is the select it shows:
482 testMySql TRACE [http-bio-8080-exec-5] openjpa.jdbc.SQL - <t 1228180882, conn 1699837157> executing prepstmnt 2127861376 SELECT t0.nombre FROM Compania t0 WHERE t0.id = ? [params=(int) 1]
497 testMySql TRACE [http-bio-8080-exec-5] openjpa.jdbc.SQL - <t 1228180882, conn 1699837157> [15 ms] spent
As you can see, there is no t0.id in the select.
Thanks for your help.
Primary Key (ID) not retrieved (?) from database using OpenJPA
Duplicate.... the net of the post is that you need to use a different enhancement method.
If you don't specifically set the value for the #Id attribute you have to declare it with #GeneratedValueso that it's automatically incremented.

Hibernate: Transfer seeming n:n mapping in Database to #OneToMany in Hibernate with additional condition

I have a Database with a Mapping between applications and application_descriptions. Every application could have more than one description (mapped by column product_id). Column product_id in table applications can have duplicate values, but combinations of column product_id and column wrapping_version are unique. So the descriptions should only map to the application with highest version.
I have worked out a #OneToMany mapping in table application to get all descriptions. In descriptions I only get the String of product_id. That’s not optimal, but it doesn’t work to map it like in alternative a).
So the solution I have made worked fine for reading data from database, but when I try to update an application to database I get (only sometimes) following error:
Hibernate:
/* update
com.twistbox.iwp.dao.Application */ update
applications
set
created=?,
design_id=?,
message=?,
product_id=?,
product_title=?,
retailer_id=?,
state=?,
tbyb_playduration=?,
tbyb_startups=?,
wrapping_security_layer=?,
wrapping_version=?
where
id=?
Hibernate:
/* delete one-to-many com.twistbox.iwp.dao.Application.applicationDescriptions */ update
application_descriptions
set
product_id=null
where
product_id=?
104330 [http-8080-1] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1048, SQLState: 23000
104330 [http-8080-1] ERROR org.hibernate.util.JDBCExceptionReporter - Column 'product_id' cannot be null
I have tried
1. to set the mapped description set to null before updating
2. set to a new empty HashSet Object before updating
3. let the mapped object like I get it from database
On default hibernate shouldn’t cascade on update and I haven’t found a way to stop doing it (last try was #OneToMany(cascade = {})). I have also tried in both tables true and false values for:
1. attribute null-able
2. updateable
3. insertable
Some of them worked for the application I got the error, but then I get same error for other applications witch only works if I remove the attributes again. Any ideas what to do?
My code (only important getter and setter, all other removed for better overview):
#Entity
#Table (name = "applications")
#FilterDef(name = "versionFilter")
public class Application implements Comparable<Application>, Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private long id;
private Retailer retailerId;
private long designId;
private String productId;
private String productTitle;
private int tbybPlayDuration;
private int tbybStartups;
private int wrappingSecurityLayer;
private int wrappingVersion;
private ApplicationStatus status;
private String message;
private Timestamp created;
private Set<ApplicationDescription> applicationDescriptions = new HashSet<ApplicationDescription>();
private Set<PricingApplicationMapping> pricingApplication = new HashSet<PricingApplicationMapping>();
public Application() {
}
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#GenericGenerator(name="increment", strategy="increment")
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
#Column(name="product_id")
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
#OneToMany(cascade = {})
#JoinColumn(name="product_id", referencedColumnName="product_id")
#Filter(name = "versionFilter", condition = "wrapping_version =select max(A.wrapping_version) from application A where A.product_id= product_id")
public Set<ApplicationDescription> getApplicationDescriptions() {
return applicationDescriptions;
}
public void setApplicationDescriptions(
Set<ApplicationDescription> applicationDescriptions) {
this.applicationDescriptions = applicationDescriptions;
}
#Override
public int compareTo(Application o) {
return this.getProductTitle().compareToIgnoreCase(o.getProductTitle());
}
}
#Entity
#Table (name = "application_descriptions")
#FilterDef(name = "paMapping")
public class ApplicationDescription implements Comparable<ApplicationDescription>, Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private long id;
private String productId;
// private Application application;
// private String countryCode;
private Territory territory;
private String name;
private String description;
private String termsAndConditions;
public ApplicationDescription() {
}
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#GenericGenerator(name="increment", strategy="increment")
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
// #ManyToOne
// #JoinColumn(name="product_id")
// public Application getApplication() {
// return application;
// }
//
// public void setApplication(Application application) {
// this.application = application;
// }
#Column(name="product_id")
public String getProductId() {
return productId;
}
public void setProductId(String productId) {
this.productId = productId;
}
#Column(name="name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Column(name="description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name="terms_and_conditions")
public String getTermsAndConditions() {
if (this.termsAndConditions != null && !this.termsAndConditions.equals("") && !this.termsAndConditions.toLowerCase().equals("null"))
return this.termsAndConditions;
return "default";
}
public void setTermsAndConditions(String termsAndConditions) {
this.termsAndConditions = termsAndConditions;
}
#JoinColumn(name="country_code")
#OneToOne
public Territory getTerritory() {
return territory;
}
public void setTerritory(Territory territory) {
this.territory = territory;
}
#Override
public int compareTo(ApplicationDescription o) {
return this.getTerritory().getCountryCode().compareToIgnoreCase(o.getTerritory().getCountryCode());
}
}
Alternative for product_id in application_descriptions a):
#ManyToOne
#JoinColumn(name="product_id")
public Application getApplication() {
return application;
}
Error Message:
Hibernate:
/* load one-to-many com.twistbox.iwp.dao.Application.applicationDescriptions */ select
applicatio0_.product_id as product5_0_2_,
applicatio0_.id as id2_,
applicatio0_.id as id4_1_,
applicatio0_.product_id as product5_4_1_,
applicatio0_.description as descript2_4_1_,
applicatio0_.name as name4_1_,
applicatio0_.terms_and_conditions as terms4_4_1_,
applicatio0_.country_code as country6_4_1_,
territory1_.country_code as country1_8_0_,
territory1_.currency as currency8_0_,
territory1_.name as name8_0_,
territory1_.terms_and_conditions as terms4_8_0_
from
application_descriptions applicatio0_
left outer join
territories territory1_
on applicatio0_.country_code=territory1_.country_code
where
applicatio0_.product_id=?
180684 [http-8080-1] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 0, SQLState: S1009
180684 [http-8080-1] ERROR org.hibernate.util.JDBCExceptionReporter - Invalid value for getLong() - 'para'
SQL generating tables:
CREATE TABLE IF NOT EXISTS `applications` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT,
`retailer_id` int(10) unsigned NOT NULL,
`design_id` int(10) unsigned NOT NULL,
`product_id` varchar(150) NOT NULL,
`product_title` varchar(150) NOT NULL,
`tbyb_playduration` int(10) NOT NULL,
`tbyb_startups` int(10) NOT NULL,
`wrapping_security_layer` int(10) unsigned NOT NULL DEFAULT '1',
`wrapping_version` int(10) unsigned NOT NULL DEFAULT '1',
`state` enum('WAITING','RUNNING','DONE','FAILED') NOT NULL DEFAULT 'WAITING',
`message` varchar(250) DEFAULT NULL,
`created` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `product_id_wrapping_version` (`product_id`,`wrapping_version`),
KEY `FK_applications_retailers` (`retailer_id`),
KEY `FK_applications_custom_designs` (`design_id`),
KEY `product_id` (`product_id`),
CONSTRAINT `FK_applications_custom_designs` FOREIGN KEY (`design_id`) REFERENCES `custom_designs` (`id`),
CONSTRAINT `FK_applications_retailers` FOREIGN KEY (`retailer_id`) REFERENCES `retailers` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
CREATE TABLE IF NOT EXISTS `application_descriptions` (
`id` int(10) NOT NULL AUTO_INCREMENT,
`product_id` varchar(150) NOT NULL,
`country_code` varchar(5) NOT NULL,
`name` varchar(150) NOT NULL,
`description` varchar(500) NOT NULL,
`terms_and_conditions` text,
PRIMARY KEY (`id`),
UNIQUE KEY `product_id_county_code` (`product_id`,`country_code`),
KEY `FK_application_descriptions_applications` (`product_id`),
KEY `FK_application_descriptions_territories` (`country_code`),
CONSTRAINT `FK_application_descriptions_territories` FOREIGN KEY (`country_code`) REFERENCES `territories` (`country_code`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Application update:
public static long updateApplication(Application application){
SessionFactory sf = HibernateUtil.getSessionFactory();
Session session = null;
try{
session = sf.openSession();
session.beginTransaction();
session.saveOrUpdate(application);
session.getTransaction().commit();
}
catch(HibernateException he){
logger.severe("Error updating application! " + he.getMessage() + " " + he.getStackTrace());
return -1;
}
catch(Exception e){
logger.severe("Error updating application! " + e.getMessage() + " " + e.getStackTrace());
return -1;
}
finally{
session.close();
}
return application.getId();
}

Categories

Resources