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
Related
I'm having issues with Hibernate. Let's say to create my table in SQL I have:
CREATE TABLE "SOMETHING_TABLE"
(
"COLUMN1" CHAR(10 BYTE) CONSTRAINT "SOMETHING_TABLE_COLUMN1_CK" NOT NULL ENABLE,
"COLUMN2" CHAR(10 BYTE),
"COLUMN3" CHAR(2 BYTE),
"COLUMN4" VARCHAR2(9 BYTE)
)
CREATE UNIQUE INDEX "PK_SOMETHING_TABLE" ON "SOMETHING_TABLE"
(
"COLUMN1", "COLUMN2", "COLUMN3"
)
And my Hibernate Entity looks like this:
#Entity
#Table(name = "SOMETHING_TABLE")
public class Something_tableImpl {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "COLUMN1")
private String column1 = null;
#Id
#Column(name = "COLUMN2")
private String column2 = null;
#Id
#Column(name = "COLUMN3")
private String column3 = null;
#Column(name = "COLUMN4")
private String column4 = null;
public String getColumn1() {
return column1;
}
public void setColumn1(String column1) {
this.column1 = column1;
}
public String getColumn2() {
return column2;
}
public void setColumn2(String column2) {
this.column2 = column2;
}
public String getColumn3() {
return column3;
}
public void setColumn3(String column3) {
this.column3 = column3;
}
public String getColumn4() {
return column4;
}
public void setColumn4(String column4) {
this.column4 = column4;
}
}
Then I create a hibernate query, more or less like this one:
public Something_table GetSomethingFrom(String column1, String column2, String column3) {
Criteria queryCriteria = myDAO.getCriteria(Something_tableImpl.class);
queryCriteria.add(Restrictions.eq("column1", column1));
if (StringUtils.isNotBlank(column2)) {
queryCriteria.add(Restrictions.eq("column2", column2));
}
if (StringUtils.isNotBlank(column3)) {
queryCriteria.add(Restrictions.eq("column3", column3));
}
List < Something_table > somethingTableList = queryCriteria.list();
if (!somethingTableList.isEmpty()) {
return somethingTableList.get(0);
}
return null;
}
Then somethingTableList size is 1, and the element this contains is null. But in the DataBase I was able to get 1 row with valid values.
So ¿Why am I getting null values?
EDIT1:
I can't add #IdClass annotation, because of in the DB exist rows that contains the values related to column1 and column2 as null. N̶o̶r̶ ̶r̶e̶m̶o̶v̶e̶ ̶t̶h̶e̶ ̶̶#̶I̶d̶̶ ̶o̶v̶e̶r̶ ̶t̶h̶o̶s̶e̶ ̶3̶ ̶c̶o̶l̶u̶m̶n̶s̶ ̶i̶n̶ ̶m̶y̶ ̶e̶n̶t̶i̶t̶y̶ ̶b̶e̶c̶a̶u̶s̶e̶ ̶o̶f̶ ̶t̶h̶e̶ ̶i̶n̶d̶e̶x̶ ̶t̶h̶a̶t̶ ̶w̶a̶s̶ ̶c̶r̶e̶a̶t̶e̶d̶ ̶i̶n̶ ̶O̶R̶A̶C̶L̶E̶.
EDIT2:
Could it be happening due to I'm not overriding hashcode() and equals()?
When I try save instance, I get this strange error:
WARN [15:06:27,917] JDBCExceptionReporter - SQL Error: 20000, SQLState: 42X04
ERROR[15:06:27,917] JDBCExceptionReporter - Column 'ad0b8d24-f596-47cb-9d79-06a3c9c1de26' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification or appears in a HAVING clause and is not in the GROUP BY list. If this is a CREATE or ALTER TABLE statement then 'ad0b8d24-f596-47cb-9d79-06a3c9c1de26' is not a column in the target table.
Row is not inserted into database.
It looks like it is trying to use scenario_id (uuid) as column name. But why?
I am using this Data Access Object:
public interface ScenarioDao extends GenericDao<Scenario, String> {
public List<Scenario> getScenariosWhereOwner(Person owner);
public List<Scenario> getScenariosWhereOwner(Person person, int LIMIT);
...
}
public interface GenericDao <T, PK extends Serializable>{
public PK create(T newInstance) {
PK primaryKey = (PK) getHibernateTemplate().save(newInstance);
return primaryKey;
}
}
POJO:
#Entity
#Table(name = "SCENARIO")
#XmlRootElement
public class Scenario implements Serializable, Comparable<Scenario> {
private static final long serialVersionUID = -6608175331606366993L;
private String scenarioId;
private Person person;
private ResearchGroup researchGroup;
private String title;
private int scenarioLength;
private boolean privateScenario;
private String description;
private String scenarioName;
private String mimetype;
private Set<History> histories = new HashSet<History>(0);
private Set<Experiment> experiments = new HashSet<Experiment>(0);
private boolean userMemberOfGroup;
private Blob scenarioFile;
private String group;
private Boolean availableFile;
private InputStream fileContentStream;
#Transient
public boolean isUserMemberOfGroup() {
return userMemberOfGroup;
}
public void setUserMemberOfGroup(boolean userMemberOfGroup) {
this.userMemberOfGroup = userMemberOfGroup;
}
#Transient
public String getGroup() {
return group;
}
public void setGroup(String group) {
this.group = group;
}
#Transient
public Boolean getAvailableFile() {
return availableFile;
}
public void setAvailableFile(Boolean availableFile) {
this.availableFile = availableFile;
}
public Scenario() {
}
public Scenario(Person person, ResearchGroup researchGroup) {
this.person = person;
this.researchGroup = researchGroup;
}
public Scenario(Person person, ResearchGroup researchGroup, String title,
int scenarioLength, boolean privateScenario, String description,
String scenarioName, String mimetype, Set<History> histories,
Set<Experiment> experiments) {
this.person = person;
this.researchGroup = researchGroup;
this.title = title;
this.scenarioLength = scenarioLength;
this.privateScenario = privateScenario;
this.description = description;
this.scenarioName = scenarioName;
this.mimetype = mimetype;
this.histories = histories;
this.experiments = experiments;
}
#Id
#GeneratedValue(generator = "system-uuid")
#GenericGenerator(name = "system-uuid", strategy = "uuid2")
#Column(name = "SCENARIO_ID", nullable = false, length = 36, scale = 0)
public String getScenarioId() {
return this.scenarioId;
}
public void setScenarioId(String scenarioId) {
this.scenarioId = scenarioId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "OWNER_ID", nullable = false)
public Person getPerson() {
return this.person;
}
public void setPerson(Person person) {
this.person = person;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "RESEARCH_GROUP_ID", nullable = false)
public ResearchGroup getResearchGroup() {
return this.researchGroup;
}
public void setResearchGroup(ResearchGroup researchGroup) {
this.researchGroup = researchGroup;
}
#Column(name = "TITLE", unique = true)
public String getTitle() {
return this.title;
}
public void setTitle(String title) {
this.title = title;
}
#Column(name = "SCENARIO_LENGTH", precision = 22, scale = 0)
public int getScenarioLength() {
return this.scenarioLength;
}
public void setScenarioLength(int scenarioLength) {
this.scenarioLength = scenarioLength;
}
#Column(name = "PRIVATE", precision = 1, scale = 0)
public boolean isPrivateScenario() {
return this.privateScenario;
}
public void setPrivateScenario(boolean privateScenario) {
this.privateScenario = privateScenario;
}
#Lob
#Type(type = "org.hibernate.type.TextType")
#Column(name = "DESCRIPTION")
public String getDescription() {
return this.description;
}
public void setDescription(String description) {
this.description = description;
}
#Column(name = "SCENARIO_NAME")
public String getScenarioName() {
return this.scenarioName;
}
public void setScenarioName(String scenarioName) {
this.scenarioName = scenarioName;
}
#Column(name = "MIMETYPE")
public String getMimetype() {
return this.mimetype;
}
public void setMimetype(String mimetype) {
this.mimetype = mimetype;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "scenario")
public Set<History> getHistories() {
return this.histories;
}
public void setHistories(Set<History> histories) {
this.histories = histories;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "scenario")
public Set<Experiment> getExperiments() {
return this.experiments;
}
public void setExperiments(Set<Experiment> experiments) {
this.experiments = experiments;
}
#XmlJavaTypeAdapter(BlobSerializer.class)
#Basic(fetch = FetchType.LAZY)
#Lob
#Column(name = "SCENARIO_FILE", nullable = true)
public Blob getScenarioFile() {
return this.scenarioFile;
}
public void setScenarioFile(Blob scenarioFile) {
this.scenarioFile = scenarioFile;
}
#Override
public int compareTo(Scenario scen) {
return this.title.compareTo(scen.getTitle());
}
public void setFileContentStream(InputStream inputStream) {
this.fileContentStream = inputStream;
}
#Transient
public InputStream getFileContentStream() {
return fileContentStream;
}
}
I try to create it using this code:
scenario = new Scenario();
scenario.setPrivateScenario(some boolean);
scenario.setScenarioLength(some int);
scenario.setDescription(some string);
scenario.setTitle(some string);
scenario.setResearchGroup(some ResearchGroup);
scenario.setPerson(some Person);
All these parameters are set correctly. I am also using GenericDao with other objects without errors. Here is insert statement generated by hibernate:
DEBUG[16:07:25,132] SQL - insert into SCENARIO (DESCRIPTION, MIMETYPE, OWNER_ID, PRIVATE, RESEARCH_GROUP_ID, SCENARIO_FILE, SCENARIO_LENGTH, SCENARIO_NAME, TITLE, SCENARIO_ID) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
TRACE[16:07:25,153] BasicBinder - binding parameter [1] as [LONGVARCHAR] - newscenariodescription
TRACE[16:07:25,153] BasicBinder - binding parameter [2] as [VARCHAR] - <null>
TRACE[16:07:25,153] BasicBinder - binding parameter [3] as [VARCHAR] - 9e87924e-3a14-4f82-ad57-c191ead873b5
TRACE[16:07:25,153] BasicBinder - binding parameter [4] as [BIT] - false
TRACE[16:07:25,154] BasicBinder - binding parameter [5] as [VARCHAR] - b399f04f-92a7-427c-9af5-f90055cb1ddc
TRACE[16:07:25,154] BasicBinder - binding parameter [6] as [BLOB] - <null>
TRACE[16:07:25,154] BasicBinder - binding parameter [7] as [INTEGER] - 5
TRACE[16:07:25,154] BasicBinder - binding parameter [8] as [VARCHAR] - <null>
TRACE[16:07:25,154] BasicBinder - binding parameter [9] as [VARCHAR] - newscenario
TRACE[16:07:25,154] BasicBinder - binding parameter [10] as [VARCHAR] - 2d71bcd2-756e-4ffd-82b0-9649d7f05e0b
WARN [16:07:25,180] JDBCExceptionReporter - SQL Error: 20000, SQLState: 38000
ERROR[16:07:25,180] JDBCExceptionReporter - The exception 'java.sql.SQLException: Column '2d71bcd2-756e-4ffd-82b0-9649d7f05e0b' is either not in any table in the FROM list or appears within a join specification and is outside the scope of the join specification or appears in a HAVING clause and is not in the GROUP BY list. If this is a CREATE or ALTER TABLE statement then '2d71bcd2-756e-4ffd-82b0-9649d7f05e0b' is not a column in the target table.' was thrown while evaluating an expression.
When I try execute:
String query = "insert into SCENARIO (DESCRIPTION, MIMETYPE, OWNER_ID, PRIVATE, RESEARCH_GROUP_ID, FILE_CONTENT, SCENARIO_LENGTH, SCENARIO_NAME, TITLE, SCENARIO_ID) values ('newscenariodescription', NULL, '9e87924e-3a14-4f82-ad57-c191ead873b5', 0, 'b399f04f-92a7-427c-9af5-f90055cb1ddc', NULL, 5, NULL, 'text', '2d71bcd2-756e-4ffd-82b0-9649d7f205e0b')";
session.createSQLQuery(query).executeUpdate();
I get same error.
When I try execute query directly I get very strange error:
SQL Error [20000] [38000]: The exception 'java.lang.NoClassDefFoundError: org/jumpmind/symmetric/db/derby/DerbyFunctions' was thrown while evaluating an expression.
SQL Error [XJ001]: Java exception: 'org/jumpmind/symmetric/db/derby/DerbyFunctions: java.lang.NoClassDefFoundError'.
The exception 'java.lang.NoClassDefFoundError: org/jumpmind/symmetric/db/derby/DerbyFunctions' was thrown while evaluating an expression.
The exception 'java.lang.NoClassDefFoundError: org/jumpmind/symmetric/db/derby/DerbyFunctions' was thrown while evaluating an expression.
Java exception: 'org/jumpmind/symmetric/db/derby/DerbyFunctions: java.lang.NoClassDefFoundError'.
org/jumpmind/symmetric/db/derby/DerbyFunctions
I forget to set capture_big_lobs in trigger table. Changing value to 1 solved problem. However if the column is NULL, then SymmetricDS will throw Null Pointer Exception. I am using 3.5.10, so maybe it's solved in newer versions.
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.
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();
}
I have following two tables
CREATE TABLE event_type_master (
Event_Type_Code varchar(128) NOT NULL,
PRIMARY KEY (Event_Type_Code)
)
CREATE TABLE event_master (
Event_Code varchar(128) NOT NULL,
Event_Type_Code varchar(128) NOT NULL,
PRIMARY KEY (Event_Code,Event_Type_Code),
CONSTRAINT FK1 FOREIGN KEY (Event_Type_Code) REFERENCES event_type_master (Event_Type_Code)
)
Now I have create model classes for the above relation as follow
EventMaster Class:-
#Entity
#Table(name="event_master")
public class EventMaster implements java.io.Serializable {
private EventMasterId id;
private EventTypeMaster eventTypeMaster;
private String eventName;
public EventMaster() {
}
public EventMaster(EventMasterId id, EventTypeMaster eventTypeMaster) {
this.id = id;
this.eventTypeMaster = eventTypeMaster;
}
public EventMaster(EventMasterId id, EventTypeMaster eventTypeMaster) {
this.id = id;
this.eventTypeMaster = eventTypeMaster;
this.eventName = eventName;
}
#EmbeddedId
#AttributeOverrides( {
#AttributeOverride(name="eventCode", column=#Column(name="Event_Code", nullable=false, length=128) ),
#AttributeOverride(name="eventTypeCode", column=#Column(name="Event_Type_Code", nullable=false, length=128) ) } )
public EventMasterId getId() {
return this.id;
}
public void setId(EventMasterId id) {
this.id = id;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="Event_Type_Code",referencedColumnName = "Event_Type_Code", nullable=false, insertable=false, updatable=false)
public EventTypeMaster getEventTypeMaster()
{
return this.eventTypeMaster;
}
public void setEventTypeMaster(EventTypeMaster eventTypeMaster) {
this.eventTypeMaster = eventTypeMaster;
}
}
EventMasterId Class for Compound Primary Key setting:-
#Embeddable
public class EventMasterId implements java.io.Serializable {
private String eventCode;
private String eventTypeCode;
public EventMasterId() {
}
public EventMasterId(String eventCode, String eventTypeCode)
{
this.eventCode = eventCode;
this.eventTypeCode = eventTypeCode;
}
#Column(name="Event_Code", nullable=false, length=128)
public String getEventCode() {
return this.eventCode;
}
public void setEventCode(String eventCode) {
this.eventCode = eventCode;
}
#Column(name="Event_Type_Code", nullable=false, length=128)
public String getEventTypeCode() {
return this.eventTypeCode;
}
public void setEventTypeCode(String eventTypeCode) {
this.eventTypeCode = eventTypeCode;
}
public boolean equals(Object other) {
........
}
public int hashCode() {
..........
}
}
EventTypeMaster Class
#Entity
#Table(name="event_type_master")
public class EventTypeMaster implements java.io.Serializable {
private String eventTypeCode;
private String eventTypeName;
private Set<EventMaster> eventMasters = new HashSet<EventMaster>(0);
public EventTypeMaster() {
}
public EventTypeMaster(String eventTypeCode) {
this.eventTypeCode = eventTypeCode;
}
public EventTypeMaster(String eventTypeCode, String eventTypeName, Set eventMasters) {
this.eventTypeCode = eventTypeCode;
this.eventTypeName = eventTypeName;
this.eventMasters = eventMasters;
}
#Id
#Column(name="Event_Type_Code", unique=true, nullable=false, length=128)
public String getEventTypeCode() {
return this.eventTypeCode;
}
public void setEventTypeCode(String eventTypeCode) {
this.eventTypeCode = eventTypeCode;
}
#OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="eventTypeMaster")
#JoinColumn(name="Event_Type_Code", referencedColumnName = "Event_Type_Code")
public Set<EventMaster> getEventMasters() {
return this.eventMasters;
}
public void setEventMasters(Set<EventMaster> eventMasters) {
this.eventMasters = eventMasters;
}
}
After setting All I created a HebernateUtil Class using Netbeans to connect to HibernateSession Factory and tried to Test adding a record to event_master table as follow
Session session = null;
session = NewHibernateUtil.getSessionFactory().getCurrentSession();
try {
org.hibernate.Transaction tx = session.beginTransaction();
EventMasterId key1=new EventMasterId();
EventTypeMaster eTypeMaster1=new EventTypeMaster();
eTypeMaster1=(EventTypeMaster)session.load(EventTypeMaster.class, "e1");
key1.setEventCode(eTypeMaster1.getEventTypeCode());
key1.setEventCode("Test_Event_Code");
EventMaster em=new EventMaster();
em.setId(key1);
em.setEventTypeMaster(eTypeMaster1);
em.setEventDesc("Event Description");
session.save(em);
session.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
}
But I am getting following Error
Hibernate: insert into event_master (Create_DTTM, Created_By, Event_Desc, Event_Name, Event_Short_Name, Last_Mod_By, Last_Mod_DTTM, Event_Code, Event_Type_Code) values (?, ?, ?, ?, ?, ?, ?, ?, ?)
1473 [main] WARN org.hibernate.util.JDBCExceptionReporter - SQL Error: 1048, SQLState: 23000
1473 [main] ERROR org.hibernate.util.JDBCExceptionReporter - Column 'Event_Type_Code' cannot be null
1474 [main] ERROR org.hibernate.event.def.AbstractFlushingEventListener - Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:94)
at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:66)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:275)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:266)
at org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167)
at org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:321)
at org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:50)
at org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1028)
at org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:366)
at org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:137)
at test.NewMain.main(NewMain.java:46)
Caused by: java.sql.BatchUpdateException: Column 'Event_Type_Code' cannot be null
at com.mysql.jdbc.PreparedStatement.executeBatchSerially(PreparedStatement.java:1666)
at com.mysql.jdbc.PreparedStatement.executeBatch(PreparedStatement.java:1082)
at org.hibernate.jdbc.BatchingBatcher.doExecuteBatch(BatchingBatcher.java:70)
at org.hibernate.jdbc.AbstractBatcher.executeBatch(AbstractBatcher.java:268)
Please help me to solve this.
I think you have a typo.
key1.setEventCode(eTypeMaster1.getEventTypeCode());
key1.setEventCode("Test_Event_Code");
Should the first line be key1.setEventTypeCode.