I am trying to get a javax.persistence running, but I get erros.
I built up a little project for testing, creating an entity class, the persistence.xml, and the running process:
Entity class:
package glasses;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Hund implements Serializable {
#Id
private long id;
private String name;
private String typ;
public long getId() {
return this.id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getTyp() {
return this.typ;
}
public void setTyp(String typ) {
this.typ = typ;
}
}
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="GlassesPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/glasses?zeroDateTimeBehavior=convertToNull"/>
<property name="javax.persistence.jdbc.password" value="mypwd"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create"/>
</properties>
</persistence-unit>
</persistence>
Error message:
Caused by: java.lang.IllegalArgumentException: Object: glasses.Hund#5d2e0422 is not a known entity type.
at org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4228)
at org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:496)
at glasses.FXMLDocumentController.handleButtonAction(FXMLDocumentController.java:48)
... 54 more
Does anyone know the problem? Is there anything wrong in the Hund-class? Or in the persistence.xml?
Use your Hund class inside your persistence.xml like following example. Just place it between the properties and the persistence-unit tags.
</properties>
<class>glasses.Hund</class>
</persistence-unit>
If you don't want to list in the persistence.xml all your entities you can add the following line in the persistence.xml:
<exclude-unlisted-classes>false</exclude-unlisted-classes>
Related
I have a basic test for an embedded database that I'm trying to get working for a java project. As it stands now I am able to save rows to the database with my entity repository object, and after the app finishes running, I can connect to the database with intellij and see those rows are still there. But then, if I comment out the save methods and run it again, when I check the database after it finishes, the database is empty.
Entity
package closet.utilities.entities;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "outfits")
public class Outfit {
#Id
#Column(name = "id")
String id;
#Column(name = "inv_name")
String invName;
#Column(name = "display_name")
String displayName;
#Column(name = "owner")
String owner;
public Outfit() {
}
public Outfit(String id, String invName, String displayName, String owner) {
this.id = id;
this.invName = invName;
this.displayName = displayName;
this.owner = owner;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getInvName() {
return invName;
}
public void setInvName(String invName) {
this.invName = invName;
}
public String getDisplayName() {
return displayName;
}
public void setDisplayName(String displayName) {
this.displayName = displayName;
}
public String getOwner() {
return owner;
}
public void setOwner(String owner) {
this.owner = owner;
}
#Override
public String toString() {
return "Outfit{" +
"id='" + id + '\'' +
", invName='" + invName + '\'' +
", displayName='" + displayName + '\'' +
", owner='" + owner + '\'' +
'}';
}
}
Repository
package closet.utilities.repositories;
import closet.utilities.entities.Outfit;
import javax.persistence.EntityManager;
import java.util.List;
import java.util.Optional;
public class OutfitRepository {
private EntityManager entityManager;
public OutfitRepository(EntityManager entityManager) {
this.entityManager = entityManager;
}
public Optional<Outfit> findById(String id) {
Outfit outfit = entityManager.find(Outfit.class, id);
return outfit != null ? Optional.of(outfit) : Optional.empty();
}
public List<Outfit> findAll() {
return entityManager.createQuery("from Outfit").getResultList();
}
public Optional<Outfit> save(Outfit outfit) {
try {
entityManager.getTransaction().begin();
entityManager.persist(outfit);
entityManager.getTransaction().commit();
return Optional.of(outfit);
} catch (Exception e) {
// TODO logging
e.printStackTrace();
}
return Optional.empty();
}
}
main method
package closet.utilities;
import closet.utilities.entities.Outfit;
import closet.utilities.repositories.OutfitRepository;
import org.hibernate.Session;
import org.hibernate.Transaction;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import java.util.List;
public class Runnable {
public static void main(String[] args) {
// Create our entity manager
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("closet");
EntityManager entityManager = entityManagerFactory.createEntityManager();
Outfit outfit = new Outfit("Ramesh", "Fadatare", "rameshfadatare#javaguides.com", "");
Outfit outfit1 = new Outfit("John", "Cena", "john#javaguides.com", "");
OutfitRepository outfitRepository = new OutfitRepository(entityManager);
//outfitRepository.save(outfit);
//outfitRepository.save(outfit1);
List<Outfit> outfits = outfitRepository.findAll();
for (Outfit o : outfits) {
System.out.println(o.getInvName());
}
}
}
persistence.xml
<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" xmlns="http://java.sun.com/xml/ns/persistence">
<persistence-unit name="closet" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>closet.utilities.entities.Outfit</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:h2:./data/closet" />
<property name="javax.persistence.jdbc.user" value="sa" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<property name="hibernate.hbm2ddl.auto" value="create-drop" />
<property name="show_sql" value="true"/>
<property name="hibernate.temp.use_jdbc_metadata_defaults" value="false"/>
</properties>
</persistence-unit>
</persistence>
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>
<!-- JDBC Database connection settings -->
<property name="connection.driver_class">org.h2.Driver</property>
<property name="connection.url">jdbc:h2:./data/closet</property>
<property name="connection.username">sa</property>
<property name="connection.password"></property>
<!-- JDBC connection pool settings ... using built-in test pool -->
<property name="connection.pool_size">1</property>
<!-- Select our SQL dialect -->
<property name="dialect">org.hibernate.dialect.H2Dialect</property>
<!-- Echo the SQL to stdout -->
<property name="show_sql">true</property>
<!-- Set the current session context -->
<property name="current_session_context_class">thread</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">create-drop</property>
<!-- dbcp connection pool configuration -->
<property name="hibernate.dbcp.initialSize">5</property>
<property name="hibernate.dbcp.maxTotal">20</property>
<property name="hibernate.dbcp.maxIdle">10</property>
<property name="hibernate.dbcp.minIdle">5</property>
<property name="hibernate.dbcp.maxWaitMillis">-1</property>
<mapping class="closet.utilities.entities.Outfit" />
</session-factory>
</hibernate-configuration>
I'm just following this tutorial here as a guide to just figure out how to get it all working. I can't see what I'm doing wrong based on that.
You use:
<property name="hbm2ddl.auto">create-drop</property>
As it is stated in the documentation:
create-drop
Drop the schema and recreate it on SessionFactory startup. Additionally, drop the schema on SessionFactory shutdown.
So, this is expected behaviour.
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'm trying to understand JPA/Hibernate, I'm able to create new database but I don't understand how insert new row in my
database.
This is the code:
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
#Entity
public class Person implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String name;
private String adress;
private String phoneNumber;
public void setName(String name) {
this.name = name;
}
public void setAdress(String adress) {
this.adress = adress;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
public String getName() {
return name;
}
public String getAdress() {
return adress;
}
public String getPhoneNumber() {
return phoneNumber;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (id != null ? id.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Person)) {
return false;
}
Person other = (Person) object;
if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) {
return false;
}
return true;
}
#Override
public String toString() {
return "entinty.Person[ id=" + id + " ]";
}
}
The class that create the database is:
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
public class Main {
public static void main(String args[]) {
Person p = new Person();
p.setName("xxx");
p.setAdress("yyy");
p.setPhoneNumber("zzz");
EntityManagerFactory emf = javax.persistence.Persistence.createEntityManagerFactory("testPU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
try {
em.persist(p);
em.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
em.getTransaction().rollback();
}
em.close();
emf.close();
}
}
At this point I have a table with one row (with written "xxx-yyy-zzz"). How can I add new row? Creating new Person doesn't work because it creates new table... I only find solution using Session and SessionFactory but I'm not able to use it, because I can't understand how generate a hibernate.cfg.xml (and in general how to create a session object).
Is There a solution using only EntityManager? Or how can I generate/write a hibernate.cfg.xml file? Is there a way to generate automatically it using netbeans?
EDIT: this is my persistence.xml file. Where do I have to put the ? I put it in the *** zone but it doesn't work...
<?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="testPU" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>test.Person</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/stackoverflow?zeroDateTimeBehavior=convertToNull"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="leonida95."/>
<property name="hibernate.cache.provider_class" value="org.hibernate.cache.NoCacheProvider"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
*****
</properties>
</persistence-unit>
</persistence>
Inside your Persistence Unit file you'll have something like
<properties>
<property name="hibernate.connection.url" value="..." />
<property name="hibernate.connection.driver_class" value="..."/>
...
</properties>
To create tables when the EntityManagerFactory is constructed, just add
<property name="hibernate.hbm2ddl.auto" value="create" />
Your code works fine.
You can call persist as many times as you want, and it will add rows to the target table.
em.persist(person1);
em.persist(person2);
...
persist does not create a table.
I have an EJB3 entity bean Player which is annotated as given below:
#Entity
#Table(name = "PLAYER")
public class Player {
public Player() {
super();
}
#Id
#GeneratedValue
private String id;
#Column(nullable = false)
private String firstName;
private String lastName;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
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;
}
}
I am using Apache Derby DB to persist this. I have a persistence.xml file which explains the hibernate properties and I have define hibernate.hbm2ddl.auto=create.
<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="PlayerApp" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>com.cricinfo.domain.Player</class>
<properties>
<property name="hibernate.connection.driver_class" value="org.apache.derby.jdbc.ClientDriver" />
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect"/>
<property name="hibernate.hbm2ddl.auto" value="create" />
<property name="hibernate.connection.url"
value="jdbc:derby://localhost:1527/PlayerAppDB;create=true" />
<property name="hibernate.show_sql" value="true" />
<property name="hibernate.format_sql" value="true" />
</properties>
</persistence-unit>
But when I try to persist this object I get an exception saying
Caused by: org.apache.derby.client.am.SqlException: Table/View 'PLAYER' does not exist.
at org.apache.derby.client.am.Statement.completeSqlca(Unknown Source)
Isn't it supposed to auto create the tables since I have set the property hibernate.hbm2ddl.auto ? Or is there something that I am missing?
My main method is as shown below:
public static void main(String[] args) {
Player p = new Player();
p.setFirstName("A");
p.setLastName("BC");
EntityManagerFactory factory = Persistence.createEntityManagerFactory("PlayerApp");
EntityManager entityMgr = factory.createEntityManager();
EntityTransaction tx = entityMgr.getTransaction();
tx.begin();
entityMgr.persist(p);
tx.commit();
entityMgr.close();
factory.close();
}
Add the below property
<property name="hibernate.generateDdl" value="true" />
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