DEV Community

Discussion on: Mapping JPA entities with Kotlin

Collapse
 
tonyengineering profile image
tony-engineering

Hello,

Thanks for your article.

I wrote a code based on what you wrote, and have difficulties to persist an entity in the database.

javax.persistence.PersistenceException: No Persistence provider for EntityManager named PersistenceProviderMysql

    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:85)
    at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:54)
    at KrakenConnector.saveLastPrice(KrakenConnector.kt:42)
    at KrakenConnector.getAndSaveLastPrice(KrakenConnector.kt:17)

I added a persistence.xml file at the following path: src/main/resources/META-INF

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.1"
             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_1.xsd">
    <persistence-unit name="PersistenceProviderMysql" transaction-type="RESOURCE_LOCAL">
        <class>KrakenConnector</class>
        <properties>
            <!-- Configuring The Database Connection Details -->
            <property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
            <property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/jpaDemoDb" />
            <property name="javax.persistence.jdbc.user" value="root" />
            <property name="javax.persistence.jdbc.password" value="" />
        </properties>
    </persistence-unit>
</persistence>

And the code to persist my entity is:

fun saveLastPrice(ohlcs: KrakenOHLCs) {
        val krakenOHLCsPersistable = KrakenOHLCsPersistable(ohlcs.ohlCs, 1)

        val emFactory: EntityManagerFactory = Persistence.createEntityManagerFactory("PersistenceProviderMysql")
        val entityManager = emFactory.createEntityManager()
        entityManager.transaction.begin()
        entityManager.persist(krakenOHLCsPersistable)
        entityManager.transaction.commit()
        entityManager.close()
        emFactory.close()
    }

I added "javax.persistence-api" version 2.2 as dependency in my pom.xml and also enabled the JPA support as described here kotlinlang.org/docs/reference/comp....

I am pretty sure the persistence.xml file is not detected because the error is the same when I delete it.

Could you provide the full working code of your example so I can try to reproduce it ?

Thanks in advance for your help,
Tony