I'm trying to to develop a simple rest API project with Java and Tomcat. The HTTP request works correctly, but I'm figuring out a lot of problem by implementing a database MySQL to store data. This is my persistence.xml file, that is located in Java Resources/META-INF:
<persistence 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"
version="2.0">
<persistence-unit name="PERSISTENCE">
<description> Hibernate JPA Configuration Example</description>
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.resourceserver.Person</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver" />
<property name="javax.persistence.jdbc.url"
value="jdbc:mysql://localhost:3306/RESTResourceServer" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="password" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
</properties>
</persistence-unit>
This is my PersonDAO.java and JPAUtil.java class:
public class PersonDao {
EntityManager entityManager;
public PersonDao() {
entityManager = JPAUtil.getEntityManagerFactory().createEntityManager();
}
public void storePerson(Person person) {
entityManager.persist(person);
// people.add(person);
}
public void deletePerson(Person person) {
entityManager.remove(person);
// people.remove(person);
}
public Person findPersonId(int id) {
/*
* for (Person person : people) { if (person.getId() == id) { return person; } }
*/
return null;
}
#SuppressWarnings("unchecked")
public List<Person> getAllUsers() {
Query query = entityManager.createQuery("Select p From People p ");
return query.getResultList();
// return people;
}
}
public class JPAUtil {
private static final String PERSISTENCE_UNIT_NAME = "PERSISTENCE";
private static EntityManagerFactory factory;
public static EntityManagerFactory getEntityManagerFactory() {
if (factory == null) {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
}
return factory;
}
public static void shutdown() {
if (factory != null) {
factory.close();
}
}
}
And in my Endpoint I simple use PersonDao persona = new PersonDao() to perform the operations; where am I wrong?
You are missing the persistence provider (no surprise there!)
Most likely you have added the JPA API as a dependency but forgot to add a concrete implementation like Hibernate or EclipseLink. This means you can compile the whole thing because the interfaces for JPA are there but there are not implementing classes.
Related
I am trying to use openjpa and mysql to persist a single class, nothing dramatic really.
Attempt to cast instance "xxx" to PersistenceCapable failed. Ensure that it has been enhanced.
So I looked around and found this
https://openjpa.apache.org/builds/2.2.1/apache-openjpa/docs/ref_guide_pc_enhance.html
where they suggest the use of
java -javaagent:/home/dev/openjpa/lib/openjpa.jar com.xyz.Main
Now I added this to my VM-Options in my intellij runtime configurations:
-javaagent:/home/xxx/Downloads/apache-openjpa-3.1.2/openjpa-all-3.1.2.jar main.java.entity.Post
But it does not seem to recognise the class:
You have enabled runtime enhancement, but have not specified the set of persistent classes. OpenJPA must look for metadata for every loaded class, which might increase class load times significantly.
I thought the 2nd argument for javaagent is me specifiying the class but I am wrong.
This is my persistence.xml:
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" version="2.2"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_2.xsd">
<!-- Define persistence unit -->
<persistence-unit name="post">
<class>main.java.entity.Post</class>
<properties>
<property name="openjpa.DynamicEnhancementAgent" value="true"/>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/DSTEST" />
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.user" value="xxx" />
<property name="javax.persistence.jdbc.password" value="xxx" />
</properties>
</persistence-unit>
And this is my entity:
package main.java.entity;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity (name="post")
public class Post {
#Id
private Integer postid;
private String user;
private Integer datum;
private String inhalt;
public Integer getPostid() {
return postid;
}
public void setPostid(Integer postid) {
this.postid = postid;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public Integer getDatum() {
return datum;
}
public void setDatum(Integer datum) {
this.datum = datum;
}
public String getInhalt() {
return inhalt;
}
public void setInhalt(String inhalt) {
this.inhalt = inhalt;
}
}
I am using Intellij on Ubuntu.
I am receiving a NullPointerException with the following code and configuration, and I am not sure why. I would appreciate some help in debugging this issue.
File persistence.xml:
<persistence-unit name="adismPersistenceUnit" transaction-type="RESOURCE_LOCAL" >
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.adism.domain.Ad</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/adism" />
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="" />
</properties>
</persistence-unit>
Entity Class:
#Entity #Table(name = "ads") public class Ad {
private Integer adId;
private String adTitle;
public Ad(){}
#Id
#Column(name="adid")
#GeneratedValue
public Integer getAdId(){
return adId;
}
public void setAdId(Integer adId){
this.adId = adId;
}
#Column(name="adtitle")
public String getAdTitle(){
return this.adTitle;
}
public void setAdTitle(String title){
this.adTitle = title;
}
}
DAO Implementation:
public class AdDaoImpl implements AdDao{
#PersistenceContext
public EntityManager entityManager;
#Override
public void save(Ad ad){
entityManager.persist(ad);
}
}
When I run following code in JSP, I get NullPointerException
Ad ad = new Ad();
ad.setAdId(1000);
ad.setAdTitle("JPA pure");
AdDao newDao = new AdDaoImpl();
newDao.save(ad);
If you just do AdDao newDao = new AdDaoImpl(); your container will not known where to inject the EntityManager.
If you are using JBoss or Glassfish (or someother kind of EJB Containner) you need to declare AdDao as EJB:
#Stateless
public class AdDao () {}
And you will use it in your servlet like:
#EJB
public AdDao ejb;
PS.: I would not inject a DAO in a controller. The best is to use other classes between both, but if you are new to this kind of technology start with it.
If you are using a solution without JPA you can do something like:
private static EntityManagerFactory emf = Persistence.createEntityManagerFactory("YOUR_PERSISTENCE_UNIT"); // store it in your class
public void yourMethod(){
final EntityManager entityManager = entityManagerFactory.createEntityManager();
entityManager.getTransaction().begin();
// do your stuff here
entityManager.getTransaction().commit();
entityManager.close();
}
people!
I made a small project using Servlets / JBoss / Hibernate / Mysql.
I put Hibernate to generate tables automatically. My question is only that: When these table are generated? Tables should be created when I rise the JBoss or when I call the servlet in the browser?
Because I realized that they are created only when I call one of my Servlets, and I imagined they would be created when I rise the JBoss.
Sorry if it's silly.
Here is my Class:
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="estacoes")
public class Estacao {
#Id
#GeneratedValue
private int id;
private String nome;
private String endereco;
private String temperatura;
private String energia;
private String porta;
private String sinal;
private String bateria;
...getters/setters...
My persistence.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
version="2.0">
<persistence-unit name="arduinoserver">
<!-- provedor/implementacao do JPA -->
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<non-jta-data-source>java:jboss/datasources/MysqlDS</non-jta-data-source>
<!-- entidade mapaeada -->
<class>arduinoserver.beans.Estacao</class>
<properties>
<!-- propriedades do hibernate -->
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.connection.charSet" value="UTF-8" />
</properties>
</persistence-unit>
And my DAO:
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import arduinoserver.beans.Estacao;
public class EstacaoDAO {
protected EntityManager entityManager;
public EstacaoDAO() {
entityManager = getEntityManager();
}
private EntityManager getEntityManager() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("arduinoserver");
if(entityManager == null) {
entityManager = factory.createEntityManager();
}
return entityManager;
}
public Estacao getById(final int id) {
return entityManager.find(Estacao.class, id);
}
#SuppressWarnings("unchecked")
public List<Estacao> findAll() {
return entityManager.createQuery("FROM estacoes").getResultList();
}
public void persist(Estacao estacao) {
try {
entityManager.getTransaction().begin();
// entityManager.persist(estacao);
entityManager.merge(estacao);
entityManager.getTransaction().commit();
} catch(Exception ex) {
ex.printStackTrace();
entityManager.getTransaction().rollback();
}
}
}
As far as I know Hibernate creates the tables when the SessionFactory is created. The application server doesn't automatically create one on its own, therefor the tables are usually not created on the server start.
I use JPA MySQL to execute queries to database , but when I try to persists some entity no row is added to the table
Here is persistense.xml:
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
version="2.0">
<persistence-unit name="avtoparki" transaction-type="RESOURCE_LOCAL">
<description>
Persistence unit for the JPA tutorial of the Hibernate Getting Started Guide
</description>
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>Entities.City</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/world" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="tauren993" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQLDialect" />
<property name="hibernate.show_sql" value="true" />
<!-- <property name="hibernate.hbm2ddl.auto" value="create" /> -->
</properties>
</persistence-unit>
</persistence>
here is entity class:
#Entity
public class City {
#Id
//#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID")
int id;
#Column(name="Name")
String name;
#Column(name="CountryCode")
String CountryCode;
#Column(name="District")
String District;
#Column(name="Population")
int Population;
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 getCountryCode() {
return CountryCode;
}
public void setCountryCode(String countryCode) {
CountryCode = countryCode;
}
public String getDistrict() {
return District;
}
public void setDistrict(String district) {
District = district;
}
public int getPopulation() {
return Population;
}
public void setPopulation(int population) {
Population = population;
}
and here is code:
EntityManagerFactory emf = Persistence.createEntityManagerFactory("avtoparki");
EntityManager em = emf.createEntityManager();
City city = new City();
city.setCountryCode("Georgia");
city.setDistrict("AVOIE");
city.setName("Tbilisi");
city.setId(1);
em.persist(city);
em.close();
System.out.println("SAVED");
when I execute there is no error it just doesn't save it to table (the city table exists and the schema is the same
Seems to me, that you are missing a transaction. Try to save your city-object with following code:
private void save (City city, EntityManagerFactory emf) {
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
try {
tx.begin();
em.persist( city );
tx.commit();
} catch( RuntimeException ex ) {
if( tx != null && tx.isActive() ) tx.rollback();
throw ex;
} finally {
em.close();
}
}
I would try an explicit flush em.persist(), em.flush(), em.close(). Just to verify.
You should create a Default no-args constructor
public City() { }
Hibernate uses reflection to create objects
I am trying to get a simple example up and running using JPA in an EJB through GlassFish. I have the following persistence.xml
<persistence version="1.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_1_0.xsd">
<persistence-unit name="default" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/wms</jta-data-source>
<class>com.xxx.xxx.datamodel.MyTest</class>
<exclude-unlisted-classes />
<properties>
<property name="eclipselink.target-server" value="SunAS9"/>
<property name="eclipselink.logging.level" value="FINEST"/>
<property name="eclipselink.target-database" value="Oracle"/>
<property name="eclipselink.jdbc.driver" value="oracle.jdbc.OracleDriver" />
<property name="eclipselink.jdbc.url" value="[dbconnectionstring]" />
<property name="eclipselink.jdbc.user" value="user" />
<property name="eclipselink.jdbc.password" value="password" />
</properties>
</persistence-unit>
</persistence>
A simple entity:
package com.xxx.xxx.datamodel;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "move_task")
public class MyTest {
private int key;
private String description;
#Id
public int getKey(){
return key;
}
public void setKey(int key){
this.key = key;
}
public String getDescription(){
return this.description;
}
public void setDescription(String description){
this.description = description;
}
#Override
public String toString(){
return "Key: " + key + " Description: " + description;
}
}
And finally the following code to try use the above:
private void jpaCall() {
try{
emf = Persistence.createEntityManagerFactory("default");
em = emf.createEntityManager();
log.info("JPA init complete");
final List<MyTest> list = em.createQuery("select p from MyTest p").getResultList();
for (MyTest current : list) {
final String description = current.getDescription();
log.info("JPA: Desc: " + description);
}
}
catch(Exception e){
log.error("Error on JPA", e);
}
}
When this is run as part of my EJB initialisation I get the following error:
java.lang.IllegalArgumentException: An exception occurred while creating a query in EntityManager:
Exception Description: Error compiling the query [select p from MyTest p]. Unknown entity type [MyTest].
...
Caused by: Exception [EclipseLink-8034] (Eclipse Persistence Services - 2.0.0.v20091127-r5931): org.eclipse.persistence.exceptions.JPQLException
Exception Description: Error compiling the query [select p from MyTest p]. Unknown entity type [MyTest].
I am not sure what I am doing wrong and would appreciate any help.
Cheers,
James
So as the comments above suggest this seems to be an issue with the eclipse plug in for glassfish. I am having no problems when deploying the ear manually.
Thanks all for the help.
James