Required software:
- GlassFish 5.0.0.
- IntelliJ IDEA Ultimate Edition
Useful links:
Before you start:
- This assumes you are running a MySQL server on
<hostname:port>
with a user<user>
and<password>
having access to database<db>
So the URL would be:jdbc:mysql://<hostname:port>/<db>
. - The password cannot be empty! It's also stored in plain text, so make a special one just for this.
- Also be sure to give GlassFish the MySQL connector jar. (Put
lib/mysql-connector-java-*.jar
in<glassfish_dir>/domains/<domain>/lib/ext/
) - Enable
Java Persistence
on one of the project modules! (Probably either a new module or a library module, since you need access to the data types from everywhere.) - Enable the
JPA Descriptors
output in the EJB artifact otherwise the@PersistenceContext
will fail! (It must haveMETA-INF/persistence.xml
in the root.)
- Run server (using GlassFish 5 here)
- Connect to admin url http://localhost:4848
Resources
->JDBC
->JDBC Connection Pools
->new
- 'Name':
MySQL_<name>
- 'Resource Type':
java.sql.Driver
- 'Database Driver Vendor':
MySql
- Do not check 'Introspect' Enabled!
- 'Name':
next
- It should have pre-filled Driver Classname with
com.mysql.jdbc.Driver
. - If not, make sure you read the instructions above this list and restart GlassFish.
- Enable 'Ping'
- Under 'Additional Properties':
- 'password':
<password>
- 'user':
<user>
- 'URL':
jdbc:mysql://<hostname:port>/<db>
- 'password':
- It should have pre-filled Driver Classname with
save
.Resources
->JDBC
->JDBC Resources
->new
- 'JNDI Name':
jdbc/mysql_<name>
- 'Pool Name': Select the name you just made.
- 'JNDI Name':
ok
- In the project's
persistence.xml
file should look like the file below. - IntelliJ magic
- Open the
Databases
tool window. - +' ->
Data Source
->MySQL
- Fill out DB details (and download drivers if required).
OK
- Open the
Persistence
tool window. - Right click on the name of the project
Assign Data Sources...
- Pick the data source you just created.
- Open the
- Enjoy the full power of IntelliJ's autocomplete and everything else that makes every other IDE bad in comparison.
BONUS ROUND
- Automatically generate
...Entity
classes:- Open the
Persistence
tool window - Right click on the persistence unit.
Generate Persistence Mapping ...
->By Database Schema
- Check some boxes.
- Profit.
- Open the
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd"
version="2.2">
<persistence-unit name="persistence-unit">
<jta-data-source>jdbc/mysql_project</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
</persistence-unit>
</persistence>