Как подружить Hibernate 7.4.0 и H2
Что узнал: A persistence unit is a configuration in Java applications (like those using JPA or Hibernate) that groups a set of database-mapped classes (entities) together with a specific database connection, transaction type, and other operational settings
Гайд как подружить hibernate 7.4.0 с h2 db: 1. Подключить hibernate и h2 в build.gradle: implementation “com.h2database:h2:2.4.240” implementation “org.hibernate.orm:hibernate-core:7.4.0.Final”
2. Создать папку resources/META-INF/ и добавить туда persistance.xml:
org.hibernate.jpa.HibernatePersistenceProvider <properties> <property name=“jakarta.persistence.jdbc.driver” value=“org.h2.Driver”/> <property name=“jakarta.persistence.jdbc.url” value=“jdbc:h2:mem:test”/> <property name=“jakarta.persistence.schema-generation.database.action” value=“drop-and-create”/> </properties> <class>ru.hawoline.entity.User</class>
3. Добавить сущность, обязательно указав аннотации @Entity, @Table(name=“someTableName”), @Id: import jakarta.persistence.*; @Entity @Table(name = “USERS”) public class User { @Id private String username; private String firstname; private String lastname; private LocalDate birthdate; private Integer age; public User() { } public User(String username, String firstname, String lastname, LocalDate birthdate, Integer age) { this.username = username; this.firstname = firstname; this.lastname = lastname; this.birthdate = birthdate; this.age = age; } } @Id - аннотация, которая указывает первичный ключ 4. Применение: try ( EntityManagerFactory emf = Persistence.createEntityManagerFactory(“H2InMemoryPU”); //Название из /META-INF/persistence.xml EntityManager em = emf.createEntityManager() ) { em.getTransaction().begin(); User user = new User( “Hawoline”, “Belikto”, “Neltanov”, LocalDate.of(2001, 8, 13), 24 ); em.persist(user); em.getTransaction().commit(); boolean contains = em.contains(user); User copyUser = em.find(User.class, “Hawoline”); System.out.println(“Hibernate 7.4.0 successfully executed with H2 In-Memory DB!”); } catch (Exception e) { e.printStackTrace(); }
DONE: - 5 урок по Hibernate от dmdev - так как я подключил новую версию hibernate и подключил h2, а не postgres, я кучу времени убил на то, чтобы записать и получить сущность из бд. Теперь вообще от урока dmdev ничего не осталось, хах
TODO: - написать dao для таблиц в проекте “Табло теннисного матча”