26 Ağustos 2022 Cuma

JPA AUTO identifier GeneratorType - Varsayılan Yöntem

Giriş
Açıklaması şöyle. Yani aslında JPA ile gelen SEQUENCE veya TABLE yöntemlerinden birisini seçiyor.
The AUTO generation strategy is the default, and this setting simply chooses the primary key generation strategy that is the default for the database in question, which quite typically is IDENTITY, although it might be TABLE or SEQUENCE depending upon how the database is configured. The AUTO strategy is typically recommended, as it makes your code and your applications most portable.
Ancak Hibernate ile burada bir problem var. Açıklaması şöyle. Yani mümkünse SEQUENCE kullanmaya çalışır. Ancak SEQUENCE yoksa TABLE yöntemini kullanır
According to the developer’s manual, if we use an ID type different from UUID (such as Long, Integer, etc.) and set the strategy to AUTO, Hibernate will do the following (since version 5.0):

 - Try to use the SEQUENCE ID generation strategy
- If sequences are not supported (i.e., we use MySQL), it will use TABLE (or IDENTITY, prior to Hibernate 5.0) strategy for ID generation
Hibernate için bu tablonun ismi hibernate_sequence.
Örnek
Post nesnesini kaydederken çıktısı şöyle. Burada hibernate_sequence tablosu üzeriden bir sürü işlem yapılıyor
@Entity
@Table(name = "post")
public class Post {
 
    @Id
    @GeneratedValue(strategy=GenerationType.TABLE)
    private Long id;
}   

SELECT tbl.next_val FROM hibernate_sequences tbl
WHERE tbl.sequence_name=default
FOR UPDATE
 
INSERT INTO hibernate_sequences (sequence_name, next_val)
VALUES (default, 1)
 
UPDATE hibernate_sequences SET next_val=2
WHERE next_val=1 AND sequence_name=default
 
SELECT tbl.next_val FROM hibernate_sequences tbl
WHERE tbl.sequence_name=default
FOR UPDATE
 
UPDATE hibernate_sequences SET next_val=3 
WHERE next_val=2 AND sequence_name=default

 
INSERT INTO post (id) values (1, 2)
Alan Tipi
Eğer bu seçeneği kullanıyorsak alan tipinin primitive bir tip yerine (long, int vs.) wrapper bir tip olmasına (Long, Integer vs.) dikkat etmek gerekir. Açıklaması şöyle
... it is recommended to use object types instead of primitives .... There is no way of distinguishing if the entity is new or pre existing with a primitive identifier.
Örnek - Kullanmayın
Şöyle yaparız. Bu yöntemin TABLE'a dönüşebilme ihtimali var ve performansı düşürebiliyor. Açıklaması yukarıda var
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "room_id")
private Integer id;
Örnek - Kullanın
Şöyle yaparız
@Id
@GeneratedValue(strategy= GenerationType.AUTO, generator="native")
@GenericGenerator(name = "native", strategy = "native")
private Long id;



Hiç yorum yok:

Yorum Gönder