Eclipselink with jpa errorfor persistenceunit load - rest

hi I'm trying to use JPA with eclipse link but it gives me following error:
I'm using maven, and context.xml file is in web module and persistaence.xml is in access/db module.
Failed to connect to MyModalTestApp: Exception [EclipseLink-30005] (Eclipse
Persistence Services - 2.6.4.v20160829-44060b6):
org.eclipse.persistence.exceptions.PersistenceUnitLoadingException
Exception Description: An exception was thrown while searching for
persistence archives with ClassLoader: ParallelWebappClassLoader
context: modaltestapp-api
delegate: false
----------> Parent Classloader:
java.net.URLClassLoader#3fee733d
Internal Exception: javax.persistence.PersistenceException: Exception
[EclipseLink-28018] (Eclipse Persistence Services - 2.6.4.v20160829-
44060b6): org.eclipse.persistence.exceptions.EntityManagerSetupException
Exception Description: Predeployment of PersistenceUnit [MyModalTestApp]
failed.
Internal Exception: Exception [EclipseLink-7161] (Eclipse Persistence
Services - 2.6.4.v20160829-44060b6):
org.eclipse.persistence.exceptions.ValidationException
Exception Description: Entity class [class
com.modaltestapp.entity.RegistrationEntity] has no primary key specified.
It should define either an #Id, #EmbeddedId or an #IdClass. If you have
defined PK using any of these annotations then make sure that you do not
have mixed access-type (both fields and properties annotated) in your
entity class hierarchy.
persistence.xml
<?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="MyModalTestApp" transaction-type="RESOURCE_LOCAL">
<non-jta-data-source>java:comp/env/jdbc/MODALTESTAPP_DATASOURCE</non-jta-data-source>
<class>com.modaltestapp.entity.RegistrationEntity</class>
<exclude-unlisted-classes>true</exclude-unlisted-classes>
<properties>
<property name="eclipselink.ddl-generation.output-mode" value="database" />
<property name="eclipselink.ddl-generation" value="none"/>
<property name="eclipselink.weaving" value="static" />
<property name="eclipselink.target-database" value="Auto"/>
<property name="eclipselink.target-server" value="None"/>
<property name="eclipselink.jdbc.batch-writing" value="JDBC"/>
<property name="eclipselink.logging.level" value="FINEST"/>
<property name="eclipselink.logging.timestamp" value="true"/>
<property name="eclipselink.logging.session" value="false"/>
<property name="eclipselink.logging.thread" value="true"/>
<property name="eclipselink.logging.exceptions" value="true"/>
<!-- 0 is a valid ID
<property name="eclipselink.id-validation" value="NULL"/> -->
<!-- We need the following, else EclipseLink cannot properly translate column names in Native SQL queries. -->
<property name="eclipselink.jdbc.uppercase-columns" value="true"/>
</properties>
</persistence-unit>
</persistence>
pojo is:
package com.modaltestapp.entity;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name = "REGISTRATION")
public class RegistrationEntity implements Serializable{
private static final long serialVersionUID = 1L;
#Column(name = "FIRSTNAME")
private String firstName;
#Column(name = "LASTNAME")
private String lastName;
#Column(name = "LASTNAME")
private String email;
#Column(name = "MESSAGE")
private String message;
#Column(name = "EDUCATION")
private String education;
#Column(name = "HOBBIES")
private String hobbies;
#Column(name = "GENDER")
private String gender;
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String getEducation() {
return education;
}
public void setEducation(String education) {
this.education = education;
}
public String getHobbies() {
return hobbies;
}
public void setHobbies(String hobbies) {
this.hobbies = hobbies;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
}
context.xml is:
<Context>
<!-- Default set of monitored resources -->
<WatchedResource>WEB-INF/web.xml</WatchedResource>
<!-- Uncomment this to disable session persistence across Tomcat restarts -->
<!--
<Manager pathname="" />
-->
<!-- Uncomment this to enable Comet connection tacking (provides events
on session expiration as well as webapp lifecycle) -->
<!--
<Valve className="org.apache.catalina.valves.CometConnectionManagerValve" />
-->
<Resource name="jdbc/MODALTESTAPP_DATASOURCE" auth="Container" type="javax.sql.DataSource"
maxTotal="8" maxIdle="2"
username="root" password="unnati#123" driverClassName="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/MODALTESTAPP" validationQuery="select 1"/>
</Context>
and my implementation code is :
try {
EntityManager em = Persistence.createEntityManagerFactory("MyModalTestApp").createEntityManager();
System.out.println("in database portion1");
/* Persist entity */
em.getTransaction().begin();
System.out.println("in database portion2");
em.persist(REG);
System.out.println("in database portion3");
em.getTransaction().commit();
System.out.println("yes transcaction done");
} catch (Exception e) {
System.out.println("Failed to connect to MyModalTestApp: " + e);
// e.printStackTrace();
}

Related

Predeployment of PersistenceUnit [h2] failed with UUID? Class: [uuid] was not found while converting from class names to classes

When i try persist my Entity I get this exception:
Exception in thread "main" javax.persistence.PersistenceException: Exception [EclipseLink-28019] (Eclipse Persistence Services - 2.7.3.v20180807-4be1041): org.eclipse.persistence.exceptions.EntityManagerSetupException
Runtime Exceptions:
Exception Description: Deployment of PersistenceUnit [h2] failed. Close all factories for this PersistenceUnit.
Internal Exception: Exception [EclipseLink-0] (Eclipse Persistence Services - 2.7.3.v20180807-4be1041): org.eclipse.persistence.exceptions.IntegrityException
Exception [EclipseLink-7198] (Eclipse Persistence Services - 2.7.3.v20180807-4be1041): org.eclipse.persistence.exceptions.ValidationException
Descriptor Exceptions:
Exception Description: Class: [uuid] was not found while converting from class names to classes.
Internal Exception: java.lang.ClassNotFoundException: uuid
Entity
#Entity
#UuidGenerator(name = "uuid")
#Converter(name = "uuidConverter", converterClass = UUIDConverter.class)
#Table(name = "ELECTRIC_METERS")
#NamedQuery(name = "ElectricMeters.findElectricMetersByNote",
query = "SELECT e FROM ElectricMeters e WHERE e.note = :note")
public class ElectricMeters implements Serializable{
#Id
#GeneratedValue(generator = "uuid", strategy = IDENTITY)
#Convert("uuidConverter")
#Column (name = "ID")
private UUID id;
#Column(name = "ADD_YARD_LIGHTING")
private boolean addYardLighting;
#Column(name = "NOTE")
private String note;
public ElectricMeters() {
}
//getters setters
}
persistence.xml
<?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="h2" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<!-- Converter -->
<class>com.art.forestbucha.util.UUIDConverter</class>
<class>com.art.forestbucha.entity.ElectricMeters</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:file://home/artem/NetBeansProjects/ForestBuchaBackEnd/src/main/resources/db/bucha"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
</properties>
</persistence-unit>
</persistence>
Converter
import java.util.UUID;
import org.eclipse.persistence.internal.helper.DatabaseField;
import org.eclipse.persistence.mappings.DatabaseMapping;
import org.eclipse.persistence.mappings.DirectCollectionMapping;
import org.eclipse.persistence.mappings.converters.Converter;
import org.eclipse.persistence.sessions.Session;
public class UUIDConverter implements Converter{
#Override
public Object convertObjectValueToDataValue(Object objectValue,
Session session) {
return (UUID) objectValue;
}
#Override
public UUID convertDataValueToObjectValue(Object dataValue,
Session session) {
return (UUID) dataValue;
}
#Override
public boolean isMutable() {
return true;
}
#Override
public void initialize(DatabaseMapping mapping, Session session) {
final DatabaseField field;
if (mapping instanceof DirectCollectionMapping) {
// handle #ElementCollection...
field = ((DirectCollectionMapping) mapping).getDirectField();
} else {
field = mapping.getField();
}
field.setSqlType(java.sql.Types.OTHER);
field.setTypeName("uuid");
field.setColumnDefinition("UUID");
}
}
create database:
CREATE TABLE PUBLIC.ELECTRIC_METERS
(ID UUID NOT NULL PRIMARY KEY,
ADD_YARD_LIGHTING BOOLEAN DEFAULT false NOT NULL,
NOTE VARCHAR(255));

Java.lang.reflect.invocationTargetException in hibernate

Any one please solve my problem. I'm getting java.lang.reflect.invocationTargetException while I'm trying to save an object into oracle database(Oracle 10G).
Here is my model class named Student.java
package org.hibernatetest;
public class Student {
private int id;
private String name;
private String email;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
}
Here is my mapping file named Student.hbm.xml
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="org.hibernatetest.Student" table="STUDENT_2018">
<id name="id" column="STUDENT_ID"/>
<property name="name" column="STUDENT_NAME"></property>
<property name="email" column="STUDENT_EMAIL"></property>
</class>
</hibernate-mapping>
here is configuration file named as hibernate.cfg.xml
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.dialect">org.hibernate.dialect.OracleDialect</property>
<property name="hibernate.connection.driver_class">oracle.jdbc.driver.OracleDriver</property>
<property name="hibernate.connection.username">Test</property>
<property name="hibernate.connection.password">Test</property>
<property name="hibernate.connection.url">jdbc:oracle:thin:#localhost:1521:XE</property>
<property name="hibernate.hbm2ddl.auto">create-drop</property>
<property name="show_sql">true</property>
<mapping resource="resource/Student.hbm.xml"/>
</session-factory>
</hibernate-configuration>
here is my persistent class named Test.java
package org.hibernatetest;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
public class Test {
public static void main(String[] args) {
Student st = new Student();
st.setId(1);
st.setName("Mohan");
st.setEmail("mmohan668#gmail.com");
Configuration cfg = new Configuration();
SessionFactory sf = cfg.configure("resource/hibernate.cfg.xml").buildSessionFactory();
Session s = sf.openSession();
s.save(st);
s.beginTransaction().commit();
s.evict(st);
}
}
Please help to resolve my problem . Thanks in advance.

HSQLDB Tables not generating

I have a database using HSQLDB, and my persistence.xml file is not creating the tables as I would expect. Here is my persistence.xml code:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="DanPfeiffer-SE452-ProjectPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>java.user.jpa.User</class>
<class>java.score.jpa.Score</class>
<class>java.teeBox.jpa.TeeBox</class>
<class>java.course.jpa.Course</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbc.JDBCDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:hsql://localhost/mydb"/>
<property name="javax.persistence.jdbc.user" value="SA"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create-tables"/>
<property name="eclipselink.deploy-on-startup" value="true" />
</properties>
</persistence-unit>
</persistence>
I have a few Java Beans written with #Entity annotation. Here's the simplest of those beans.
package main.java.user.jpa;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import main.java.score.IScore;
import main.java.score.jpa.Score;
import main.java.user.IUser;
#Entity
#NamedQuery(name = "findAllUsers", query = "select u from User u")
public class User implements Serializable, IUser {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int userId;
#NotNull
private String firstName;
#NotNull
private String lastName;
#NotNull
private double handicap;
#OneToMany
private Collection<Score> scores;
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return this.firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return this.lastName;
}
public void setId(int id) {
this.userId = id;
}
public int getId() {
return userId;
}
public void setHandicap(double hcp) {
this.handicap = hcp;
}
public double getHandicap() {
return handicap;
}
#Override
public void setScores(Collection<Score> scores) {
if (this.scores != null){
for (Score temp : scores){
this.scores.add(temp);
}
}
else{
this.scores = scores;
}
}
#Override
public Collection<Score> getScores() {
// TODO Auto-generated method stub
return null;
}
public boolean equals(Object object){
boolean result = false;
if (object instanceof User){
User temp = (User)object;
if (temp.getFirstName().equals(this.firstName)
&& temp.getLastName().equals(this.lastName)
&& temp.getHandicap() == this.handicap){
result = true;
}
}
return result;
}
public String toString(){
String result = ("User: \nID: " + this.userId + "\nName:" + this.firstName + " " + this.lastName + " \nHandicap:" + this.handicap);
return result;
}
}
From my understanding, the persistence.xml file should drop and create all of the tables each time the hsqldb.jar file is run.
I haven't found an issue with my connection (it works when I connect, just no data), my persistence file or location. I originally populated the database this way.

JPA Create Parent/child relationship with a lot of children

I am trying to store entity Track with children entities TrackPoints with JPA method create. However, to store Track with its children TrackPoints last really long - about 30 seconds. I tried GenerationType.Identity and GenerationType.SEQUENCE. If I also have Hibernate Spatial (Postgis) column, it lasts even longer - about 60 seconds to store parent and all children. JPA sends insert sequentially one followed by another. How can I optimize this? Can anybody tell me what is the main problem?
Technologies:
Wildfly 8.1, JPA 2.1 (hibernate), Hibernate Spatial, EJB, JTA
PostgreSQL 9.3 + PostGis - default setup (just install from Ubuntu package)
Track.java
#Entity
#Table(name = "TRACKS")
public class Track implements Serializable {
#Id
#Column(name = "track_id", nullable = false, unique = true)
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private Long id;
#NotNull
#NotEmpty
#Size(min = 1, max = 100)
#Column(nullable = false, length = 100)
private String name;
#Size(max = 200)
#Column(nullable = false, length = 200)
private String description;
#OneToOne(optional = false)
#JoinColumn(name = "userId", nullable = false)
private User userOwner;
#NotNull
#NotEmpty
#Column(nullable = false, length = 55)
private String type;
#NotNull
private Boolean isShared;
#OneToMany(mappedBy = "track")
private List<TrackPoint> trackPoints;
}
TrackPoint.java
#Entity
#Table(name = "TRACK_POINTS")
public class TrackPoint implements Serializable {
private static final long serialVersionUID = 8089601593251025235L;
#Id
#Column(name = "trackpoint_id", nullable = false, unique = true)
#GeneratedValue(generator = "track_point_sequence", strategy = GenerationType.SEQUENCE)
#SequenceGenerator(name = "track_point_sequence", sequenceName = "track_point_sequence", allocationSize = 1000)
private Long id;
#NotNull
private int trackSegment;
#NotNull
private double elevation;
#NotNull
#Temporal(TemporalType.TIMESTAMP)
private Date timeStamp;
#NotNull
#ManyToOne(optional = false, fetch = FetchType.EAGER)
#JoinColumn(name = "track_id")
private Track track;
/*Hibernate Spatial - Postgis field.
#NotNull
#Column(nullable = false)
#Type(type = "org.hibernate.spatial.GeometryType")
private Geometry location;*/
}
TrackService.java
#Stateless
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public class TracksService implements ITracksService {
#Inject
private IDaoService dao;
#Override
public Long createTrack(GpxType gpx, String userId, String name, String desc) {
// Map GPX to Track, TrackPoint object.
track = dao.create(track);
int batch_size = 50;
int i = 0;
for(TrackPoint point: track.getTrackPoints()) {
dao.create(point);
if(i++ % batch_size == 0) {
dao.flush();
dao.clear();
}
}
return track.getId();
}
DaoService.java
#Stateless
#TransactionAttribute(TransactionAttributeType.REQUIRED)
public class DaoService implements IDaoService {
#PersistenceContext()
private EntityManager em;
#Override
public <T extends Serializable> T create(T t) {
em.persist(t);
return t;
}
}
persistence.xml
<persistence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xsi:schemaLocation=
"http://xmlns.jcp.org/xml/ns/persistence
http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd">
<persistence-unit name="postgisTourbookPU" transaction-type="JTA">
<description>PostgresSQL database with PostGIS extension</description>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<jta-data-source>${tourbook.datasource.postgresql.jndi-name}</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<shared-cache-mode>NONE</shared-cache-mode>
<properties>
<!-- JPA properties -->
<property name="javax.persistence.schema-generation.database.action"
value="drop-and-create"/>
<!-- <property name="javax.persistence.schema-generation-target"
value="database"/>-->
<!-- Creation Schema Properties -->
<property name="javax.persistence.schema-generation.create-source"
value="metadata"/>
<!-- <!– DDL Script location, when script is used –>
<property name="javax.persistence.schema-generation.create-script-source"
value="META-INF/create-script.sql"/>-->
<!-- Drop Schema Properties -->
<property name="javax.persistence.schema-generation.drop-source"
value="metadata"/>
<!-- <property name="javax.persistence.schema-generation.drop-script-source"
value="META-INF/drop-script.sql"/>-->
<property name="javax.persistence.sql-load-script-source"
value="META-INF/load-script.sql"/>
<!-- JPA driver information -->
<property name="javax.persistence.jdbc.driver"
value="org.postgresql.Driver"/>
<!-- Hibernate properties -->
<property name="hibernate.connection.characterEncoding"
value="UTF-8"/>
<property name="hibernate.dialect"
value="org.hibernate.spatial.dialect.postgis.PostgisDialect"/>
<property name="hibernate.default_schema"
value="public"/>
<property name="hibernate.show_sql"
value="true"/>
<property name="hibernate.jdbc.batch_size" value="50"/>
<property name="hibernate.jdbc.fetch_size"
value="50"/>
<property name="hibernate.order_inserts"
value="true"/>
<property name="hibernate.order_updates"
value="true"/>
<property name="hibernate.cache.use_query_cache"
value="false"/>
<!-- Hibernate caching -->
</properties>
</persistence-unit>
</persistence>
Edited
So I have tried, batch insert in Hibernate, but I still get 30 seconds for saving 2000 points.
you're inserting a parent with all the children. In that case the Hibernate JPA indeed can be slow, but there are a few tips to improve the performance
- check the hibernate batch guide http://docs.jboss.org/hibernate/core/4.0/devguide/en-US/html/ch04.html
- I've used the hibernate.jdbc.batch_size parameter (set to e.g. 50)
Good luck
Gabriel

GAE : Google Cloud SQL + JPA is not working

When i connected my cloud sql instance with JPA using EclipseLink 2.2.1, it shows following error
W 2012-10-24 12:21:46.120
org.datanucleus.metadata.xml.AbstractMetaDataHandler error: MetaData Parser encountered an error in file "file:/base/data/home/apps/s~appengineaplicationID/8.362672796318745816/WEB-INF/classes/META-INF/persistence.xml" at line 2, column 248 : cvc-complex-type.3.1: Value '2.0' of attribute 'version' of element 'persistence' is not valid with respect to the corresponding attribute use. Attribute 'version' has a fixed value of '1.0'. - Please check your specification of DTD and the validity of the MetaData XML that you have specified.
W 2012-10-24 12:21:46.885
Error for /jpatest
java.lang.ExceptionInInitializerError
at com.my.jpa.ContactService.createContact(ContactService.java:20)
at com.my.jpa.JPATestServlet.doGet(JPATestServlet.java:16)
Caused by: org.datanucleus.exceptions.NucleusUserException: No available StoreManager found for the datastore URL key "". Please make sure you have all relevant plugins in the CLASSPATH (e.g datanucleus-rdbms?, datanucleus-db4o?), and consider setting the persistence property "datanucleus.storeManagerType" to the type of store you are using e.g rdbms, db4o
W 2012-10-24 12:21:46.887
Nested in java.lang.ExceptionInInitializerError:
javax.persistence.PersistenceException: Provider error. Provider: org.datanucleus.jpa.PersistenceProviderImpl
at javax.persistence.Persistence.createFactory(Persistence.java:176)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:112)
at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:66)
at com.my.jpa.EMF.<clinit>(EMF.java:8)
at com.my.jpa.ContactService.createContact(ContactService.java:20)
at com.my.jpa.JPATestServlet.doGet(JPATestServlet.java:16)
C 2012-10-24 12:21:46.893
Uncaught exception from servlet
java.lang.ExceptionInInitializerError
at com.my.jpa.ContactService.createContact(ContactService.java:20)
at com.my.jpa.JPATestServlet.doGet(JPATestServlet.java:16)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
My code for persistance.xml is
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0"
xmlns="http://java.sun.com/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence http://java.sun.com/xml/ns/persistence/persistence_2_0.xsd">
<persistence-unit name="JPATest">
<class>com.my.jpa.Contact</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.google.cloud.sql.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:google:rdbms://instance_name/db" />
<property name="javax.persistence.jdbc.user" value="" />
<property name="javax.persistence.jdbc.password" value="" />
</properties>
</persistence-unit>
</persistence>
My Entity Manager Factory Class is :
public final class EMF {
private static final EntityManagerFactory emfInstance = Persistence
.createEntityManagerFactory("JPATest");
private EMF() {
}
public static EntityManagerFactory get() {
return emfInstance;
}
}
Servlet is :
public class JPATestServlet extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
ContactService service = new ContactService();
service.createContact(new Contact("Manu", "Mohan", "686019", "TVM"));
resp.setContentType("text/plain");
resp.getWriter().println("Hello, world");
}
}
Entity Class is :
#Entity
public class Contact {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String firstName;
private String lastName;
private String phoneNumber;
private String address;
public Contact() {
}
public Contact(String fn, String ln, String pn, String addr) {
this.firstName = fn;
this.lastName = ln;
this.phoneNumber = pn;
this.address = addr;
}
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 getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
One would think that if you want to use EclipseLink, then you would set the "provider" in "persistence.xml", since you have other JPA implementation(s) in the CLASSPATH too, or alternatively you fix the CLASSPATH to make sure there is only 1 JPA implementation present