I need to create entity based on information from database. Based on database I created string like this :
` package az.com.ds.entity.crudEntity;
import javax.persistence.Table;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Column;
#Table(name = "CMN_SP", schema = "CMN")
#Entity
public class CmnSpEnt {
#Id
private Integer id;
#Column(name = "NAME")
private String name;
} `
Then I created java file based on this string and compiled it at runtime. Everything works perfectly to this step. But when I want to get data based on entity it throws exception as
org.hibernate.hql.internal.ast.QuerySyntaxException: CmnSpEnt is not mapped [Select x from CmnSpEnt x ].
Now I need to map entity for hibernate in order to get data from database. Is there a way to accomplish this?
Related
I'm really stuck here and I need help, I've been trying to run my application and let hibernate create tables using my java entities, but it keeps raising this exception :
Unable to execute schema management to JDBC target [create table answer (id_answer bigint not null auto_increment, order integer, text varchar(255), question_id_question bigint, primary key (id_answer))]
Says that there is an error in my SQL syntax, even though i didn't write any sql, i let hibernate handle it all.
Below are my classes and configuration:
Answer.java :
package com.sfm.elearn.business.entities;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity
public class Answer implements Serializable {
#Id #GeneratedValue
private Long idAnswer;
private String text;
private Integer order;
#ManyToOne
#JsonIgnore
private Question question;
public Answer() {
super();
// TODO Auto-generated constructor stub
}
public Answer(String text, Integer order, Question question) {
super();
this.text = text;
this.order = order;
this.question = question;
}
public Long getIdAnswer() {
return idAnswer;
}
public void setIdAnswer(Long idAnswer) {
this.idAnswer = idAnswer;
}
}
This is my configuration :
spring.datasource.url=jdbc:mysql://localhost:3306/ElearningBase
spring.datasource.username=root
spring.datasource.password=654321
spring.datasource.testWhileIdle=true
spring.datasource.validationQuery=SELECT 1
spring.jpa.show-sql=true
spring.jpa.hibernate.ddl-auto=update
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.MySQL5Dialect
EDIT: I found the error , the attribute "order" is a reserved SQL keyword that's what was causing the error, changing the variable's name solved it!
If Hibernate is creating your tables for your then your hibernate.ddl-auto property should be set to 'create' or 'create-drop'. The update option means Hibernate expects your tables to already exist. See: Hibernate hbm2ddl.auto possible values and what they do?
I've been looking for a way to interact with my database using EntityManager class in Java.
The question is related to these two tables I have defined in my DB:
PARENT_TABLE:
PK_ONE
PK_TWO
CHILD TABLE:
PK_ONE
COLUMN
PK_TWO
Here is something I have so far.
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.SecondaryTable;
import javax.persistence.Table;
import javax.persistence.PrimaryKeyJoinColumn;
#Entity
#Table(name="PARENT_TABLE")
#SecondaryTable(name="CHILD_TABLE", pkJoinColumns={
#PrimaryKeyJoinColumn(name="PK_ONE"),
#PrimaryKeyJoinColumn(name="PK_TWO")})
public class ExampleTbl implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name="PK_ONE")
private String pkOne;
#Id
#Column(name="COLUMN", table="CHILD_TABLE")
private String column;
#Column(name="PK_TWO")
private String pkTwo;
//GETTERS AND SETTERS
}
My questions are:
To be able to Insert to the PARENT_TABLE a new row, do I have to create a new Entity class with just two fields (PK_ONE, PK_TWO) to be able to use the merge() or persist() method?
Will I have to create another Entity class to Insert a new row to my CHILD_TABLE?
To retrieve a List with the existing data I have a method something like this:
#Transactional(readOnly = true)
public List<ExampleTbl> getFoldersList() {
em = emf.createEntityManager();
Query q = em.createQuery("SELECT e FROM ExampleTbl e WHERE e.pkTwo = :pkTwo ORDER BY e.pkOne");
q.setParameter("pkTwo", "My Test");
List<ExampleTbl> result = q.getResultList();
return result;
}
Do you think this is the best way to do it?
I think its a question with a couple of possible answers. I would recommend reviewing some of the ways they set things up in the Java EE 6 tutorial examples. You can read about that at http://docs.oracle.com/javaee/6/tutorial/doc/giqst.html
Using JPA and Hibernate
I have an entity class
#Entity
#Table(name = "ROLES")
public class Role implements Serializable
{
#Column
private List<String> tubes;
// another fields .setters, getters
}
Every String in List tubes - is one row from another table (TUBES).
Table ROLES has an OneToMany relationship with TUBES.
A can make another Entity Tubes and map table TUBES on Entity Tubes. But how I can make this without another entity?
Edit:
I made
#ElementCollection
#CollectionTable(name = "TUBES", joinColumns = #JoinColumn(name = "role_id"))
#Column(name = "tube")
private ArrayList<String> tubes;
Deploy on JBoss. And in runtime I get SQLGrammarException
Query created by JPA is:
/* SELECT r FROM Role r WHERE r.name = ? */ select role0_.AA_ID as AA1_0_, role0_.ROLNAME as ROLNAME0_, role0_.role as PID4_0_ from PIDDB_PID_ROLE role0_ where role0_.ROLNAME=?
17:17:14,661 ERROR [JDBCExceptionReporter] ORA-00904: "ROLE0_"."tube": invalid identifier
You can use #ElementCollection mapping I think this is what are you looking for.
#ElementCollection(fetch=FetchType.LAZY)
#CollectionTable(name="TUBES", joinColumns=#JoinColumn(name="role_id"))
#Column(name="tube")
private List<String> tubes;
Update:
dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.0.Final</version>
</dependency>
**Update2:**
import javax.persistence.CollectionTable;
import javax.persistence.Column;
import javax.persistence.ElementCollection;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.Table;
This question already has answers here:
Creating Indexes on DB with Hibernate #Index Annotation
(4 answers)
Closed 7 years ago.
i have a java class used as an entity that has 2 classes that inherit from it. this class has some indices but these indices didn't appear in the database. this is my java super class code
import java.io.Serializable;
import java.util.List;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
import javax.persistence.Version;
import javax.persistence.OneToMany;
import org.hibernate.annotations.GenericGenerator;
#Entity
#Table(name="service", uniqueConstraints = {#UniqueConstraint(columnNames={"name"})})
#org.hibernate.annotations.Table(appliesTo = "service",
indexes = { #Index(name = "service_name", columnNames = { "name" }),
#Index(name = "service_description", columnNames = { "description" }),
#Index(name = "service_accessNumber", columnNames = { "access_number" })
})
public class Service implements Serializable {
#Column(name="access_number",length = 95,nullable=false)
String accessNumber;
#Column(length=80,nullable=false)
String name;
#Column(length=140)
String description;
}
does any one know what is my problem
Note: i have this problem in my all java classes but this is one of them. the code in all class is the same of this
Edit: i build an xml file and put it in a grails project, and when i run this project, database created
Would a single #Table annotation work? I haven't tried it, I guess the Hibernate #Table might be overridden by JPA #Table.
You may also try #Index annotation on the column fields:
public class Service implements Serializable {
#Index(name="service_accessnumber")
#Column(name="access_number",length = 95,nullable=false)
String accessNumber;
#Index(name="service_name")
#Column(length=80,nullable=false)
String name;
#Index(name="service_description")
#Column(length=140)
String description;
}
i have the same problem, but i found it's solution and it works fine with me try it, it may help you
in your DataSource.groovy file in your grails project make sure that under
environment dbCreate is not equal to "update": if it is equal to "update", change
it to "create".
This works fine just try it
I'm looking for a way to set the "default" mapping that Hibernate applies to a variable name in a Java object to query it against the database. At the moment we are using the inline javax.persistence markup to manually set column names, but since we have a rigid naming policy for our database it would be nice to be able to just skip on the manual naming and let Hibernate do the mapping. However, at the moment this doesnt work nice at all with anything save for local, non-primary key fields.
At the moment, Hibernate seems to be set to map non-foreign keys to just their name (see "foo" in the below example class), and foreign-keys to "variableName_ReferencedTable_Id" (see "bar" in the below example class). We would like non-foreign keys to stay as they are, except for the variable marked #id, which we would like to be mapped to "TableName_Id", and we would like foreign keys to be mapped to "variableName_Id". Is this even possible, or do we just have to put up with manual mapping?
package testPackage.test
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
public class Table1 {
private int id;
private int localVariable;
private int foreignKeyVariable;
// Constructor here somewhere
// Without a #Column( name="Table1_Id" ), this comes out as "id".
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
// This works fine, being a local field.
public int getLocalVariable() {
return localVariable;
}
public void setLocalVariable(int LocalVariable) {
this.localVariable = localVariable;
}
// Withou a #JoinColumn( name="foreignKeyVariable_Id" ) , this comes out as "foreignKeyVariable_Table2_Id".
#ManyToOne( cascade = {CascadeType.PERSIST, CascadeType.MERGE} )
#JoinColumn() // Not sure if this would even be necessary at all. Happy to leave it out if possible.
public int getForeignKeyVariable() {
return foreignKeyVariable;
}
public void setForeignKeyVariable(int foreignKeyVariable) {
this.foreignKeyVariable = foreignKeyVariable;
}
}
(copied from comment)
Hibernate does have the concept of NamingStrategy, but it's not sensitive to whether than object is a PK or a normal column, so that's not going to be of any use.