Руководство по Hibernate. Руководство по Hibernate
![]()
|
Аннотации.Во всех предыдущих примерах мы использовали конфигурационные XML – файлы для конфигурирования Hibernate. В этих XML – файлах мы указывали Hibernate с какой таблицей в нешей базе данных (далее – БД) необходимо связать тот или иной POJO – класс и к каким колонкам относятся те или иные поля в этом классе. Но в Hibernate предусмотрена возможность конфигурирования прилоения с помощью аннотаций. Аннотации являются мощным иструментом для предоставления метаданных, а также намного нагляднее при чтении нашего кода другим разработчиком. Обязательными аннотациями являются следующие: @Entity Эта аннотация указывает Hibernate, что данный класс является сущностью (entity bean). Такой класс должен иметь конструктор по-умолчанию (пустой конструктор). @Table С помощью этой аннотации мы говорим Hibernate, с какой именно таблицей необходимо связать (map) данный класс. Аннотация @Table имеет различные аттрибуты, с помощью которых мы можем указать имя таблицы, каталог, БД и уникальность столбцов в таблец БД. @Id С помощью аннотации @Id мы указываем первичный ключ (Primary Key) данного класса. @GeneratedValue Эта аннотация используется вместе с аннотацией @Id и определяет такие паметры, как strategy и generator. @Column Аннотация @Column определяет к какому столбцу в таблице БД относится конкретное поле класса (аттрибут класса). Наиболее часто используемые аттрибуты аннотации @Column такие: name Указывает имя столбца в таблице unique Определяет, должно ли быть данное значение уникальным nullable Определяет, может ли данное поле быть NULL, или нет. length Указывает, какой размер столбца (например количество символов, при использовании String). Для понимания того, как это работает на практике, рассмотрим пример небольшого приложения. Пример: Шаг 1. Создадим таблцу в нашей БД. HIBERNATE_DEVELOPERS CREATE TABLE HIBERNATE_DEVELOPERS( ID INT NOT NULL AUTO_INCREMENT, FIRST_NAME VARCHAR(50) DEFAULT NULL, LAST_NAME VARCHAR(50) DEFAULT NULL, SPECIALTY VARCHAR(50) DEFAULT NULL, EXPERIENCE INT DEFAULT NULL, PRIMARY KEY(ID) ); Шаг 2. Создадим POJO – класс. Developer.java package net.proselyte.hibernate.annotations; import javax.persistence.*; @Entity @Table(name = "HIBERNATE_DEVELOPERS") public class Developer { @Id @GeneratedValue (strategy = GenerationType.AUTO) @Column (name = "id") private int id; @Column (name = "FIRST_NAME") private String firstName; @Column (name = "LAST_NAME") private String lastName; @Column (name = "SPECIALTY") private String specialty; @Column (name = "EXPERIENCE") private int experience; /** * Default Constructor */ public Developer() { } /** * Plain constructor */ public Developer(String firstName, String lastName, String specialty, int experience) { this.firstName = firstName; this.lastName = lastName; this.specialty = specialty; this.experience = experience; } /** * Getters and Setters */ public int getId() { return id; } public void setId(int id) { this.id = id; } public String getFirstName() { return firstName; } public void setFirstName(String firstName) { this.firstName = firstName; } public String getLastName() { return lastName; } public void setLastName(String lastName) { this.lastName = lastName; } public String getSpecialty() { return specialty; } public void setSpecialty(String specialty) { this.specialty = specialty; } public int getExperience() { return experience; } public void setExperience(int experience) { this.experience = experience; } /** * toString method (optional) */ @Override public String toString() { return "Developer:\n" + "id: " + id + "\nFirst Name: " + firstName + "\n" + "Last Name: " + lastName + "\n" + "Specialty: " + specialty + "\n" + "Experience: " + experience + "\n"; } } Шаг 3. Создадим конфигурационные файлы hibernate.cfg.xml "http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd"> org.hibernate.dialect.MySQLDialect com.mysql.jdbc.Driver jdbc:mysql://localhost/ИМЯ_ВАШЕЙ_БД ВАШЕ_ИМЯ_ПОЛЬЗОВАТЕЛЯ ВАШ_ПАРОЛЬ Developer.hbm.xml "-//Hibernate/Hibernate Mapping DTD//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd"> This class contains developer details. Шаг 4. Создадим класс DeveloperRunner.java DeveloperRunner.java package net.proselyte.hibernate.annotations; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.Transaction; import org.hibernate.cfg.Configuration; import java.util.List; public class DeveloperRunner { private static SessionFactory sessionFactory; public static void main(String[] args) { sessionFactory = new Configuration().configure().buildSessionFactory(); DeveloperRunner developerRunner = new DeveloperRunner(); System.out.println("Adding Developer's records to the database"); Integer developerId1 = developerRunner.addDeveloper("Proselyte", "Developer", "Java Developer", 2); Integer developerId2 = developerRunner.addDeveloper("Some", "Developer", "C++ Developer", 2); Integer developerId3 = developerRunner.addDeveloper("Peter", "Team Lead", "Java Team Lead", 6); System.out.println("List of Developers:"); developerRunner.listDevelopers(); System.out.println("Removing \'Some Developer\' and updating \'Proselyte Developer\''s experience:"); developerRunner.removeDeveloper(developerId2); developerRunner.updateDeveloper(developerId1, 3); System.out.println("Final list of Developers:"); developerRunner.listDevelopers(); sessionFactory.close(); } public Integer addDeveloper(String firstName, String lastName, String specialty, int experience) { Session session = sessionFactory.openSession(); Transaction transaction = null; Integer developerId = null; transaction = session.beginTransaction(); Developer developer = new Developer(firstName, lastName, specialty, experience); developerId = (Integer) session.save(developer); transaction.commit(); session.close(); return developerId; } public void listDevelopers() { Session session = sessionFactory.openSession(); Transaction transaction = null; transaction = session.beginTransaction(); List developers = session.createQuery("FROM Developer").list(); for (Developer developer : developers) { System.out.println(developer); System.out.println("\n================\n"); } session.close(); } public void updateDeveloper(int developerId, int experience) { Session session = sessionFactory.openSession(); Transaction transaction = null; transaction = session.beginTransaction(); Developer developer = (Developer) session.get(Developer.class, developerId); developer.setExperience(experience); session.update(developer); transaction.commit(); session.close(); } public void removeDeveloper(int developerId) { Session session = sessionFactory.openSession(); Transaction transaction = null; transaction = session.beginTransaction(); Developer developer = (Developer) session.get(Developer.class, developerId); session.delete(developer); transaction.commit(); session.close(); } } Если всё было сделано правильно, то в результате работы программы вы получите, примерно, следующий результат: /usr/lib/jvm/java-8-oracle/bin/java -Didea.launcher.port=7536 -Didea.launcher.bin.path=/home/proselyte/Programming/Soft/IntellijIdea/bin -Dfile.encoding=UTF-8 -classpath /usr/lib/jvm/java-8-oracle/jre/lib/management-agent.jar:/usr/lib/jvm/java-8-oracle/jre/lib/plugin.jar:/usr/lib/jvm/java-8-oracle/jre/lib/rt.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jsse.jar:/usr/lib/jvm/java-8-oracle/jre/lib/charsets.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jce.jar:/usr/lib/jvm/java-8-oracle/jre/lib/resources.jar:/usr/lib/jvm/java-8-oracle/jre/lib/deploy.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jfxswt.jar:/usr/lib/jvm/java-8-oracle/jre/lib/javaws.jar:/usr/lib/jvm/java-8-oracle/jre/lib/jfr.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/dnsns.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/sunpkcs11.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/sunec.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/sunjce_provider.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/jaccess.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/nashorn.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/localedata.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/zipfs.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/cldrdata.jar:/usr/lib/jvm/java-8-oracle/jre/lib/ext/jfxrt.jar:/home/proselyte/Programming/IdeaProjects/ProselyteTutorials/Hibernate/target/classes:/home/proselyte/.m2/repository/org/springframework/spring-core/4.1.1.RELEASE/spring-core-4.1.1.RELEASE.jar:/home/proselyte/.m2/repository/commons-logging/commons-logging/1.1.3/commons-logging-1.1.3.jar:/home/proselyte/.m2/repository/org/springframework/spring-web/4.1.1.RELEASE/spring-web-4.1.1.RELEASE.jar:/home/proselyte/.m2/repository/org/springframework/spring-aop/4.1.1.RELEASE/spring-aop-4.1.1.RELEASE.jar:/home/proselyte/.m2/repository/aopalliance/aopalliance/1.0/aopalliance-1.0.jar:/home/proselyte/.m2/repository/org/springframework/spring-beans/4.1.1.RELEASE/spring-beans-4.1.1.RELEASE.jar:/home/proselyte/.m2/repository/org/springframework/spring-context/4.1.1.RELEASE/spring-context-4.1.1.RELEASE.jar:/home/proselyte/.m2/repository/javax/servlet/servlet-api/2.5/servlet-api-2.5.jar:/home/proselyte/.m2/repository/org/springframework/spring-webmvc/4.1.1.RELEASE/spring-webmvc-4.1.1.RELEASE.jar:/home/proselyte/.m2/repository/org/springframework/spring-expression/4.1.1.RELEASE/spring-expression-4.1.1.RELEASE.jar:/home/proselyte/.m2/repository/org/springframework/integration/spring-integration-file/4.2.1.RELEASE/spring-integration-file-4.2.1.RELEASE.jar:/home/proselyte/.m2/repository/org/springframework/integration/spring-integration-core/4.2.1.RELEASE/spring-integration-core-4.2.1.RELEASE.jar:/home/proselyte/.m2/repository/org/springframework/spring-messaging/4.2.2.RELEASE/spring-messaging-4.2.2.RELEASE.jar:/home/proselyte/.m2/repository/org/springframework/retry/spring-retry/1.1.2.RELEASE/spring-retry-1.1.2.RELEASE.jar:/home/proselyte/.m2/repository/org/springframework/spring-tx/4.2.2.RELEASE/spring-tx-4.2.2.RELEASE.jar:/home/proselyte/.m2/repository/commons-io/commons-io/2.4/commons-io-2.4.jar:/home/proselyte/.m2/repository/org/hibernate/hibernate-core/5.1.0.Final/hibernate-core-5.1.0.Final.jar:/home/proselyte/.m2/repository/org/jboss/logging/jboss-logging/3.3.0.Final/jboss-logging-3.3.0.Final.jar:/home/proselyte/.m2/repository/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar:/home/proselyte/.m2/repository/org/javassist/javassist/3.20.0-GA/javassist-3.20.0-GA.jar:/home/proselyte/.m2/repository/antlr/antlr/2.7.7/antlr-2.7.7.jar:/home/proselyte/.m2/repository/org/apache/geronimo/specs/geronimo-jta_1.1_spec/1.1.1/geronimo-jta_1.1_spec-1.1.1.jar:/home/proselyte/.m2/repository/org/jboss/jandex/2.0.0.Final/jandex-2.0.0.Final.jar:/home/proselyte/.m2/repository/com/fasterxml/classmate/1.3.0/classmate-1.3.0.jar:/home/proselyte/.m2/repository/dom4j/dom4j/1.6.1/dom4j-1.6.1.jar:/home/proselyte/.m2/repository/xml-apis/xml-apis/1.0.b2/xml-apis-1.0.b2.jar:/home/proselyte/.m2/repository/org/hibernate/common/hibernate-commons-annotations/5.0.1.Final/hibernate-commons-annotations-5.0.1.Final.jar:/home/proselyte/.m2/repository/javassist/javassist/3.12.1.GA/javassist-3.12.1.GA.jar:/home/proselyte/.m2/repository/mysql/mysql-connector-java/5.1.38/mysql-connector-java-5.1.38.jar:/home/proselyte/Programming/Soft/IntellijIdea/lib/idea_rt.jar com.intellij.rt.execution.application.AppMain net.proselyte.hibernate.annotations.DeveloperRunner Feb 22, 2016 9:34:01 PM org.hibernate.Version logVersion INFO: HHH000412: Hibernate Core {5.1.0.Final} Feb 22, 2016 9:34:01 PM org.hibernate.cfg.Environment INFO: HHH000206: hibernate.properties not found Feb 22, 2016 9:34:01 PM org.hibernate.cfg.Environment buildBytecodeProvider INFO: HHH000021: Bytecode provider name : javassist Feb 22, 2016 9:34:01 PM org.hibernate.annotations.common.reflection.java.JavaReflectionManager INFO: HCANN000001: Hibernate Commons Annotations {5.0.1.Final} Feb 22, 2016 9:34:02 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl configure WARN: HHH10001002: Using Hibernate built-in connection pool (not for production use!) Feb 22, 2016 9:34:02 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001005: using driver [com.mysql.jdbc.Driver] at URL [jdbc:mysql://localhost/PROSELYTE_TUTORIAL] Feb 22, 2016 9:34:02 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001001: Connection properties: {user=root, password=****} Feb 22, 2016 9:34:02 PM org.hibernate.engine.jdbc.connections.internal.DriverManagerConnectionProviderImpl buildCreator INFO: HHH10001003: Autocommit mode: false Feb 22, 2016 9:34:02 PM org.hibernate.engine.jdbc.connections.internal.PooledConnections INFO: HHH000115: Hibernate connection pool size: 20 (min=1) Mon Feb 22 21:34:03 EET 2016 WARN: Establishing SSL connection without server's identity verification is not recommended. According to MySQL 5.5.45+, 5.6.26+ and 5.7.6+ requirements SSL connection must be established by default if explicit option isn't set. For compliance with existing applications not using SSL the verifyServerCertificate property is set to 'false'. You need either to explicitly disable SSL by setting useSSL=false, or set useSSL=true and provide truststore for server certificate verification. Feb 22, 2016 9:34:03 PM org.hibernate.dialect.Dialect INFO: HHH000400: Using dialect: org.hibernate.dialect.MySQLDialect Adding Developer's records to the database List of Developers: Feb 22, 2016 9:34:04 PM org.hibernate.hql.internal.QueryTranslatorFactoryInitiator initiateService INFO: HHH000397: Using ASTQueryTranslatorFactory Developer: id: 1 First Name: Proselyte Last Name: Developer Specialty: Java Developer Experience: 2 ================ Developer: id: 2 First Name: Some Last Name: Developer Specialty: C++ Developer Experience: 2 ================ Developer: id: 3 First Name: Peter Last Name: Team Lead Specialty: Java Team Lead Experience: 6 ================ Removing 'Some Developer' and updating 'Proselyte Developer''s experience: Final list of Developers: Developer: id: 1 First Name: Proselyte Last Name: Developer Specialty: Java Developer Experience: 3 ================ Developer: id: 3 First Name: Peter Last Name: Team Lead Specialty: Java Team Lead Experience: 6 ================ Так будет выглядеть наша таблица HIBERNATE_DEVELOPERS в БД +----+------------+-----------+----------------+------------+ | ID | FIRST_NAME | LAST_NAME | SPECIALTY | EXPERIENCE | +----+------------+-----------+----------------+------------+ | 1 | Proselyte | Developer | Java Developer | 3 | | 3 | Peter | Team Lead | Java Team Lead | 6 | +----+------------+-----------+----------------+------------+ В этой статье мы изучили основы конфигурирования Hibernate с помощью аннотаций и рассмотрели пример простого приложения с их использованием. Начало формы Конец формы |