I have two tables named User and Role(POJO classes). I am using hibernate and named query to access data from postgresql. User has roleid which is the foreign key referencing id in Role table.
#NamedQuery(name="User.logincheck",query="SELECT u FROM User u WHERE u.loginName = :loginName AND u.password = :password")
If I am writing the above query to access contents of User table alone the code is working.
But I want to get one column from Role table so I add
#SecondaryTable(name="Role",
pkJoinColumns=#PrimaryKeyJoinColumn(name="ID",
referencedColumnName = "RoleID"))
When I add the above code I'm getting Internal sever error. I'm using tomcat 8.
How can I make it work and retrieve one column from the first query?
Related
long story short, I have a coupon system project.
in it I have companys, coupons and customer.
all of their data is save in an SQL DB, based on apache derby.
for example:
a company exist on the company table. has id, name, password, email
a coupon exist on the coupon table. has id, title, price, etc..
only a company can create a coupon, and what it does, not only it is created on the coupon table mentioned above, it is also populating a second 'index' table, joining company's and coupons= company_coupon. has company_id, coupon_id
now everything else in the project is working beautifully, and the tables are checked by my teachers and everything is configured correctly.
what I'm trying to do next, and just cant seem to figure out the syntax for is:
when I delete a company, I also want to delete every coupon this company has created, from the coupon table. this I do by searching the company_coupon table for company_id matches, and deleting based on the coupon_id paired with them.
I'm trying this statment:
String sql = "DELETE FROM coupon INNER JOIN company_coupon ON id = company_coupon.coupon_id WHERE company_coupon.company_id = "
sql += companyObject.getId();
<-- method is getting an object and I have access to it's id, but I tried hard coding a specific company id and still..
the same error keeps coming back in different variations:
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "INNER" at
line 1, column 8.
I searched online here and elsewhere, was advised to add an 'alias' after the DELETE. got the same error, pointing at that extra word:
"DELETE c FROM coupon INNER JOIN company_coupon ON id = company_coupon.coupon_id WHERE company_coupon.company_id = " ---->>
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "c" at
line 1, column 8.
any ideas? :(
You might need two delete statements:
delete from company where id=1;
delete from company_coupon where id_company=1;
If your database supports cascade deletes on foreign keys, you might need just one delete statement.
Take a look at: http://sqlfiddle.com/#!7/86102/6 (click "Run SQL" and scroll down to the bottom of the result, try changing the sql yourself)
Solved:
String sql = "DELETE FROM customer_coupon WHERE coupon_id IN (SELECT company_coupon.coupon_Id FROM company_coupon WHERE company_coupon.company_id = ";
sql += comp.getId();
sql += ")";
I sent a command to the database
INSERT INTO UserEntity(id, username, email, password, enabled, registration_date, modified_date)
SELECT
1, 'JonkiPro', 'someemail#someemail.com,', 'safsd', true, GetDate(), GetDate()
WHERE NOT EXISTS (
SELECT * FROM users WHERE username = 'JonkiPro'
);
which is to add a new user to the database. Cherry during compilation throws out the error
ERROR: relationship "userentity" does not exist
I am in the application created entity 'UserEntity' which represents the user with an annotation added #Table(name="users")?
How do I make a mistake when creating this query?
Pretty clear your error code. Basically you are trying to insert some data in a table userentity that doesn't exist in your database schema. (In SQL, tables = relationships).
You just have to put the name of your database table that you want to insert into or create a table named userentity.
So I am using Postgres and Hibernate 4.2.2 and with entity like this
#Entity(name = "Users")
#Check(constraints = "email ~* '^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+[.][A-Za-z]+$'")
#DynamicInsert
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id_user",unique = true)
#Index(name = "user_pk")
private Integer idUser;
Hibernate still inserts some id that is already in the table, instead of leaving it emtpy for the database to fill it in. Also hibernate forces ids based on its cache not even checking the database whether it has the lates id.
How can I force it so I can leave id blank and let the database insert it?
First I thought it was because I was using int and that int is by default 0 but even when using object it just forces the id there from its cache.
So my goal is to let the database fill the ids instead of hibernate or at least Hibernate before filling it in to check the database for id first.
So the error I was getting wasCaused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "users_pkey" Detail: Key (id_user)=(1) already exists.
And it wasn't caused by Hibernate and caching but by import of data at creation of database, where I inserted with given ids eg: INSERT INTO users(id_user,email,password,tag) VALUES (1,'a#b.c','***','Adpleydu');
and the sequence for generating wasn't updated so if I inserted with pure SQL via console I got the same error.
Seeding the data is the problem. However you can still seed with pure sequal and have the sequence "keep up".
1) Assure your primary key is of type SERIAL.
CREATE TABLE table_name(
id SERIAL
);
2) Add this 'setval' line to assure the sequence is updated.
select setval('table_name_id_seq',COALESCE((select max(id) + 1 from table_name), 1));
Reference:
https://www.postgresqltutorial.com/postgresql-serial/
I'm using EclipseLink(JPA 2.0) under Netbeans 7.0 with JDK 7. Adding more, this is a JavaSE.
I have this tables, Employee and Record where in the relation is Employee(1) --- (*)Records.
Adding more about the structure of the Record: RecordID (PK), EmployeeID(FK), Status, etc.
I wanted to query out from the Record Table (not using the Employee->Rental Collection) what records has a relation with the employee..
I tried using the query, it always returns an exception
Exception Description: Error compiling the query [SELECT r FROM Record r WHERE
r.employeeid = :employeeid], unknown state or association field
[employeeid] of class [Record].
From the information given it's not completely clear, but I believe you need to reference the id inside the Employee object.
eg. the correct query is probably:
SELECT r FROM Record r WHERE r.employee.id = :employeeid
(notice the extra dot in employee.id)
If this doesn't work, please provide us with some actual code of your Java classes.
I am using Hibernate and getting
Exception in thread "main" org.hibernate.ObjectNotFoundException: No row with the given identifier exists: [#271]
What is pretty weird about this error is, that the object with the given id exists in the database. I inserted the problematic record in another run of the application. If I access it in the same run (i.e. same hibernate session) there seem to be no problems retrieving the data.
Just because it could be a fault of the mapping:
public class ProblemClass implements Persistent {
#ManyToOne(optional = false)
private MyDbObject myDbObject;
}
public class MyDbObject implements Persistent {
#OneToMany(mappedBy = "myDbObject")
private List<ProblemClass> problemClasses;
#ManyToOne(optional = false)
private ThirdClass thirdClass;
}
I have absolutely no clue even where to look at. Any hints highly appreciated!
Just to clarify:
The data was inserted in another RUN of the application. It is definitely in the database, as I can see it via an SQL-Query after the application terminated. And after THAT, i.e. when starting the application again, I get the error in the FIRST query of the database -- no deletion, no rollback involved.
Addition:
Because it was asked, here is the code to fetch the data:
public List<ProblemClass> getProblemClasses() {
Query query = session.createQuery("from ProblemClass");
return query.list();
}
And just to make it complete, here is the generic code to insert it (before fetching in another RUN of the application):
public void save(Persistent persistent) {
session.saveOrUpdate(persistent);
}
Eureka, I found it!
The problem was the following:
The data in the table ThirdClass was not persisted correctly. Since this data was referenced from MyDbObject via
optional = false
Hibernate made an inner join, thus returning an empty result for the join. Because the data was there if executed in one session (in the cache I guess), that made no problems.
MySQL does not enforce foreign key integrity, thus not complaining upon insertion of corrupt data.
Solution: optional = true or correct insertion of the data.
Possible reasons:
The row was inserted by the first session, but transaction was not committed when second session tried to access it.
First session is roll-backed due to some reason.
Sounds like your transaction inserting is rollbacked
Main reason behind this issue is data mismatch, for example i have entity mapping class called "X" and it has column "column1" and it has reference to the table "Y" column "column1" as below
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "column1", referencedColumnName = "column1")
public Y getColumn1() {
return Y;
}
In this if X table column1 has value but Y table column1 is not having the value. Here link will be failed.
This is the reason we will get Hibernate objectNotFound exception
This issue can also be resolved by creating proper data model like creating proper indexing and constraints (primary key/foreign key) ..
This might be your case, kindly check my answer on another post.
https://stackoverflow.com/a/40513787/6234057
I had the same Hibernate exception.
After debugging for sometime, i realized that the issue is caused by the Orphan child records.
As many are complaining, when they search the record it exists.
What i realized is that the issue is not because of the existence of the record but hibernate not finding it in the table, rather it is due to the Orphan child records.
The records which have reference to the non-existing parents!
What i did is, find the Foreign Key references corresponding to the Table linked to the Bean.
To find foreign key references in SQL developer
1.Save the below XML code into a file (fk_reference.xml)
<items>
<item type="editor" node="TableNode" vertical="true">
<title><![CDATA[FK References]]></title>
<query>
<sql>
<![CDATA[select a.owner,
a.table_name,
a.constraint_name,
a.status
from all_constraints a
where a.constraint_type = 'R'
and exists(
select 1
from all_constraints
where constraint_name=a.r_constraint_name
and constraint_type in ('P', 'U')
and table_name = :OBJECT_NAME
and owner = :OBJECT_OWNER)
order by table_name, constraint_name]]>
</sql>
</query>
</item>
2.Add the USER DEFINED extension to SQL Developer
Tools > Preferences
Database > User Defined Extensions
Click "Add Row" button
In Type choose "EDITOR", Location - where you saved the xml file above
Click "Ok" then restart SQL Developer
3.Navigate to any table and you will be able to see an additional tab next to SQL, labelled FK References, displaying FK information.
4.Reference
http://www.oracle.com/technetwork/issue-archive/2007/07-jul/o47sql-086233.html
How can I find which tables reference a given table in Oracle SQL Developer?
To find the Orphan records in all referred tables
select * from CHILD_TABLE
where FOREIGNKEY not in (select PRIMARYKEY from PARENT_TABLE);
Delete these Orphan records, Commit the changes and restart the server if required.
This solved my exception. You may try the same.
Please update your hibernate configuration file as given below:
property start tag name="hbm2ddl.auto" create/update property close tag
I have found that in Oracle this problem can also be caused by a permissions issue. The ProblemClass instance referred to by the MyDbObject instance may exist but have permissions that do not allow the current user to see it, even though the user can see the current MyDbObject.