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
Related
getting id = null when I try to insert data in table here is my create table syntax
CREATE TABLE query_builder (
id int(11) NOT NULL AUTO_INCREMENT,
query_title varchar(150) NOT NULL,
sql_query text NOT NULL,
condition varchar(50) NOT NULL,
output_fields varchar(45) NOT NULL,
physician int(11) NOT NULL,
creation_time timestamp NULL DEFAULT CURRENT_TIMESTAMP,
modification_time timestamp NULL DEFAULT NULL,
discription text NOT NULL,
PRIMARY KEY (id),
KEY query_builder_physician_FK_idx (physician),
CONSTRAINT query_builder_physician_FK FOREIGN KEY (physician) REFERENCES physician (Physician_Id) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
and entity for this is
import java.io.Serializable;
import javax.xml.bind.annotation.XmlTransient;
public class QueryBuilder implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, unique = true)
private Integer id;
#Basic(optional = false)
#Column(name = "query_title")
private String queryTitle;
#Basic(optional = false)
#Lob
#Column(name = "sql_query")
private String sqlQuery;
#Basic(optional = false)
#Column(name = "condition")
private String condition;
#Basic(optional = false)
#Column(name = "output_fields")
private String outputFields;
#Column(name = "creation_time")
#Temporal(TemporalType.TIMESTAMP)
private Date creationTime;
#Column(name = "modification_time")
#Temporal(TemporalType.TIMESTAMP)
private Date modificationTime;
#Basic(optional = false)
#Lob
#Column(name = "discription")
private String discription;
#JoinColumn(name = "physician", referencedColumnName = "Physician_Id")
#ManyToOne(optional = false)
private Physician physician;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name= "querybuilderId")
private Collection<QueryBuilderCondition> queryBuilderConditionCollection;
public QueryBuilder() {
}
public QueryBuilder(Integer id) {
this.id = id;
}
public QueryBuilder(Integer id, String queryTitle, String sqlQuery, String condition, String outputFields, String discription) {
this.id = id;
this.queryTitle = queryTitle;
this.sqlQuery = sqlQuery;
this.condition = condition;
this.outputFields = outputFields;
this.discription = discription;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getQueryTitle() {
return queryTitle;
}
public void setQueryTitle(String queryTitle) {
this.queryTitle = queryTitle;
}
public String getSqlQuery() {
return sqlQuery;
}
public void setSqlQuery(String sqlQuery) {
this.sqlQuery = sqlQuery;
}
public String getCondition() {
return condition;
}
public void setCondition(String condition) {
this.condition = condition;
}
public String getOutputFields() {
return outputFields;
}
public void setOutputFields(String outputFields) {
this.outputFields = outputFields;
}
public Date getCreationTime() {
return creationTime;
}
public void setCreationTime(Date creationTime) {
this.creationTime = creationTime;
}
public Date getModificationTime() {
return modificationTime;
}
public void setModificationTime(Date modificationTime) {
this.modificationTime = modificationTime;
}
public String getDiscription() {
return discription;
}
public void setDiscription(String discription) {
this.discription = discription;
}
public Physician getPhysician() {
return physician;
}
public void setPhysician(Physician physician) {
this.physician = physician;
}
#XmlTransient
public Collection<QueryBuilderCondition> getQueryBuilderConditionCollection() {
return queryBuilderConditionCollection;
}
public void setQueryBuilderConditionCollection(Collection<QueryBuilderCondition> queryBuilderConditionCollection) {
this.queryBuilderConditionCollection = queryBuilderConditionCollection;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof QueryBuilder)) {
return false;
}
QueryBuilder other = (QueryBuilder) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "com.medikm.entity.QueryBuilder[ id=" + id + " ]";
}
}
to store data in table i uset below code
builder.setCondition(condition);
builder.setCreationTime(new Date());
builder.setDiscription(discription);
builder.setOutputFields(fields);
builder.setPhysician(new PhysicianJpaController().findPhysician(physicianId));
builder.setQueryTitle(title);
builder.setSqlQuery(query);
em.persist(builder);
em.getTransaction().commit();
em.close();
but above code give me an error
this is the error that i got when i try to persist
[EL Warning]: 2016-06-29 14:22:03.749--UnitOfWork(900737)--Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.2.v20100323-r6872): org.eclipse.persistence.exceptions.DatabaseExceptionInternal Exception: om.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'condition, output_fields, discription, creation_time, modification_time, physici' at line 1Error Code: 1064
Call: INSERT INTO query_builder (query_title, sql_query, condition,output_fields, discription, creation_time, modification_time, physician) VALUES (?, ?, ?, ?, ?, ?, ?, ?) bind => [adfdfafad, SELECT c.Case_Id, c.Age FROM case1 c, patient p, episode e, personal_medical_history pmh, reproductive_history rh WHERE( c.Disease_type = 2 AND c.Primary_Diagnosis_Dt <> '2016/06/22' OR c.Clinical_Stage = 'I'
) AND c.Patient_Id = p.Patient_Id AND e.Case_Id = c.Case_Id
AND pmh.Patient_Id = p.Patient_Id AND rh.Patient_Id = p.Patient_Id
GROUP BY c.Case_Id , "OR", ["ca.Age","ca.aortic_node_positive"], adffda, 2016-06-29 14:22:03.724, null, 200]Query: InsertObjectQuery(com.medikm.entity.QueryBuilder[ id=null ])javax.persistence.RollbackException: Exception [EclipseLink-4002] (Eclipse Persistence Services - 2.0.2.v20100323-r6872):org.eclipse.persistence.exceptions.DatabaseException
Internal Exception: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'condition, output_fields, discription, creation_time, modification_time, physici' at line 1
Error Code: 1064Call: INSERT INTO query_builder (query_title, sql_query, condition, output_fields, discription, creation_time, modification_time, physician) VALUES (?, ?, ?, ?, ?, ?, ?, ?) bind => [adfdfafad, SELECT c.Case_Id, c.Age FROM case1 c, patient p, episode e, personal_medical_history pmh, reproductive_history rhWHERE( c.Disease_type = 2 AND c.Primary_Diagnosis_Dt <> '2016/06/22' OR c.Clinical_Stage = 'I' ) AND c.Patient_Id = p.Patient_Id
AND e.Case_Id = c.Case_Id AND pmh.Patient_Id = p.Patient_Id
AND rh.Patient_Id = p.Patient_Id GROUP BY c.Case_Id , "OR", ["ca.Age","ca.aortic_node_positive"], adffda, 2016-06-29 14:22:03.724, null, 200]Query: InsertObjectQuery(com.medikm.entity.QueryBuilder[ id=null ])at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commitInternal(EntityTransactionImpl.java:102)at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:63)
please let me know if anything wrong done by me please help... Thank you
Identity sequencing uses special IDENTITY columns in the database to allow the database to automatically assign an id to the object when its row is inserted. Identity columns are supported in many databases, such as MySQL, DB2, SQL Server, Sybase and Postgres. Oracle does not support IDENTITY columns but they can be simulated through using sequence objects and triggers.
If you are using Oracle, that might be the reason.
You can change this code
#GeneratedValue(strategy = GenerationType.IDENTITY)
To this
#GeneratedValue(strategy = GenerationType.SEQUENCE)
PhysicianJpaController() might not find a physician with "physicianId",so you might be trying to do this:
builder.setPhysician(null);
while you have also this:
physician int(11) NOT NULL
hey guys thank you so much for your help issue that I found is in my entity as I check I found that condition is reserved keyword in mysql and because of this I got this error
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;
}
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.
Hi I am trying to do one to many insert but I am having problems.
I have two tables:
CREATE TABLE users_app (
user_id int UNSIGNED NOT NULL AUTO_INCREMENT,
user_number varchar(45) NOT NULL default '0',
user_password varchar(45) NOT NULL default '0',
os int(1) unsigned NOT NULL,
token varchar(500) NOT NULL,
PRIMARY KEY (`user_id`)
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8;
CREATE TABLE user_app_devices(
id int AUTO_INCREMENT PRIMARY KEY,
user_id int UNSIGNED NOT NULL,
device_name varchar(45) NOT NULL,
FOREIGN KEY (user_id) REFERENCES users_app (user_id)
)ENGINE=InnoDB CHARSET=utf8;
My classes:
#Entity
#Table(name="user_app_devices")
public class UserAppDevice implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private int id;
#Column(name="device_name")
private String deviceName;
//bi-directional many-to-one association to UsersApp
#ManyToOne
#JoinColumn(name="user_id")
private UsersApp usersApp;
public UserAppDevice() {
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getDeviceName() {
return this.deviceName;
}
public void setDeviceName(String deviceName) {
this.deviceName = deviceName;
}
public UsersApp getUsersApp() {
return this.usersApp;
}
public void setUsersApp(UsersApp usersApp) {
this.usersApp = usersApp;
}
}
#Entity
#Table(name="users_app")
public class UsersApp implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="user_id")
private int userId;
private int os;
private String token;
#Column(name="user_number")
private String userNumber;
#Column(name="user_password")
private String userPassword;
//bi-directional many-to-one association to UserAppDevice
#OneToMany(mappedBy="usersApp")
private List<UserAppDevice> userAppDevices;
public UsersApp() {
}
public int getUserId() {
return this.userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getOs() {
return this.os;
}
public void setOs(int os) {
this.os = os;
}
public String getToken() {
return this.token;
}
public void setToken(String token) {
this.token = token;
}
public String getUserNumber() {
return this.userNumber;
}
public void setUserNumber(String userNumber) {
this.userNumber = userNumber;
}
public String getUserPassword() {
return this.userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public List<UserAppDevice> getUserAppDevices() {
return this.userAppDevices;
}
public void setUserAppDevices(List<UserAppDevice> userAppDevices) {
this.userAppDevices = userAppDevices;
}
public UsersApp(int os, String token, String userNumber, String userPassword) {
this.os = os;
this.token = token;
this.userNumber = userNumber;
this.userPassword = userPassword;
}
I want to add new user with device
I try this code:
Session session = (Session) em.getDelegate();
session.beginTransaction();
UsersApp user = new UsersApp(os, token, userNumber, userPassword);
session.save(user);
UserAppDevice ud = new UserAppDevice();
ud.setUsersApp(user);
ud.setDeviceName(device);
session.save(ud);
session.getTransaction().commit();
but I am facing exception:
13:16:48,516 WARN [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http--0.0.0.0-8080-3) SQL Error: 1452, SQLState: 23000
13:16:48,517 ERROR [org.hibernate.engine.jdbc.spi.SqlExceptionHelper] (http--0.0.0.0-8080-3) Cannot add or update a child row: a foreign key constraint fails (`application`.`user_a
pp_devices`, CONSTRAINT `user_app_devices_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users_app` (`user_id`))
13:16:48,520 ERROR [org.jboss.as.ejb3.tx.CMTTxInterceptor] (http--0.0.0.0-8080-3) javax.ejb.EJBTransactionRolledbackException: Cannot add or update a child row: a foreign key const
raint fails (`application`.`user_app_devices`, CONSTRAINT `user_app_devices_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users_app` (`user_id`))
13:16:48,524 ERROR [org.jboss.ejb3.invocation] (http--0.0.0.0-8080-3) JBAS014134: EJB Invocation failed on component DeviceRegisterDAOImpl for method public abstract void com.break
id.ejb.model.DeviceRegisterDAO.add(int,java.lang.String,java.lang.String,java.lang.String,java.lang.String): javax.ejb.EJBTransactionRolledbackException: Cannot add or update a chi
ld row: a foreign key constraint fails (`application`.`user_app_devices`, CONSTRAINT `user_app_devices_ibfk_1` FOREIGN KEY (`user_id`) REFERENCES `users_app` (`user_id`))
at org.jboss.as.ejb3.tx.CMTTxInterceptor.handleInCallerTx(CMTTxInterceptor.java:139) [jboss-as-ejb3-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.as.ejb3.tx.CMTTxInterceptor.invokeInCallerTx(CMTTxInterceptor.java:204) [jboss-as-ejb3-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.as.ejb3.tx.CMTTxInterceptor.required(CMTTxInterceptor.java:306) [jboss-as-ejb3-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.as.ejb3.tx.CMTTxInterceptor.processInvocation(CMTTxInterceptor.java:190) [jboss-as-ejb3-7.1.1.Final.jar:7.1.1.Final]
at org.jboss.invocation.InterceptorContext.proceed(InterceptorContext.java:288) [jboss-invocation-1.1.1.Final.jar:1.1.1.Final]
at org.jboss.as.ejb3.remote.EJBRemoteTransactionPropagatingInterceptor.processInvocation(EJBRemoteTransactionPropagatingInterceptor.java:80) [jboss-as-ejb3-7.1.1.Final.jar:
7.1.1.Final]
What am I missing ?
You haven't told Hibernate that the ID of UserApp was generated automatically by the database:
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name="user_id")
private int userId;
(and do the same for the other entity)
Since your are using bidirectional, change your client code as below.
Session session = (Session) em.getDelegate();
session.beginTransaction();
UserAppDevice ud = new UserAppDevice();
ud.setDeviceName(device);
UsersApp user = new UsersApp(os, token, userNumber, userPassword);
user.setUserAppDevices(new ArrayList<UserAppDevice>())
user.getUserAppDevices().add(ud);
session.save(user);
session.getTransaction().commit();
As mentioned by JB Nizet, you're missing the autogenerated strategy.
An alternative would be to use UUID as your id column and create the values yourself with
#Id
private UUID id = UUID.randomUUID();
Also, don't forget to set equals/hashCode to use the id field as discussed to death in The JPA hashCode() / equals() dilemma
Incidentally, why are you using Session (hibernate specific) instead of sticking to JPA's API?
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();
}