Last active
October 22, 2016 23:57
-
-
Save thergbway/0a68550a27668ce571e7c72cf6e6078f to your computer and use it in GitHub Desktop.
HIBERNATE&JPA. NATIVE HIBERNATE CONFIGURATION
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
1. Hibernate modules: | |
* hibernate-core. Core module. Defines its ORM features and APIs as well as the various integration SPIs. | |
* hibernate-entitymanager. Defines Hibernate’s support for JPA. | |
* hibernate-java8. Support for using Java8 specific data-types such as any of the JSR 310 Date/Time types. | |
* hibernate-envers. Hibernate’s historical entity versioning feature. | |
* hibernate-spatial. Hibernate’s Spatial/GIS data-type support. | |
* hibernate-osgi. Hibernate support for running in OSGi containers. | |
* hibernate-c3p0. Integrates the C3P0 connection pooling library into Hibernate. | |
* hibernate-hikaricp. Integrates the HikariCP connection pooling library into Hibernate. | |
* hibernate-proxool. Integrates the Proxool connection pooling library into Hibernate. | |
* hibernate-jcache. Integrates the JCache caching specification into Hibernate, | |
enabling any compliant implementation to become a second-level cache provider. | |
* hibernate-ehcache. Integrates the Ehcache caching library into Hibernate as a second-level cache provider. | |
* hibernate-infinispan. Integrates the Infinispan caching library into Hibernate as a second-level cache provider. | |
2. Особенности классов для маппинга: | |
* id | |
* конструктор по умолчанию. Мб private, но это задействует обработку байткода. С public/private конструктором | |
будет создан прокси | |
* Serializable не нужен Hibernate, но может пригодится другим фреймворкам | |
* Getters, Setters and private fields are NOT required but it is a recommended design | |
3. Популярные диалекты: | |
* org.hibernate.dialect.PostgreSQL82Dialect | |
* org.hibernate.dialect.H2Dialect | |
* org.hibernate.dialect.MySQL5Dialect | |
* org.hibernate.dialect.OracleDialect | |
* org.hibernate.dialect.SybaseDialect | |
* org.hibernate.dialect.SQLServerDialect | |
* org.hibernate.dialect.HSQLDialect | |
* org.hibernate.dialect.DerbyDialect | |
4. Если БД не поддерживает последовательности, то используй GenerationType.AUTO(по умолчанию) | |
5. Native Hibernate требует - {org.hibernate -> hibernate-core -> ${hibernate-version}} | |
JPA Hibernate - {org.hibernate -> hibernate-entitymanager -> ${hibernate-version}}. | |
Необходимо выбрать одно | |
6. hbm2ddl.auto: | |
* validate. Проверяет схему, БД не изменяет. Лучший вариант для продакшена | |
* update. Обновляет схему (рискованный вариант для продакшена) | |
* create. Удаляет таблицы при старте, затем создает нужные | |
* create-drop. Создает таблицы на старте, удаляет таблицы при закрытии SessionFactory | |
* none. Недокументированная. Отключает данный функционал. | |
* пустая строка. Мб тоже, что и none. Некоторые пишут, что лучше, чем none | |
! Документация по значениям: http://docs.jboss.org/hibernate/orm/5.0/javadocs/org/hibernate/boot/SchemaAutoTooling.html | |
7. Файлы с возможными параметрами Hibernate и JPA: | |
* org.hibernate.cfg.AvailableSettings для Hibernate | |
* org.hibernate.cfg.Environment для Hibernate | |
* org.hibernate.jpa.AvailableSettings для JPA |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0"?> | |
<!DOCTYPE hibernate-mapping PUBLIC | |
"-//Hibernate/Hibernate Mapping DTD 3.0//EN" | |
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> | |
<hibernate-mapping package="intro"> | |
<class name="intro.Book" table="BOOKS"> | |
<id name="id" column="BOOK_ID"> | |
<generator class="increment"/> | |
</id> | |
<property name="date" type="timestamp" column="BOOK_DATE"/> | |
<property name="title"/> | |
</class> | |
</hibernate-mapping> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package intro; | |
import lombok.AllArgsConstructor; | |
import lombok.Data; | |
import lombok.NoArgsConstructor; | |
import java.util.Date; | |
@Data | |
@AllArgsConstructor | |
@NoArgsConstructor | |
public class Book { | |
private Long id; | |
private String title; | |
private Date date; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package intro; | |
import lombok.AllArgsConstructor; | |
import lombok.Data; | |
import lombok.NoArgsConstructor; | |
import org.hibernate.annotations.GenericGenerator; | |
import javax.persistence.*; | |
import java.util.Date; | |
@Data | |
@AllArgsConstructor | |
@NoArgsConstructor | |
@Entity | |
@Table(name = "CARS") | |
public class Car { | |
@Id | |
@GeneratedValue(generator = "increment") | |
@GenericGenerator(name = "increment", strategy = "increment") | |
private Long id; | |
private String title; | |
@Temporal(TemporalType.TIMESTAMP) | |
@Column(name = "CAR_DATE") | |
private Date date; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version='1.0' encoding='utf-8'?> | |
<!DOCTYPE hibernate-configuration PUBLIC | |
"-//Hibernate/Hibernate Configuration DTD 3.0//EN" | |
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> | |
<hibernate-configuration> | |
<session-factory> | |
<property name="connection.driver_class">org.h2.Driver</property> | |
<property name="connection.url">jdbc:h2:mem:db1;DB_CLOSE_DELAY=-1;MVCC=TRUE</property> | |
<property name="connection.username">sa</property> | |
<property name="connection.password"/> | |
<property name="connection.pool_size">1</property> | |
<property name="dialect">org.hibernate.dialect.H2Dialect</property> | |
<property name="cache.provider_class">org.hibernate.cache.internal.NoCachingRegionFactory</property> | |
<property name="show_sql">true</property> | |
<property name="hbm2ddl.auto">create</property> | |
<!--Через XML--> | |
<mapping resource="Book.hbm.xml"/> | |
<!--Через аннотации--> | |
<mapping class="intro.Car"/> | |
</session-factory> | |
</hibernate-configuration> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd"> | |
<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"> | |
<appender name="stdout" class="org.apache.log4j.ConsoleAppender"> | |
<param name="Target" value="System.out"/> | |
<layout class="org.apache.log4j.PatternLayout"> | |
<param name="ConversionPattern" value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n"/> | |
</layout> | |
</appender> | |
<!--Turn on your favourite loggers--> | |
<logger name="org.hibernate"> | |
<level value="INFO"/><!--or DEBUG for more verbose logging--> | |
</logger> | |
<logger name="org.hibernate.SQL"> | |
<level value="INFO"/> | |
</logger> | |
<root> | |
<level value="WARN"/> | |
<appender-ref ref="stdout"/> | |
</root> | |
</log4j:configuration> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package intro; | |
import org.apache.log4j.Logger; | |
import org.hibernate.Session; | |
import org.hibernate.SessionFactory; | |
import org.hibernate.Transaction; | |
import org.hibernate.cfg.Configuration; | |
import java.util.Date; | |
import java.util.Objects; | |
public class Main { | |
private static final Logger log = Logger.getLogger(Main.class); | |
public static void main(String[] args) { | |
SessionFactory sessionFactory = null; | |
Session session = null; | |
Transaction tx = null; | |
try { | |
Configuration cfg = new Configuration(); | |
cfg.configure("hibernate.cfg.xml"); | |
sessionFactory = cfg.buildSessionFactory(); | |
session = sessionFactory.openSession(); | |
tx = session.beginTransaction(); | |
session.save(new Book(null, "First book", new Date())); | |
session.save(new Book(null, "Second book", new Date())); | |
session.save(new Car(null, "First car", new Date())); | |
session.save(new Car(null, "Second car", new Date())); | |
tx.commit(); | |
session.close(); | |
session = sessionFactory.openSession(); | |
tx = session.beginTransaction(); | |
session.createQuery("from Book", Book.class).list().forEach(System.out::println); | |
session.createQuery("from Car", Car.class).list().forEach(System.out::println); | |
tx.commit(); | |
} catch (Exception e) { | |
log.error("Got error!", e); | |
if (Objects.nonNull(tx) && tx.isActive()) | |
tx.rollback(); | |
} finally { | |
if (Objects.nonNull(session)) | |
session.close(); | |
if (Objects.nonNull(sessionFactory)) | |
sessionFactory.close(); | |
} | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="UTF-8"?> | |
<project xmlns="http://maven.apache.org/POM/4.0.0" | |
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | |
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> | |
<modelVersion>4.0.0</modelVersion> | |
<groupId>org.thergbway</groupId> | |
<artifactId>native_hb</artifactId> | |
<version>1.0-SNAPSHOT</version> | |
<properties> | |
<maven.compiler.source>1.8</maven.compiler.source> | |
<maven.compiler.target>1.8</maven.compiler.target> | |
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> | |
</properties> | |
<dependencies> | |
<dependency> | |
<groupId>com.h2database</groupId> | |
<artifactId>h2</artifactId> | |
<version>1.4.192</version> | |
</dependency> | |
<dependency> | |
<groupId>postgresql</groupId> | |
<artifactId>postgresql</artifactId> | |
<version>9.1-901-1.jdbc4</version> | |
</dependency> | |
<dependency> | |
<groupId>junit</groupId> | |
<artifactId>junit</artifactId> | |
<version>4.12</version> | |
</dependency> | |
<dependency> | |
<groupId>org.slf4j</groupId> | |
<artifactId>slf4j-log4j12</artifactId> | |
<version>1.7.21</version> | |
</dependency> | |
<dependency> | |
<groupId>com.mchange</groupId> | |
<artifactId>c3p0</artifactId> | |
<version>0.9.5.2</version> | |
</dependency> | |
<dependency> | |
<groupId>org.javassist</groupId> | |
<artifactId>javassist</artifactId> | |
<version>3.20.0-GA</version> | |
</dependency> | |
<dependency> | |
<groupId>org.hibernate</groupId> | |
<artifactId>hibernate-core</artifactId> | |
<version>5.2.3.Final</version> | |
</dependency> | |
<dependency> | |
<groupId>org.hibernate</groupId> | |
<artifactId>hibernate-ehcache</artifactId> | |
<version>5.2.3.Final</version> | |
</dependency> | |
<dependency> | |
<groupId>org.hibernate</groupId> | |
<artifactId>hibernate-validator</artifactId> | |
<version>5.2.4.Final</version> | |
</dependency> | |
<dependency> | |
<groupId>net.sf.ehcache</groupId> | |
<artifactId>ehcache-core</artifactId> | |
<version>2.6.11</version> | |
</dependency> | |
<dependency> | |
<groupId>org.projectlombok</groupId> | |
<artifactId>lombok</artifactId> | |
<version>1.16.10</version> | |
</dependency> | |
</dependencies> | |
<build> | |
<plugins> | |
<plugin> | |
<groupId>org.apache.maven.plugins</groupId> | |
<artifactId>maven-clean-plugin</artifactId> | |
<version>3.0.0</version> | |
<executions> | |
<execution> | |
<id>auto-clean</id> | |
<phase>initialize</phase> | |
<goals> | |
<goal>clean</goal> | |
</goals> | |
</execution> | |
</executions> | |
</plugin> | |
<plugin> | |
<groupId>org.apache.maven.plugins</groupId> | |
<artifactId>maven-compiler-plugin</artifactId> | |
<version>3.5.1</version> | |
<configuration> | |
<source>${maven.compiler.source}</source> | |
<target>${maven.compiler.target}</target> | |
</configuration> | |
<executions> | |
<execution> | |
<goals> | |
<goal>compile</goal> | |
</goals> | |
</execution> | |
</executions> | |
</plugin> | |
</plugins> | |
</build> | |
</project> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment