19 Eylül 2018 Çarşamba

Configuration Sınıfı - hibernate.cfg.xml Dosyasını Yükler

Giriş
Şu satırı dahil ederiz.
import org.hibernate.cfg.Configuration;
hibernate.properteis veya hibernate.cfg.xml dosyasını okuyarak SessionFactory nesnesi yaratır.
Bu sınıf bir ara AnnotationConfiguration olarak bölündü ancak daha sonra tüm işlev tekrar bu sınıfta toplandı.

Kullanım
hibernate.properties dosyasını okumak için eski kodlarda şu çağrılar yapılır.
constructor() -> addDirectory() -> buildSessionFactory ()
hibernate.cfg.xml dosyasını okumak için yeni kodlarda şu çağrılar yapılır
constructor() -> configure() -> addDirectory() -> buildSessionFactory ()
Örnek
src/main/resources/test-hibernate-client.cfg.xml dosyasını yüklemek için şöyle yaparız
SessionFactory createSessionFactory(Properties props) {
  Configuration conf = new Configuration();
  conf.configure(Foo.class.getClassLoader().getResource("test-hibernate-client.cfg.xml"));
  conf.addAnnotatedClass(Foo.class);
  conf.addProperties(props);

  SessionFactory sessionFactory = conf.buildSessionFactory();
  sessionFactory.getStatistics().setStatisticsEnabled(true);
  return sessionFactory;
}

constructor
hibernate.properties dosyasını yükler
Örnek
Şöyle yaparız.
Configuration cfg =new Configuration();
Örnek
Dosya yüklendiği için şöyle yapabiliriz.
Properties properties = configuration.getProperties();
addAnnotatedClass metodu
Örnek
Şöyle yaparız.
new Configuration().configure("hibernateUser.cfg.xml")
 .addAnnotatedClass(AppUser.class)
 .buildSessionFactory();
Örnek
Şöyle yaparız.
sessionFactory = new Configuration()
  .configure()
  .addAnnotatedClass(Seller.class)
  .addAnnotatedClass(Book.class)
  .buildSessionFactory();
addClass metodu
Tüm yolu belirtilen belirtilen sınıfa ait hbm.xml dosyasını ekler.

addDirectory metodu
hbm.xml dosyalarını içeren dizinleri belirtir. Bu dizinler taranarak dosyalar yüklenir.

addPackage metodu
İnsanın aklı Spring'e gidiyor ancak bu metod ismi belirtilen paketteki sınıfları taramaz. Sınıfları eklemek için şöyle yaparız.

addURL metodu
hbm.xml dosyası jar içindeyse eklemek için kullanılır.

buildSessionFactory metodu - Eski
Bu metodu kullanmamak lazım.
Örnek
Şöyle yaparız.
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();

Örnek
Şöyle yaparız.
sqlProps.put("hibernate.connection.driver_class", "org.h2.Driver");
sqlProps.put("hibernate.hbm2ddl.auto", "update");
sqlProps.put("hibernate.connection.url", "jdbc:h2:test;CIPHER=AES");
sqlProps.put("hibernate.connection.username", "TEST");

sqlProps.put("hibernate.connection.password", "testAES test");
sqlProps.put("hibernate.dialect", "org.hibernate.dialect.H2Dialect");

//Pooling
sqlProps.put("hibernate.c3p0.min_size", "5");
sqlProps.put("hibernate.c3p0.max_size", "20");
sqlProps.put("hibernate.c3p0.timeout", "300");
sqlProps.put("hibernate.c3p0.max_statements", "50");
sqlProps.put("hibernate.c3p0.idle_test_period", "3000");
sqlProps.put("hibernate.temp.use_jdbc_metadata_defaults", "false");

org.hibernate.cfg.Configuration cfg =
  new org.hibernate.cfg.Configuration()
    .addAnnotatedClass(Apartment.class)
    .addAnnotatedClass(Housing.class)
    .addAnnotatedClass(Landlord.class)
    .addAnnotatedClass(Tenant.class)
    .addAnnotatedClass(Transaction.class)
    .mergeProperties(sqlProps);

SessionFactory sessionFactory = cfg.buildSessionFactory();

buildSessionFactory metodu - ServiceRegistry
Örnek
Şöyle yaparız.
private static SessionFactory buildSessionFactory() {
  try {
    Configuration configuration = new Configuration();
    ServiceRegistry serviceRegistry
            = new StandardServiceRegistryBuilder()
                .applySettings(configuration.getProperties()).build();
    configuration.addAnnotatedClass(LookUpModel.class);
    return configuration
           .buildSessionFactory(serviceRegistry);
  }catch(Exception e) {
    e.printStackTrace();
    throw new RuntimeException("There is issue in hibernate util");
  }
}
Örnek

Şöyle yaparız.
configuration.buildSessionFactory(
    new StandardServiceRegistryBuilder()
        .applySettings(configuration.getProperties())
        .build()
);

Örnek
Şöyle yaparız.
SessionFactory sf = new Configuration().configure().buildSessionFactory(
            new StandardServiceRegistryBuilder().build() );
configure metodu 
resources dizininde hibernate.cfg.xml dosyası bulunur. hibernate.cfg.xml dosyasını yükler.
Örnek
Şöyle yaparız.
Configuration configuration = new Configuration().configure();
Örnek
Şöyle yaparız.
// Create the SessionFactory from standard (hibernate.cfg.xml) config file.
SessionFactory sessionFactory = new Configuration().configure().buildSessionFactory();
configure metodu - String
Belirtilen dosyayı okur

Örnek
Şöyle yaparız.
Configuration configuration=new Configuration().configure("myhibernate.cfg.xml");
SessionFactory sessionFactory=configuration.buildSessionFactory();`
Dosya şöyledir. Hibernate xml dosyası şöyledir.

generateDropSchemaScript metodu
Bu metod Hibernate 5 ile silindi.

generateSchemaCreationScript metodu
Bu metod Hibernate 5 ile silindi.

setProperties metodu
Kullanılacak değerler java.util.Properties sınıfı ile belirtilir.

hibernate.properties Dosyası - Kullanmayın

Giriş
Bu dosyada Hibernate'in çalışması için gerekli ayarlar bulunur. Ayarlar SessionCache vs gibi şeylerle ilgilidir. Bu dosyanın xml olarak tutulan hali hibernate.cfg.xml dosyasıdır.

Bu dosya kodlarken src/main/resources dizini altına yerleştirilir.

18 Eylül 2018 Salı

Hibernate Hikari

Giriş
Maven'a dependency'leri ekledikten sonra bir ayar yapmaya gerek yok. Hikari varsayılan ayarlar ile açılıyor.

HikariCPConnectionProvider sınıfı org.hibernate.service.spi.Configurable arayüzünü gerçekleştirdiği için Hibernate otomatik olarak bu sınıfı ilklendiriyor.

Örnek
hibernate.properties dosyasında şöyle yaparız.
hibernate.connection.provider_class=
  org.hibernate.hikaricp.internal.HikariCPConnectionProvider

14 Eylül 2018 Cuma

Hibernate 5 ve Java 8 java.time Sınıfları

Giriş
Tablo şöyle. Java 8 ile gelen bu sınıflar JPA 2.2 ile desteklenecek ancal Hibernate JPA 2.2'den önce desteklemeye başladı. Açıklaması şöyle.
Hibernate 5 natively supports the java 8 Date/Time APIs. Just ensure that the hibernate-java8 jar is on your class path.

Java Type               JDBC Type
java.time.Duration                BIGINT
java.time.Instant                TIMESTAMP
java.time.LocalDateTime TIMESTAMP
java.time.LocalDate         DATE
java.time.LocalTime        TIME
java.time.OffsetDateTime     TIMESTAMP
java.time.OffsetTime        TIME
java.time.ZonedDateTime IMESTAMP

12 Eylül 2018 Çarşamba

Second Level Cache

Giriş
Second Level Cache ile veri ehcache, Hazelcast gibi bir cache sağlayıcısı üzerinde saklanır

Java Serialization Kullanır
Açıklaması şöyle.
No Custom serialization - Memory intensive
If you use second level caching you would not be able to use fast serialization frameworks as Kryo and will have to stick to java serializeable which sucks.

On top of this for each entity type you will have a separate region and within each region you will have entry for each key of each entity. In terms of memory efficiency this is inefficient.
Entity'ler Id Alanı İle Saklanır
Açıklaması şöyle.
Using 2nd level cache is easier to setup but it only stores entities by id. There is also a query cache, storing ids returned by a given query. So the 2nd level cache is a two step process that you need to fine tune to get the best performance. When you execute projection queries the 2nd level object cache won't help you, since it only operates on entity load. The main advantage of 2nd level cache is that it's easier to keep it in sync whenever data changes, especially if all your data is persisted by hibernate.