Add framework support idea нет hibernate
Описание стандарта Java Persistence API. В статье будет показано как настроить Spring + JPA + Hibernate и подключить к БД MySQL.
Используемые технологии
- Spring 4.1.5.RELEASE
- Hibernate 5.0.1.Final
- JPA 2.1
- MySQL 5.6.25
- IntelliJ IDEA 14
- Maven 3.2.5
1. Описание задачи
Создать проект с использованием Java Persistence API, Spring, Hibernate и подключить всё это к базе данных MySQL. Spring будет использоваться как базовая конфигурация проекта, предоставит аннотации и свяжет все фреймворки в одном месте. Hibernate будет поставщиком службы постоянства, а JPA станет основой для программирования доступа к данным.
2. Описание JPA
JPA — это стандарт программной модели ORM для JSE\JEE, в котором определен общий набор концепций, аннотаций, интерфейсов и других служб, которые поставщик постоянства должен реализовать (пакет javax.persistence ). Эта стандартизация позволяет разработчикам переключаться между поставщиками постоянства, например между Hibernate, EclipseLink, Oracle TopLink, OpenJPA и другими. На разработку JPA достаточно сильно повлиял Hibernate и поэтому вы найдете много общего между ними. На данный момент рекомендуется использовать в проекте JPA в связке с поставщиком постоянства, например Hibernate. Именно это будет рассмотрено в этой статье.
3. Структура проекта
База данных MySQL и сущности взяты из статьи Hibernate – быстрый старт. Пример приложения Hello World. Рекомендую к прочтению её, а так же нескольких следующих статей из цикла по Hibernate, т.к. там есть описание подключения, настройки и базовых запросов, которые так же будут использованы в том или ином виде здесь.
4. Создание проекта
Вначале создаем пустой проект maven:
Затем необходимо настроить pom.xml:
xsi : schemaLocation = "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd" >
Подписи к зависимостям говорят сами за себя. Первая зависимость Вначале идет общая ссылка на весь проект spring, а далее отдельно зависимости для драйвера подключения к БД MySQL, зависимость Hibernate, и три минимально необходимых библиотеки Spring.
4.1. Добавление поддержки фреймворков Hibernate, JPA
Нажимаем на название проекта правой кнопкой и выбираем Add Framework support..
Отмечаем галочкой Spring, JavaEE Persistence и Hibernate. Если зависимости подгрузились, то будет предложено выбрать библиотеку maven. После этого в проект добавятся необходимые xml — META-INF\persistence.xml и sping-config.xml .
ВАЖНО
По умолчанию spring-config.xml будет добавлен в корень, но как вы видите из структуры проекта он был перенесен в папку resources. Объяснение смотрите в главе немного ниже.
4.2 Настройка spring-config.xml
- Дескриптор tx:annotation-driven — предназначен для поддержки объявления требований к установлению границ транзакций с использованием аннотаций.
- context:component-scan — сканирование компонентов в указанном пакете и ниже
- context:annotation-config — включает поддержку таких аннотаций как @Require , @Autowired
- бин transactionManager — диспетчер транзакций для фабрики диспетчера сущностей
- EntityManagerFactory — самый главный бин:) В целом с ним и будем работать для доступа к данным
5. Подключение к базе данных MySQL
Полностью взято из статьи Создание MySQL базы данных и подключение к IntelliJ IDEA. Как заполнялись данные читайте в разделе Hibernate.
6. Добавление сущностей в Java, используя JPA + Hibernate
В целом процедура та же, что и для работы с Hibernate, только здесь в вкладке Persistence отсутствует hibernate, а есть только JPA.
Я выбрал добавление только аннотаций и генерацию свойств колонок и убрал галочку, отвечающую за создание xml файлов:
Продолжение
2 thoughts on “ JPA — пример приложения Hello World. Настройка использования Spring + JPA + Hibernate. Часть 1 ”
Kpacu8o :
А можно подсказку?
Не совсем понимаю в какую сторону нужно гуглить.
Делал пункт 4.1, добавил поддержку фреймворков, а xmlки не сгенерировались вообще. Через «Project Structure» -> «Modules» вижу все три модуля(то-бишь спринг, гибернейт, JPA)
Выбираю JPA, там можно добавить META-INF\persistence.xml, но он считай что голый(выглядит вот так, поэтому думаю что он явно сгенерирован не так как надо, можно конечно руками все найти и прописать, для начала даже, наверное, полезно было бы, но все таки охота пользоваться сразу средствами среды).
Kpacu8o :
(часть 2, жаль что длинные комменты сайт не пропускает)Причем в более ранней версии проекта(собственно делал по статье про быстрый старт с гибернейтом[понятно что файлы другие, но генерировались они нормально, причем это происходит с промежутком в полтора часа — закончил с той статьей, немного отдохнул и принялся за эту], только с другим драйвером и реализацией бд) все файлы генерировались нормально, надо было только дополнить конфигурацию для гибернейта, а тут вообще ничего, даже нормальной шапки нет…
Далее, конфигу для спринга думал так же на молодости сгенерировать, но не получилось, если выбрать этот модуль, то там немного о другом, и соответственно сгенерить, пусть даже и кривой файл я не могу. Если подскажете куда гуглить, будет хорошо, если сразу дадите прямой совет что и как делать(и где я накосячил), буду вообще рад(тут уж как вам удобнее). Использую Java SE, версия 15, идейка, hibernate 5.4.23.FINAL, spring 5.2.10.RELEASE, драйвер oracle.jdbc(тк пользуюсь оракловской реализацией бд, написал чисто на всякий случай)
Hibernate is an object-relational mapping framework that implements the Jakarta Persistence (JPA) specification.
IntelliJ IDEA provides the following:
Coding assistance specific to Hibernate.
A dedicated facet for managing the Hibernate configuration hibernate.cfg.xml .
Additions to the Persistence tool window for managing your Hibernate items, creating configuration files and persistent classes, navigating to related source code in the editor, opening diagrams and consoles, and more.
Entity-relationship (ER) diagrams that you can access from the Persistence tool window.
An ability to generate managed entity classes and object-relational mappings for them by importing a database schema or an EJB deployment descriptor file ejb-jar.xml .
The Hibernate console for writing and running HQL queries, and analyzing the query results.
Manually add a facet to a module
In the Project tool window Alt+1 , right-click the module to which you want to add a facet, and select Add Framework Support .
Select the necessary framework from the list.
Depending on your choice, you might be prompted to configure additional settings (for example, to configure a library).
Apply the changes and close the dialog.
Making sure that the Hibernate Support plugin is enabled
In the Settings / Preferences dialog Ctrl+Alt+S , select Plugins .
In the right-hand part of the dialog, on the Plugins page, type hib in the search box. As a result, only the plugins whose names and descriptions contain hib are shown.
If the checkbox to the right of Hibernate Support is not selected, select it.
If suggested, restart IntelliJ IDEA.
Enabling Hibernate support when creating a project or module
Do one of the following:
If you are going to create a new project: click Create New Project on the Welcome screen or select File | New | Project .
As a result, the New Project wizard opens.
If you are going to add a module to an existing project: open the project you want to add a module to, and select File | New | Module .
As a result, the New Module wizard opens.
On the first page of the wizard, in the left-hand pane, select Java . In the right-hand part of the page, specify the JDK that you are going to use.
Under Additional Libraries and Frameworks , select the Hibernate checkbox.
If there is a database defined in IntelliJ IDEA as a data source, you can select to import the database schema. This will result in creating the necessary entity classes and object/relational mappings for them.
-
Download Hibernate implementation files and arrange those files in a library.
To do that, under Libraries , select Download . Optionally, click Configure to edit the library settings. (The Downloading Options dialog will open.)
To do that, click Use library and select the required library from the list. Optionally, click Configure to edit the library settings. (The Edit Library dialog will open.)
To do that, click Use library and then click Create . Select the required JAR files in the dialog that opens. (For multiple selection, keep the Ctrl key pressed.) Optionally, click Configure to edit the library settings. (The Create Library dialog will open.)
Postpone setting up the library until a later time. In this case, select Set up library later .
Specify the name and location settings.
If you selected to import a database schema, the Import Database Schema dialog opens, and you can specify the entity classes to be generated and associated settings.
Enable Hibernate support for an existing project
If you already have a Java Enterprise web application, you can add the Hibernate framework support.
Open the build file in the editor ( pom.xml or build.gradle depending on the build tool that you use in your project).
Add the following dependency, but make sure to change the version according to your project's requirements:
Press Ctrl+Shift+O to import the changes.
For more information on how to work with build tools, refer to Maven or Gradle.
This information is valid for projects that are built with the native IntelliJ IDEA builder. If you're using a build tool, such as Maven or Gradle, make all changes using the build file.
For developing framework-specific applications, IntelliJ IDEA features facets. Facets contain libraries, dependencies, and technologies, and they provide you with additional UI elements for configuring framework-specific settings.
Note that not all facets are available out of the box. To be able to use some of them, you need to install a plugin for the necessary framework first. Refer to JetBrains Plugin Repository for more information on existing plugins.
IntelliJ IDEA can identify a file or a directory that is typical for a certain framework, and add the necessary facet for you. Once the facet is detected and added, IntelliJ IDEA will inform you about the missing configuration and will suggest the necessary actions.
If a facet is not detected automatically, you can add it manually. You can add more than one facet to a module.
Some frameworks are available only in IntelliJ IDEA Ultimate. Refer to comparison matrix to make sure your version of IntelliJ IDEA supports the necessary frameworks.
You can find all facets that are configured for modules in your project in the Project Structure dialog: from the main menu, select File | Project Structure ( Ctrl+Alt+Shift+S ) and select Modules .
If you use a build tool in your project, such as Maven or Gradle, make all changes using the build file.
Create a new Java Enterprise project with Hibernate
Click New Project on the Welcome screen or select File | New | Project .
From the Generators list, select Java Enterprise .
Name the new project, select a build tool, a language you want to use, and select the Web application project template.
Select the Create Git repository option to place the new project under version control.
From the JDK list, select the JDK that you want to use in your project.
If the JDK is installed on your computer, but not defined in the IDE, select Add JDK and specify the path to the JDK home directory.
If you don't have the necessary JDK on your computer, select Download JDK .
On the next step of the wizard, select the Java EE version to be supported.
From the Dependencies list, select the Persistence (JPA) specification and Hibernate as the implementation.
For more information on how to create a Java Enterprise project, refer to Tutorial: Your first Java EE application.
IntelliJ IDEA creates the default project structure with the JPA facet and all the necessary libraries as external dependencies, such as javax.persistence for the JPA specification and org.hibernate for the Hibernate framework. If you specified an application server, IntelliJ IDEA will also create a run configuration to start the server, build and deploy the artifact.
Enabling Hibernate support for an existing module
In the Project Tool Window, right-click the necessary module and select Add Framework Support .
In the left-hand pane of the Add Frameworks Support dialog that opens, select the Hibernate checkbox.
If there is a database defined in IntelliJ IDEA as a data source, you can select to import the database schema. This will result in creating the necessary entity classes and object/relational mappings for them.
-
Download Hibernate implementation files and arrange those files in a library.
To do that, under Libraries , select Download . Optionally, click Configure to edit the library settings. (The Downloading Options dialog will open.)
To do that, click Use library and select the required library from the list. Optionally, click Configure to edit the library settings. (The Edit Library dialog will open.)
To do that, click Use library and then click Create . Select the required JAR files in the dialog that opens. (For multiple selection, keep the Ctrl key pressed.) Optionally, click Configure to edit the library settings. (The Create Library dialog will open.)
Postpone setting up the library until a later time. In this case, select Set up library later .
If you selected to import a database schema, the Import Database Schema dialog opens, and you can specify the entity classes to be generated and associated settings.
When you have a Spring Boot project with JPA and using Hibernate to access a database, there is a strong feature in Intellij Idea which hast many benefits such as:
- Entity-relationship (ER) diagrams.
- The ER diagrams are accessed from the Persistence tool window (see Opening entity-relationship diagrams) and provide about the same set of functions as the tool window.
- A JPA console that lets you write and run JPQL queries, and analyze the query results. See Working with the JPA console. in Java code including JPA annotations and their attributes, and also in JPA configuration and O/R mapping XML files.
- JPA-specific code inspections.
- The Persistence tool window that shows your JPA project items and lets you create new configuration files and persistent classes, navigate to related source code in the editor, open diagrams and consoles, and more. See Working with the Persistence Tool Window.
Unfortunately, sometime this feature is not active and I couldn't found any instruction on Jet-brain web site to run it.
This feature is only supported in the Ultimate edition.
1- I’ve created a Spring Boot project using Maven with the wizard and select Web, JPA and MySQL dependencies.
But persistence window doesn’t exist yet.
2- In Project Structure window, add JPA to Facets to the main module and at the bottom, set Default JPA Provider to Hibernate. (No need to add any descriptor)
3- Now you can see the Persistence tool window is appeared and automatically contains Entities as Persistence Unit.
4- At this step a DataSource should be added to project and (also set datasource properties in the application.properties)
5- You can create a database of defined entities by right click on Entities and select Generate Persistence Mapping and By Database Schema.
6- Now we reach to the best part, the JPA console to write your HQL or JPL and get the result instantly.
Disable framework auto-detection
By default, auto-detection is enabled for all the supported frameworks. You can disable framework auto-detection completely, or exclude individual frameworks from auto-detection.
From the main menu, select File | Project Structure ( Ctrl+Alt+Shift+S ) and select Facets .
Select Detection and click Alt+Insert .
From the Framework to Exclude list, select the necessary option.
You can disable auto-detection of a specific framework only in one directory or in the whole project. The list also allows you to disable auto-detection of all frameworks in a specific directory.
If you want to disable auto-detection of all frameworks in the whole project, deselect the Enable framework detection checkbox.
To re-enable auto-detection everywhere, select the Enable framework detection checkbox and remove all entries from the Exclude from detection list.
Create a Hibernate configuration file hibernate.cfg.xml and a class with a main() method that outputs the records for your managed entities.
Download the library files that implement the framework and add them to the dependencies of the corresponding module.
Generate entity classes and object/relational mappings for your database tables (if you have an appropriate data source available).
Create a Hibernate facet. You'll be able to use that facet for managing your configuration hibernate.cfg.xml files.
Make the Persistence tool window available.
Читайте также: