Posts

Showing posts with the label Hiberbate

Spring jpa criteria example

 import jakarta.persistence.EntityManager; import jakarta.persistence.TypedQuery; import jakarta.persistence.criteria.CriteriaBuilder; import jakarta.persistence.criteria.CriteriaQuery; import jakarta.persistence.criteria.Join; import jakarta.persistence.criteria.Path; import jakarta.persistence.criteria.Predicate; import jakarta.persistence.criteria.Root; import java.math.BigDecimal; import java.time.LocalDate; import java.time.LocalDateTime; import java.time.Month; import java.util.List; import java.util.Objects; import org.springframework.data.jpa.domain.Specification; import org.springframework.stereotype.Component; @Component public class TransactionCriteria { private static final String TRANSACTION_POINT = "transactionPoint"; private static final String EARNED_POINTS = "earnedPoints"; private static final String CREATED_AT = "createdAt"; private static final String OPERATION_TYPE = "operationType"; private static final String CUSTOMER_ID = ...

AuditableDate for entities in jpa

 import jakarta.persistence.Column;  import jakarta.persistence.EntityListeners;  import jakarta.persistence.MappedSuperclass;  import java.io.Serial;  import java.io.Serializable;  import java.time.LocalDateTime;  import lombok.Getter;  import lombok.Setter;  import org.springframework.data.annotation.CreatedDate;  import org.springframework.data.annotation.LastModifiedDate;  import org.springframework.data.jpa.domain.support.AuditingEntityListener;    @Getter  @Setter  @MappedSuperclass  @EntityListeners(AuditingEntityListener.class)  public class AuditableDate implements Serializable {        @Serial      private static final long serialVersionUID = 1L;        @CreatedDate      @Column(updatable = false)      private LocalDateTime createdAt;        @LastModifiedDate      private Loc...

entity id sequence la generate olan zaman hibernate in bazaya select gondermesi

hibernate, entity id uchun sequence istifade ederken @GeneratedValue( generator = "USERS_ID_SEQ_GEN", strategy = GenerationType.SEQUENCE) @SequenceGenerator( name = "USERS_ID_SEQ_GEN", sequenceName = "USERS_ID_SEQ", allocationSize = 1)  her save etmezden qabag bazaya sequencein novbeti valuesunu oyrenmek uchun sorgu atir bu selectin sayini azaltmaq uchun allocationSize -i boyuk eded vermek olar. Onda her eded tamamlandiqda sorgu gonderilib novbeti tsikl oyrenilecek. Bunun menfisi odur ki, app restart olanda yeni save olunacaq entitylerin idsi bazadaki sonuncu id + allocation size a beraber olur. Yeni sonuncu id = 5 olanda restart gedibse , eger allocation = 50 dirse , onda yeniler 55den bashlayacaq.  selecti umumyetle legv etmek uchun, @GeneratedValue(strategy = GenerationType.IDENTITY) istifade ede bilerik. Bu zaman hibernate save olunacaq entitynin idsini bilmir ve id bazada yaradilir. Bunun menfisi odur ki, bulk i...

oracle pl/sql ve hibernate arasinda array tiplerle ishlemek

oracle pl/sql prosedurlarla ishleyerken bazada yaradilan custom array typelarla(base integer ve ya stringden ibaretdir) ishleyerken java terefde problem olur , HikaryDataSoruce da arraylar createArrayOf ile yaranir  , oracle ise ancaq createArray ile yaradilan array typelari qebul edir . bu problemi hell etmek uchun:     public OracleConnection getOracleConnection() {         Connection conn = oracleDb().getConnection();         return conn.unwrap(OracleConnection.class);     } Array prodCodes = getOracleConnection.createArray("BACK.T_STR_COLL", request.getProdCodes()); array i bazaya oturmemishden evvel OracleConnection u almaq lazimdir bunu da yuxarida olan kod ile almaq olur , daha sonra ui dan oturulen arrayi javada OracleConnectionun createArray metodu ile yaradib o formada bazaya oturmek lazimdir burada SimpleJdbcCall vasitesile oracle pl/sql proseduru chagirilir , nece chagirilmagi docda var: https://docs.spring.io/...

hibernateda entiyde array tipli objectlerle ishlemek uchun solution

bele case ola bilerki postgres bazada int ve ya string tipde array saxlansin . bu arrayla entityde hibernate vasitesile ishlemek uchun bir solution lazimdir  bunu uchun gradle da  implementation 'com.vladmihalcea:hibernate-types-52:2.7.0'    bu dependecy lazimdir bunun maven versiyasini da tapmaq olar . indi ise kod numunesine baxaq: @Entity(name = "Event") @Table(name = "event") @TypeDefs({     @TypeDef(         name = "string-array",         typeClass = StringArrayType.class     ),     @TypeDef(         name = "int-array",         typeClass = IntArrayType.class     ) }) public static class Event extends BaseEntity {     @Type( type = "string-array" )     @Column(         name = "sensor_names",         columnDefinition = "text[]"     )     private String[] sensorNames; ...

Hibernate and Application Performance

 hibernate 2 cur cache memory var: L1(Level bir) burada entitymanager a aiddir. bazadan gelen entityler cacheda saxlanir ve her entitymanagere xasdir L2(level 2) burada ise umumiyyetle EntityManagerFactory ye xidmet eden entiymanagerler arasinda shared cache memorydir ve level 1 den daha uzun muddetlidir level 2 cache i aktivleshdirmek uchun dependency elave edilir projecte ve 1-2 config edilir Javada 4 cur reference type var : https://dzone.com/articles/reference-types-java-part-1 Strong references. Soft references. Weak references. Phantom references entitymanager de weak referance var , ve o strongla muqayisede GC terefinden istenilen an siline biler ram lazim olsa. soft referance - strongdan zeif , weakdan gucludur ve GC onu ancaq en vacib hallarda sile biler, weak i her memory chatmiyanda sile biler ama softu ancaq outofmemory alacagi teqdirde silib ishlede biler ve soft un omru uzun olur . ve Level 2 cache da istifade edir bunu hibernate. burda da bele shey varki , LRU(last r...

Hibernate Projection approach in project

With using this approach we can get any of field of entity and this way is more efficient rather than get all entity fileds , example in below: @Repository public interface CompanyRepo extends JpaRepository<Company, Long> {     Integer countById(long id);     <T extends CompanyViewProtocol> Optional<T> findById(long id, Class<T> type); } public interface CompanyViewProtocol { } public interface ContactDetailView extends CompanyViewProtocol {     CompanyContactDetail getContactDetail(); } in there companyRepo.findById(1L,ContactDetailView.class)   gives us CompanyContactDetail 

make update process without setter methods with BeanUtils.copyProperties(source,target,editableColumns)

This is just code sample that is why some imports some injections are missed! import static com.company.project.util.EntityUtil.copyPropertiesExceptId;  public class OfficeServiceImpl implementes OfficeService{ public OfficePhoto update(Long companyId, Long officeId, Long id, OfficePhotoEditableColumn      officePhotoEditableColumn) throws EntityNotFountException {     OfficePhoto byId = findById(companyId, officeId, id);     copyPropertiesExceptId(byId, officePhotoEditableColumn, OfficePhotoEditableColumn.class);     return officePhotoRepo.save(byId); } } this method does update proses without using any setter methods: we just give (target,source,editableColumsObject) : public class EntityUtil{ public static void copyPropertiesExceptId(BaseEntity target, BaseEntity source, Class editableColumns) {     long targetOriginalId = target.getId();     BeanUtils.copyProperties(source, target, editableColumns);     ...

removing object from many side in @OneToMany relation

  @ManyToOne (fetch = FetchType. LAZY ) private Company company ; @PreRemove private void preRemove () { // Office silinmezden once Company ile olan elaqesini kesmek lazimdir this . company .getOffices().remove( this ) ; } using this @PreRemove in Office entity which is many side in @OneToMany relation adi halda silmeye chalisanda error verirki one terefi silinmeyine icaze vermir ona gore de bu annotation ile hell etmek olur problemi problemi bunnla hell etmek olar, amma bu yaxsi solutuon deyil , chunki eksine One da olan datani silmek isteyende ConcurrentMapp... nese qeribe error verir bunun evezine , burda bash veren emelyati delete metodunda etmek lazimdir

HIbernate Configuration for Mysql Server in Maven project

Configuration Hibernate for Mysql in Maven project: in pom.xml: dependency For mysql server <dependency>             <groupId>mysql</groupId>             <artifactId>mysql-connector-java</artifactId>             <version>5.1.48</version>   </dependency>       Hibernate dependecies:         <dependency>             <groupId>org.hibernate</groupId>             <artifactId>hibernate-entitymanager</artifactId>             <version>5.4.10.Final</version>  </dependency>    ...