I started a Dynamic Web Project in Eclipse an turned it into a JPA project using Hibernate as the persistence provider. Then I used the JPA tools of Eclipse to generate Entities from the tables, which also worked fine. But when I try to persist an object of my class "Person", I receive the error 'Table "Person" not found'. The table is named exactly like this in the database (PostgreSQL) and the Entity Manager is also active (isOpen returns true). I also tried different namings (uppercase, explicitly quoted etc) of the table in the database and of the name attribute in the annotation to be sure it's not that kind of problem.
#Entity
#Table(schema="public", name="Person")
#NamedQuery(name="Person.findAll", query="SELECT p FROM Person p")
public class Person implements Serializable {
...
Table "Person" not found; SQL statement:
insert into public.Person ([columns]) values ([values])[42102-197]
What am I doing wrong?
Related
I would like some of tables in my database to have standard columns such as createdBy, ModifiedBy, CreatedDateTime, modifiedDateTime etc.
So, I created an interface with those properties and implemented the interface in an abstract base class. I derived my concrete classes from this base class.
This is a brand new application using Code-First approach. When I create the database, the derived properties are ignored. The tables are created with just the properties in the derived classes.
I'm not sure why.
Thank you.
I'm not sure exactly what was different, but tried it again with the following changes and it worked:
gave dbCreator rights in the database for the user
Changed the properties in my base class to be in the format (similar change for the other properties):
public string CreatedBy { get; set;}
I have a JPA entity with the following definition. Its marked as read only and the cache is set to expire at 3 am.
Please consider this scenario .
1. The table has a record with deptId :100 and department Name: "SALES"
Fetch the record programatically using
entityManager.createNamedQuery("Department.findById").setParameter("depId",100) .getResultList();
The returned record contains the department name as "SALES"
The above record data is modified directly in the backend database using a update
sqlquery. changed the department name from "SALES" to "REGIONAL_SALES"
Programatically fetch the record with deptId :100 using entityManager.createNamedQuery("Department.findById").setParameter("depId",100) .getResultList();
The returned record contains the updated department name
How does JPA know the value in the backend has been updated? Instead of fetching from cache its fetching the updated value from DB
or
Is it the cache got updated after the DB change. I have set the cache to expire only at 3am (24 hr format)
Please help me understand
#NamedQuery(name="Department.findById", query = "SELECT d from Department d WHERE d.deptNo= :depId")
#Entity
#Table(name="DEPARTMENT")
#Cache(expiryTimeOfDay=#TimeOfDay(hour=3))
#ReadOnly
public class Department{
#EmbeddedId
int deptNo;
#Column
String deptName;
//constructor, getter and setter
}
JPA providers have different caching policies. You didn't state what provider do you use but I'm assuming that you are using EclipseLink. Quote from their wiki:
By default in EclipseLink all queries access the database, unless they are by Id, or by cache indexed fields.
I recommend you check
http://wiki.eclipse.org/EclipseLink/UserGuide/JPA/Basic_JPA_Development/Caching/Query_Cache
http://www.eclipse.org/eclipselink/documentation/2.6/concepts/cache003.htm
From my point of view your query should hit cache first.
Its strange though you annotate #EmbeddedId and int typed field.
Does it work for you because it causes following exception?
The Entity class (...) has an embedded at
tribute [id] of type [class int] which is NOT an Embeddable class. Probable reason: missing #Embeddable or missing in orm.xml if metadata-complete
A query will go to the database (barring any implementation-specific option to just use the cache). It isn't a case of the implementation "knowing" the datastore is updated ... it goes there anyway. Not the same for a EM.find() call though.
I have an EDMX file which has both tables and views mapped from a SQL Server database. I am trying to add a view named CourseCompany to the EDMX file which serves as a many-to-many connection between two other views.
By looking at another many-to-many association using tables as an example, these are the non-default value properties on the association I added:
Association Set Name: CourseCompany
End1 Multiplicity: * (Collection of Course)
End1 Navigation Property: Companies
End2 Multiplicity: * (Collection of Company)
End 2 Navigation Property: Courses
Name: CourseCompany
But doing this produces this compile error:
Error 3027: No mapping specified for the following EntitySet/AssociationSet - CourseCompany
I made sure the views that this association is going between have their primary keys defined correctly in the EDMX. What do I need to do to add this association in the EDMX?
Follow these steps to resolve this problem:
Add the many-to-many view through the "Update Model from Database" tool.
Edit the newly added entity so that both fields have Entity Key set to true.
Add an Association to the EDMX and configure it as I noted in the question above.
Click on the Association link and go to the Mapping Details tab.
Select the view name in the Maps to dropdown and set the field mappings as well.
Delete the entity that was added in step 1.
This kind of error is often caused by not running the "Generate Database From Model" command (accessible from the context menu of the EDMX designer) after making changes to the design.
Running the tool (if it worked, it will update the SQL generation script) should cause the problem to go away.
I use the Zend 2 Framework to build my web application. I implemented my database table models by this tutorial: http://framework.zend.com/manual/2.1/en/user-guide/database-and-models.html
I have a many-to-many relationship between two models in my database. To get data from them I googled and found this link: http://mattmccormick.ca/2010/04/24/how-to-easily-create-models-and-table-relationships-in-zend-framework/
The problem is that all the table models extends from Zend_Db_Table_Abstract in the example. I don't know how to get data from the models.
I have a table containing votings, every voting has a unique hash id. Every voting also has tags. Therefore I defined a table tags with all the tags available and a voting_tag_map where all many-to-many relationships are mapped.
What I have tried so far is the following, that's code from my VotingTable class:
public function getTagsByVoting($votingHash){
$select = $this->tableGateway->getSql()->select();
$select->from(array('v' => 'voting'))
->join('voting_tag_map', 'v.voting_id=voting_tag_map.voting_id')
->join('tags', 'voting_tag_map.tag_id=tags.tag_id');
$resultSet = $this->tableGateway->selectWith($select);
return $resultSet;
}
It says then:
Since this object was created with a table and/or schema in the constructor, it is read only.
Thats because of the from() method. If I delete the from() method, it says:
Statement could not be executed
Can anyone help me please?
Since this object was created with a table and/or schema in the constructor, it is read only.
This error is because you are trying to set the table name in the from clause, but it's already been set in the contructor of the TableGateway, and you can't change it once set.
If you really need to do this then you can extens AbstractTableGateway yourself then you won't have to add a string tablename to the contructor, but you don't really need to use an alias on your main table...
The SQL error you get when you comment out the from() method will be due to your referencing the votes table as it's alias 'v' in your join, when you are not using the alias v, try changing it to 'voting.XXX' from 'v.XXX'
we have question about inheritance in PostgreSQL and mapping it as entities in JPA.
Our database, and tables we want to map are:
CREATE TABLE Answer (
idAnswer SERIAL,
answerContent VARCHAR,
idQuestion INTEGER,
version INTEGER,
CONSTRAINT Answer_idAnswer_PK PRIMARY KEY (idAnswer),
CONSTRAINT Answer_idQuestion_FK FOREIGN KEY (idQuestion) REFERENCES Question(idQuestion)
);
CREATE TABLE MatchAnswer (
matchingAnswer VARCHAR NOT NULL,
version INTEGER,
CONSTRAINT MatchAnswer_idAnswer_PK PRIMARY KEY (idAnswer)
) INHERITS(Answer);
CREATE TABLE TrueFalseAnswer (
isTrue BOOLEAN NOT NULL,
version INTEGER,
CONSTRAINT TrueFalseAnswer_idAnswer_PK PRIMARY KEY (idAnswer)
) INHERITS(Answer);
And we mapped them for entities using automatic tool in Netbeans 7.1.2.
At first I thought it would be enough just to add
#Entity
#Table(name = "truefalseanswer", catalog = "jobfairdb", schema = "public")
#XmlRootElement
public class Truefalseanswer extends Answer implements Serializable {
private static final
so just extends, but it didn't work properly.
What is the best approach to this? Thanks in advance.
JPA's concept of inheritance is based on ordinary tables. It doesn't really "get" the idea of PostgreSQL's table inheritance. That's one of the costs of working with a spec designed to expose the lowest common denominator of features and do so portably.
See this guide for a decent summary of JPA inheritance strategies. Note that in the newer Java 6 JavaDoc for #Inheritance there is a note saying that:
If the Inheritance annotation is not specified or if no inheritance
type is specified for an entity class hierarchy, the SINGLE_TABLE
mapping strategy is used.
... and if you look at how SINGLE_TABLE works, it's not surprising it doesn't work for you; it's expecting all subclasses to be in one big table with a magic discriminator value.
InheritanceType.TABLE_PER_CLASS is closer to how Pg behaves, but I suspect that the JPA impl will get a bit confused when the base type tables have entries for each entity of a leaf type. It tries to do things like UNION queries across the subclass tables when querying on the superclass, and that could produce odd results - at least duplication if UNION is used and performance issues if it uses UNION ALL. Depending on exactly how the provider implements the strategy it may work at least partially. You'd have to test, and the results would possibly be fairly provider specific.
A really good implementation of PG inheritance support for JPA would probably require JPA provider extensions for a new inheritance strategy that understood the PostgreSQL extensions for inheritance and for ONLY queries.
If you can convince your JPA implementation to use SELECT ... FROM ONLY subclass_table when in InheritanceType.TABLE_PER_CLASS mode then it should inter-operate OK with PostgreSQL inheritance. It would see only the non-inherited rows in each table and work with them as if they were ordinary tables. Your other non-JPA code could then keep using the inheritance features. I guess it's possible you could modify the PostgreSQL dialect code for Hibernate to do this, but personally I wouldn't go there unless I absolutely had to make JPA support existing PostgreSQL schema that relied heavily on inheritance.
There is a solution using MappedSuperClass annotation.
#MappedSuperClass
public abstract class AbstractAnswer{
#Id
protected Long idAnswer;
#Column(name="answerContent")
protected String answerContent;
}
#Entity
#Table(name="Answer")
public class Answer extends AbstractAnswer{
}
#Entity
#Table(name="MatchAnswer")
public class MatchAnswer extends AbstractAnswer{
protected String matchingAnswer;
}
#Entity
#Table(name="TrueFalseAnswer")
public class TrueFalseAnswer extends AbstractAnswer{
protected Boolean trueFalseAnswer;
}
Inheritance in Hibernate has nothing to do with PostgreSQL inheritance, even though both try to accomplish the same and might look the same.
The reason for this is that Hibernate takes the SQL standards as base, and adjusts the small specific features from each RDBMS. For instance, while MySQL have an "auto-increment" for sequential IDs, Oracle uses sequences.
Historically, data inheritance (or specialization) has been done by using separate tables for the specific fields, with primary-foreign-keys linking the tables together. In your example, MatchAnswer would have the ID as PK and FK to Answer.idAnswer. Same with TrueFalseAnswer (the ID is PK/FK to Answer.idAnswer).
The "inherits" definition that you posted is not (AFAIK) defined in any SQL standard, so, I'd be surprised if Hibernate supported this, specially because it seems to be something extremely specific to PostgreSQL and it seems it's a somewhat experimental feature: look at "Caveats" on the "Inheritance" chapter of the PostgreSQL documentation.
That said, I'd suggest to keep your data sane, mapping them according to the best relational-model practices. Then, in your Hibernate mappings, you can express data inheritance where it makes sense.