#OneToMany Column not showing? - spring

I am new to Hibernate and curious, why my column is not showing.
So I have following code (in kotlin):
#Entity
class Project (
var guid: String = "",
#OneToMany(mappedBy = "project", cascade = [CascadeType.ALL])
var tickets: List<Ticket?>,
var current: Date
){
#Id #GeneratedValue(strategy = GenerationType.AUTO)
var id: Long = 0
}
and the other entity:
#Entity
class Ticket (
var guid: String = "",
#ManyToOne
#JoinColumn(name="project_id")
var project: Project?,
var current: Date
){
#Id #GeneratedValue(strategy = GenerationType.AUTO)
var id: Long = 0
}
In my database, the table "ticket" has a column project_id, with null values.
BUT my other table "Project" has no column for the list of Tickets. What went wrong? Every help will be appreciated, please dont forget to explain.
Thank you!

The reason your Project table has no column for the list of tickets, is that relational databases are designed to have one value per cell. You cannot store a list or array of something in a table. The solution for this is to create another table (let's call it the child table) that references this table (the parent table). Each row in the child table will be one entry of that list, and stores a reference to the parent list. So in a way, the relationship has been inverted: instead of storing the tickets in the Project table, a reference to the Project table is stored in the Ticket table.
In your case, you're indicating that the project_id should be used as a reference, since you're mentioning it in the #JoinColumn. However, there is no such property in the Project table, so you should add it. Hibernate is expecting that this is the column to link the two tables.
Also: don't forget to create a foreign key constraint to the parent table on the column that you're using in the Ticket table either.

Related

Schema-validation: wrong column type encountered in column [name] in table [testTable]

i'm getting this error while starting my springboot application:
Schema-validation: wrong column type encountered in column [name] in table [testTable];
found [character (Types#VARCHAR)], but expecting [clob (Types#CLOB)]
Other people of my team can run it just fine, but it doesn't work for me.
This is my class:
#Entity
#Table(name = "testTable")
data class TestTable(
#Id
val id: Long,
#Lob
#Column
val name: String,
#Column(nullable = false)
val parentId: Long,
I guess its a problem with mapping, but I don't understand why other people don't have the problem.
Thanks in advance.
Other people of your team probably use a different database schema. The error says that your model requires a CLOB column type (due to the use of #Lob), but the database column has the type VARCHAR. If you want to work with this schema, remove the #Lob annotation. Otherwise, migrate the column to CLOB: alter table testTable alter column name set data type clob

How to migrate [DDL] from generation type identity to generation type sequence for postgres db

As of now I am generating id using
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
the sequence generated in DB is like:
CREATE SEQUENCE public.table_name_id_seq
START WITH 1
INCREMENT BY 1
NO MINVALUE
NO MAXVALUE
CACHE 1;
ALTER SEQUENCE public.table_name_id_seq OWNED BY public.table_name.id;
ALTER TABLE ONLY public.table_name ALTER COLUMN id SET DEFAULT``nextval('public.table_name_id_seq'::regclass);
or at some places in definition itself:
CREATE TABLE "public.table_name" (
"id" int8 NOT NULL DEFAULT nextval('table_name_id_seq'::regclass),
"some_column" varchar(255),
PRIMARY KEY ("id")
);
I am using hibernate as JPA provider, I needed to enable insert and update batching due to which I want to change the generation type to SEQUENCE from IDENTITY.
After changing to generation type sequence [in hibernate] and using older sequence [of postgres] i see weird id being generated. This is not the expected behavior.
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "table_name_id_seq ")
private Long id;
The ids which are highlighted in yellow is created after using generation type sequence. I was expecting id after 23 to be 24 and not -22.
How can I fix this? How can I smoothly shift from IDENTITY to SEQUENCE? What is the proper DDL?
Answering to this part of your question:
How can I smoothly shift from IDENTITY to SEQUENCE? What is the proper DDL?
You should do the following things:
Drop the default value from the table_name.id column:
alter table only table_name
alter column id drop default;
Correct your mapping for the id field:
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "my_generator")
#SequenceGenerator(name = "my_generator", sequenceName = "table_name_id_seq", allocationSize = 1)
private Long id;
Please note that an allocationSize should be equal to the INCREMENT BY of your sequence definition.

Hibernate insert with id generation on insert trigger with sequence

Here my problem, I have a sequence in my oracle database and a trigger on insert to fetch the next value from the sequence and put it as id. With a tool like sql developer, it works perfectly.
My id is defined at this
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "MY_SEQUENCE")
#SequenceGenerator(sequenceName = "MY_SEQUENCE", allocationSize = 1, name = "MY_SEQUENCE")
private BigInteger jobId;
The problem is hibernate firstly read the next value of the sequence, set it as the id and then persist it. Then my database update my id with the next value of the sequence but that new id isn't "updated" in my code after my .save(entity).
I read that I should use the GenerationType.IDENTITY but I would like to do batch inserts and I also read that with IDENTITY the batch inserts is not possible.
If possible, I would like to keep my trigger so like that hibernate doesn't have to call the database each time I insert and be able to do batch inserts.
Edit: I'll probably need to insert near a million of rows

Spring Data/JPA PostgreSQL SequenceGenerator and duplicate primary keys on concurrent access to the same database

In my Spring Data/JPA project I use ProstgreSQL database.
I use a following mapping for my JPA entity PK on cards table:
#Id
#SequenceGenerator(name = "cards_id_seq", sequenceName = "cards_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.AUTO, generator = "cards_id_seq")
private Long id;
Everything works fine until some other applications or persons do not insert manually new records into this table. Once it happens my application fails with the following error:
Caused by: org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "cards_pkey"
Detail: Key (id)=(42) already exists.
when tries to insert records because of out of sync between PostgreSQL sequence object and actual PK IDs in the database.
What am I doing wrong and how to solve this situation in order to assign the correct IDs to new records inserted via my application ?

Issues updating record with Hibernate and Spring

I am having one-to-many relationship tables. When I insert records, the program inserts new records without any problem, but when I try to update the record by using saveOrUpdate(), the program does not work as my expectation. Only parent table (e.g., student) record is updated and new records inserted in the child table (e.g., studentaddress). As in the parent table, I need an update in child table too.
How to achieve this? Please help me. Following is the Hibernate tool-generated code:
Student Table
#OneToMany(fetch = FetchType.LAZY, mappedBy = "student",cascade=CascadeType.ALL)
Studentaddress Table
#ManyToOne(fetch = FetchType.LAZY) #JoinColumn(name = "student_id", nullable = false)
I have searched a lot but could not get any site relating to update but I have seen some sites for one table update. In my case, I want to update two tables.
try to add to student this
#org.hibernate.annotations.Cascade(org.hibernate.annotations.CascadeType.SAVE_UPDATE)

Resources