Problem whit add sequence in Oracle and Spring - spring

I get this error when I try add new record
Hibernate:
select
STEST_PP_DATA_SEQ.nextval
from
dual
2022-04-06 12:53:03.487 WARN 23884 --- [0.1-8082-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : SQL Error: 2289, SQLState: 42000
2022-04-06 12:53:03.510 ERROR 23884 --- [0.1-8082-exec-1] o.h.engine.jdbc.spi.SqlExceptionHelper : ORA-02289: sequence does not exist
My Class
#Data
#NoArgsConstructor
#AllArgsConstructor
#Entity(name = "TEST_PP_DATA")
#SequenceGenerator(name = "STEST_PP_DATA_SEQ", sequenceName = "STEST_PP_DATA_SEQ", initialValue = 1, allocationSize = 1)
public class TestPPData extends AuditableEntity{
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "STEST_PP_DATA_SEQ")
#Column(name = "ID", nullable = false)
This how I add sequence to my DB
CREATE SEQUENCE STEST_PP_DATA_SEQ INCREMENT BY 1 START WITH 1 NOMAXVALUE MINVALUE 1 NOCYCLE NOCACHE NOORDER

Probably you need to fully qualify the name. Can you try the following query to retrieve the owner:
SELECT owner, status
FROM All_Objects
WHERE object_type = 'SEQUENCE'
AND object_name = 'STEST_PP_DATA_SEQ';
and then use the sequence as:
select <OWNER>.STEST_PP_DATA_SEQ.nextval
from dual;
and if the first query doesn't return anything or the status is different from VALID, then you have a problem in your sequence creation.

Related

Hibernate, select where foreign key is null

I have entity as follows:
#Entity
#Table(name = "LORRY")
#NamedQueries({
#NamedQuery(name = "Lorry.findSuitableLorries",
query = "SELECT l from Lorry l " +
"WHERE l.order IS NULL")
})
public class Lorry {
#Id
#Column(name = "ID", length = 7)
#Pattern(regexp="[a-zA-Z]{2}\\d{5}")
#Size(min = 7, max = 7)
private String regNum;
#OneToOne(mappedBy = "lorry")
private Order order;
}
Now I need to select all rows where order id is null in the LORRY table, but it doesn't seem to work as I get empty list every time. How can I check if foreign key is null using JPQL?
Try either SELECT l from Lorry l WHERE l.order.id IS NULL or SELECT l from Lorry l left join l.order o WHERE o IS NULL

How to update row in table with condition is refer to another table

How can I update a table which the condition is refer to other table in spring jpa ?
I have table Task which relation to TaskProgress (many to one). And TaskProgress has some value eg: CREATE, INPROGRES, DONE, ARCHIVED,...
Here is my query in repostitory:
#Modifying
#Query("UPDATE Task t SET t.responsibleUser = null WHERE t.responsibleUser.id = :userId " +
"AND t.deleted = false AND t.taskProgress.name <> 'ARCHIVED'")
void removeResponsibleUserId(UUID userId);
But I got the error:
Hibernate: update task cross join set responsible_user_id=null where responsible_user_id=? and deleted=0 and name<>'ARCHIVED'
2020-11-25 00:38:51 - SQL Error: 1064, SQLState: 42000
2020-11-25 00:38:51 - 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 'set responsible_user_id=null where responsible_user_id=x'152B59C33A0035003500000' at line 1
Use an exists predicate like this:
#Modifying
#Query("UPDATE Task t SET t.responsibleUser = null WHERE t.responsibleUser.id = :userId " +
"AND t.deleted = false AND NOT EXISTS (SELECT 1 FROM t.taskProgress p WHERE p.name = 'ARCHIVED')")
void removeResponsibleUserId(UUID userId);

jhipster : unable to select specific columns

when i select 4 column an error occur :
Caused by: org.postgresql.util.PSQLException: The column name id was not found in this ResultSet.
#Query(value = "select name,rating,numberofviews,status from learningunit", nativeQuery = true)
List<Learningunit> findAllData();
then i add id to the query and the same error occur with different column and so on
#Query(value = "select id,name,rating,numberofviews,status from learningunit", nativeQuery = true)
List<Learningunit> findAllData();
Caused by: org.postgresql.util.PSQLException: The column name summary
was not found in this ResultSet.
notes:i using jhipster and ever entity has a dto and mapper
entity
DTO
Mapper
finally i solved the problem using this query #Query(value = "select null as id , name,rating,numberofviews,null as status from learningunit", nativeQuery = true)
the point is to select null as the name of your column

JPA/Hibernate map #OneToMany for Oracle hierarchical data

Say I have parent-child info in table Organization as followed:
id name parent_id
1 A 1
2 A1 1
3 A2 1
4 A11 2
With Oracle, I can get all descendants or ancestors of an organization using "start with/connect by". For example, the following sql will get all the subtree under "A" include itself (i.e. A, A1, A2, A11)
select * from Organization start with id=1 connect by nocycle prior id=parent_id;
Or this sql will get all ancestors of A11 including itself (i.e. A11, A1, A)
with o_hier as (select o.id, o.parent_id, CONNECT_BY_ISCYCLE as lvl from Organization o start with id=4 connect by nocycle prior parent_id = id) select o.* from Organization o, o_hier where o.id = o_hier.id union all select o.* from Organization o, o_hier where o.id = o_hier.parent_id and o_hier.lvl = 1;
Now I want to map this table into OrganizationEntity like this:
#Entity
#Table(name = "Organization")
public class OrganizationEntity {
//getter/setter omitted for readability
#Id
#Column(name = "ID")
private String id;
#Column(name = "NAME")
private String name;
#ManyToOne(fetch = FetchType.LAZY)
#???
List<OrganizationEntity> descendants = new ArrayList<>();
#ManyToOne(fetch = FetchType.LAZY)
#???
List<OrganizationEntity> ancestors= new ArrayList<>();
}
I'm aware of possible performance issue, but can we map something like this using Hibernate/JPA?
This is a tricky one. You can use standard parent and childern mappings.
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "ID")
OrganizationEntity parent;
#OneToMany(fetch = FetchType.LAZY)
#mappedBy(mappedBy="parent")
List<OrganizationEntity> childern;
And then use standard tree taversals algorithms to get all the ancestors (simple while loop) or all the descendants (some DFS variant, usually preorder).
Performace wise this wound be very slow.
Other, and better idea is just do the traversals within the database with CONNECT BY and then map the result set to objects. You can do that with pure JPA calls or Hibernate specific calls.

Hibernate + oracle sequence + trigger

I have a table with an index auto filled by a trigger that use a sequence (Oracle database)
CREATE TABLE A
(
IDS NUMBER(10) NOT NULL
)
CREATE OR REPLACE TRIGGER A_TRG
BEFORE INSERT
ON A REFERENCING NEW AS New OLD AS Old
FOR EACH ROW
BEGIN
:new.IDS := A_SEQ.nextval;
END A_TRG;
/
I have a matching Java class:
Class A {
#Id
#SequenceGenerator(name = "aSequence", sequenceName = "A_SEQ", allocationSize = 1)
#GeneratedValue(generator = "aSequence", strategy = GenerationType.SEQUENCE)
#Column(name = "IDS")
Long id;
...
}
When I try to persist an instance of A like this:
EntityTransaction transaction = entityManager.getTransaction();
transaction.begin();
A a = new A();
Long id = getHibernateTemplate().save(a);
transaction.commit();
I get this problem:
ID in code returned by the save call = "X"
ID in database = "X+1"
Is there a way to setup Hibernate to let the database trigger create the ID ?
Thanks
Reponse found at HIbernate issue with Oracle Trigger for generating id from a sequence
I need to adapt my trigger to run only if no ID is given:
CREATE OR REPLACE TRIGGER A_TRG
BEFORE INSERT
ON A REFERENCING NEW AS New OLD AS Old
FOR EACH ROW
WHEN (New.IDS is null) -- (1)
BEGIN
:new.IDS := A_SEQ.nextval;
END A_TRG;
/
(1) this line allow Hibernate to manually call A_SEQ.nextVal to set the ID and then bypass the trigger else Hibernate will get the nextval for uselessly because the trigger will always reset the ID calling nextval again
In your class B you have #GeneratedValue(generator = "preferenceSequence") which not defined in the example that you have, it should be #GeneratedValue(generator = "bSequence")
By default hibernate allocation size is 50 the B: IDS=50 seems to suggest the mapping is picking the wrong sequence.

Resources