Hibernate: How configure EntityManager in Hibernate? - eclipse

I create a hibernate project with 'hibernate tools'provide by JBoss to Eclipse.
Generated the Entities (POJO's) and then the DAO's.
This way for example:
#Entity
#Table(name = "area", catalog = "project_schema", uniqueConstraints = #UniqueConstraint(columnNames = "area"))
public class Area implements java.io.Serializable {
private Integer id;
private String area;
public Area() {
}
public Area(String area) {
this.area = area;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "id", unique = true, nullable = false)
public Integer getId() {
return this.id;
}
public void setId(Integer id) {
this.id = id;
}
#Column(name = "area", unique = true, nullable = false, length = 45)
public String getArea() {
return this.area;
}
public void setArea(String area) {
this.area = area;
}
}
And then the respectely DAO class (generated by Hibernate Tools too):
#Stateless
public class AreaHome {
private static final Log log = LogFactory.getLog(AreaHome.class);
#PersistenceContext
private EntityManager entityManager;
public void persist(Area transientInstance) {
log.debug("persisting Area instance");
try {
entityManager.persist(transientInstance);
log.debug("persist successful");
} catch (RuntimeException re) {
log.error("persist failed", re);
throw re;
}
}
public void remove(Area persistentInstance) {
log.debug("removing Area instance");
try {
entityManager.remove(persistentInstance);
log.debug("remove successful");
} catch (RuntimeException re) {
log.error("remove failed", re);
throw re;
}
}
public Area merge(Area detachedInstance) {
log.debug("merging Area instance");
try {
Area result = entityManager.merge(detachedInstance);
log.debug("merge successful");
return result;
} catch (RuntimeException re) {
log.error("merge failed", re);
throw re;
}
}
public Area findById(Integer id) {
log.debug("getting Area instance with id: " + id);
try {
Area instance = entityManager.find(Area.class, id);
log.debug("get successful");
return instance;
} catch (RuntimeException re) {
log.error("get failed", re);
throw re;
}
}
}
But when I try to call AreaHome.persist() it launchs an exception 'NullPointerException'.
I configure my project with hibernate.cfg.xml and everything works fine though:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password"><password></property>
<property name="hibernate.connection.url">jdbc:mysql://<hostname>:3306/<schema></property>
<property name="hibernate.connection.username">root</property>
<!-- <property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property> -->
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<!-- SQL -->
<property name="hibernate.format_sql">true</property>
<property name="hibernate.show_sql">true</property>
<!-- C3P0 -->
<property name="hibernate.c3p0.acquire_increment">2</property>
<property name="hibernate.c3p0.max_size">20</property>
<property name="hibernate.c3p0.min_size">5</property>
<property name="hibernate.c3p0.timeout">180</property>
<property name="hibernate.c3p0.idle_test_period">100</property>
<!-- Classes -->
<mapping class="com.suaparte.pojo.Area" />
</session-factory>
</hibernate-configuration>
This works fine when I try:
public void persist(Area area) throws ExceptionHandler {
Session session = HibernateUtil.getSessionFactory().openSession();
try {
session.beginTransaction();
session.save(area);
session.getTransaction().commit();
} catch (HibernateException he) {
session.getTransaction().rollback();
throw new ExceptionHandler(he.getCause());
} finally {
if (session != null) {
session.close();
}
}
}
But I want to use the DAO's generated by Hibernate Tools because they have EntityManager (which is supposed to be injected, but isn't apparentely).
What I have to do ? Any idea ?
Sorry by the long question, but I wanna to be very clear about my problem.

In fact you need to implement a EntityManagerFactory.
Create a persistence.xml file that resides in the META-INF folder.
Take a look at example
http://docs.jboss.org/hibernate/entitymanager/3.6/reference/en/html_single/#setup-configuration-packaging
after the commands to create the EntityManagerFactory and EntityManager then:
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("JavaStackOver");
EntityManager entityManager = entityManagerFactory.createEntityManager();
Resolve dependencies, I used maven:
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>4.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.0.1.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-annotations</artifactId>
<version>3.5.6-Final</version>
</dependency>
Inject on your Dao JPA and Done!
The advantage of working with EntityManager is to have the option to change the Hibernate in futuro. Otherwise could use the Session.

Related

Having trouble getting JPA to work on Wildfly 19.1

I am fairly new to Wildfly and really new to JPA. I get a null exception when I try to call a method from the DAO. I made some changes suggested using the #Stateless and #Inject annotations, but the DAO does not appear to be initializing at all. The object is null when I try to call the findAllClientCompanies method.
Here is the peristence.xml file.
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="miscPU">
<jta-data-source>java:/jdbc/misc</jta-data-source>
<properties>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.transaction.flush_before_completion" value="true"/>
</properties>
</persistence-unit>
<persistence-unit name="autojobsPU">
<jta-data-source>java:/jdbc/autojobs</jta-data-source>
<properties>
<property name="hibernate.show_sql" value="false"/>
<property name="hibernate.transaction.flush_before_completion" value="true"/>
</properties>
</persistence-unit>
</persistence>
Here is the entity declaration:
#Entity
#Table(name="clientcompany")
public class ClientCompany extends Company implements Serializable {
Here is the dao, the findAllClientCompanies is the specific method that is blowing up with a null exception:
package com.lingosys.jpa;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.PersistenceContext;
import javax.persistence.TypedQuery;
import javax.persistence.Query;
import java.io.Serializable;
import java.util.List;
/**
*
* #author mphoenix
*/
#Stateless
public class ClientCompanyDAO implements Serializable {
#PersistenceContext(unitName="miscPU")
private EntityManager em;
public ClientCompanyDAO() {
}
public void create(ClientCompany clientCompany) {
em.persist(clientCompany);
}
public EntityTransaction getTransaction() {
return em.getTransaction();
}
public ClientCompany findClientCompany(int id) {
ClientCompany clientCompany = (ClientCompany) em.find(ClientCompany.class, id);
return clientCompany;
}
public List <ClientCompany> findAllClientCompanies() {
TypedQuery<ClientCompany> query = em.createQuery("select c from ClientCompany c", ClientCompany.class);
return query.getResultList();
}
public void delete(ClientCompany clientCompany) {
em.remove(em.contains(clientCompany) ? clientCompany:em.merge(clientCompany));
}
public int deleteAllClientCompanies() {
Query query = em.createQuery("delete from ClientCompany");
return query.executeUpdate();
}
}
And here is the JSF bean that calls the dao method:
#Inject
private ClientCompanyDAO daoClientCompany;
private boolean noValidEmail = false;
private String fakeEmailUserName = "";
private Connection conn;
private List<ClientCompany> unsortedList;
private String specialInstructions;
private String createdBy;
//XML processing variables
private Document document = null;
private String xmlMsgs = "";
private boolean xmlLoaderDisabled = false;
//prospect handling variables
private boolean prospectDisabled = false;
private static final String YES = "Yes";
//Legal entity based variables
boolean entitySet = false;
boolean lls = false;
boolean clientIDSet = false;
boolean billingInstructionsSet = false;
boolean billingEmailSet = false;
private static final String[] IS_LLS = {"LLS", "Coto/TI", "LLS-UK"};
boolean companyLoggedOn = false;
private boolean processDisabled = true;
private boolean userSpecificEntity = false;
/**
* Constructor initializes Web Service client, Hibernate DAOs, UI lists, and
* client view.
*
*/
public ClientCreatorBean() {
fmrws = new FormerWSOps();
try {
unsortedList = daoClientCompany.findAllClientCompanies();
view = fmrws.getClientCompanyView();
} catch (Exception ex) {
java.util.logging.Logger.getLogger(ClientCreatorBean.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
}
reset();
OK it looks like this problem had to do with my invoking the DAO in my constructor. I resolved it by putting the code in another method and prefacing that method with the #PostConstructor annotation.

Transactional CDI bean not committing record to database

I am trying to build a simple REST service, using JAX-RS, that will perform the standard CRUD operations on a database table. I am able to successfully query for records, but I cannot insert new ones. I do not get any errors and when I step through the code in debug mode everything looks good. I am using a transactional CDI bean running in a Glassfish 4.1 container.
It feels like it's just never committing the transaction. I'm pretty new to Java EE, but my understanding is that since the bean is transactional the container should handle the commit for me. Anyone know why it is not?
#Path("/recipes")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public class RecipeResource {
#Inject
RecipesService recipesService;
#GET
public List<Recipe> getRecipes() {
return recipesService.getAllRecipes();
}
#POST
public void addRecipse(Recipe recipe) {
recipesService.addRecipe(recipe);
}
}
public class RecipesService {
#PersistenceContext(unitName="PANTRYDB", type=PersistenceContextType.TRANSACTION)
EntityManager em;
public RecipesService () {
}
public List<Recipe> getAllRecipes () {
List<Recipe> recipes = null;
try {
TypedQuery<Recipe> typedQuery = em.createQuery("select r from Recipe r", Recipe.class);
recipes = typedQuery.getResultList();
} catch (Exception e) {
System.out.println(e);
}
return recipes;
}
#Transactional
//This is the method that seems to not commit it's transaction
//The Recipe object is populated correctly, and the persist() doesn't
//throw any errors
public void addRecipe(Recipe recipe) {
try {
em.persist(recipe);
} catch (Exception e) {
System.out.println(e);
}
}
}
#Entity
#Table(name="RECIPES", schema="COOKBOOK")
public class Recipe {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column
private String name;
#Column(name="CREATED_DATE")
private Calendar createdDate;
#Column(name="LAST_MADE_DATE")
private Calendar lastMadeDate;
#Column
private String description;
#Column
private String notes;
public int getId() {
return id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Calendar getCreatedDate() {
return createdDate;
}
public void setCreatedDate(Calendar createdDate) {
this.createdDate = createdDate;
}
public Calendar getLastMadeDate() {
return lastMadeDate;
}
public void setLastMadeDate(Calendar lastMadeDate) {
this.lastMadeDate = lastMadeDate;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
#Override
public String toString() {
return name;
}
}
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="PANTRYDB" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>com.domain.Recipe</class>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeddedDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:derby:/Users/development/eclipse/ws_playground/databases/pantry_db/PANTRYDB" />
<property name="hibernate.dialect" value="org.hibernate.dialect.DerbyDialect"/>
<property name="javax.persistence.jdbc.user" value=""/>
<property name="javax.persistence.jdbc.password" value=""/>
</properties>
</persistence-unit>
</persistence>
I tried your application on a weblogic 12.2.1 and it successfully inserted in database and i do not have any problem with transaction.
Here is my code.
RecipeResource class (I modified the #Path to call it via web browser and also instanciated the Recipe manually):
#Path("/recipes")
#Consumes(MediaType.APPLICATION_JSON)
#Produces(MediaType.APPLICATION_JSON)
public class RecipeResource {
#Inject
RecipesService recipesService;
#GET
#Path("get")
public List<Recipe> getRecipes() {
return recipesService.getAllRecipes();
}
#GET
#Path("add")
public String addRecipse() {
Recipe recipe = new Recipe();
recipe.setDescription("desc");
recipesService.addRecipe(recipe);
return "OK";
}
}
The Recipe class is same as yours except that i commented the schema :
#Entity
#Table(name="RECIPES") //, schema="COOKBOOK")
public class Recipe {
}
My persistence.xml (I'm using in-memory database):
<?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="PANTRYDB" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/__default</jta-data-source>
<class>org.jvi.webservice.transactional.db.Recipe</class>
<properties>
<!--<property name="eclipselink.ddl-generation" value="create-tables"/>-->
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
<property name="eclipselink.logging.level" value="FINE"/>
<property name="eclipselink.logging.level.sql" value="FINE"/>
<property name="eclipselink.logging.parameters" value="true"/>
<property name="eclipselink.logging.logger" value="DefaultLogger"/>
<property name="eclipselink.cache.shared.default" value="false"/>
</properties>
</persistence-unit>
So your problem might come from the Application Server.
Did you try to deploy your webapp on another server?
When you are using JTA transaction management, responsibility for creating and managing database connections is provided by application server, not your application.
Basically, you have to configure your data source in your GlassFish server instance, not directly in persistence.xml via properties:
Configure connection pool and datasource JNDI name in your GlassFish server instance
Link data source configuration in your persistence.xml via <jta-data-source> element
Please check this answer for further details:
https://stackoverflow.com/a/9137741/1980178
Are you sure you are not mixing two frameworks. RecipeResource has a #Path annotation which is from the JavaEE framework, and the #Transactional annotation is from the Spring framework, I think you should replace it with #TransactionAttribute which is the equivalent JavaEE anotation.
Have a look here for details between transaction in Spring an JavaEE

JPA EntityManager Nullpointer exception (which shouldn't be!?)

My ejb code:
#Stateless
public class EmployeeBean {
#PersistenceContext(unitName="Eclipselink_JPA")
private EntityManager entitymanager;
public void createEmployee(){
Employee employee = new Employee( );
employee.setEid( 1201 );
employee.setEname( "Gopal" );
employee.setSalary( 40000 );
employee.setDeg( "Technical Manager" );
entitymanager.persist( employee );
entitymanager.getTransaction( ).commit( );
entitymanager.close( );
}
}
Basically, nullpointer exception happens at the line where entitymanager.persist is called, which should not happen right?
My persistence.xml file
<?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="Eclipselink_JPA" transaction-type="RESOURCE_LOCAL">
<class>com.jpa.beans.Employee</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:file:E:\HQLDB_AJ"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value="password"/>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbc.JDBCDriver"/>
<property name="eclipselink.logging.level" value="FINE"/>
<property name="eclipselink.ddl-generation" value="create-tables"/>
</properties>
</persistence-unit>
</persistence>
I have eclipselink.jar and other eclipselink jpa jars in my class path.
Here is my entity beans:
#Entity
#Table
public class Employee {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int eid;
private String ename;
private double salary;
private String deg;
public Employee(int eid, String ename, double salary, String deg) {
super( );
this.eid = eid;
this.ename = ename;
this.salary = salary;
this.deg = deg;
}
public Employee( ) {
super();
}
public int getEid( ) {
return eid;
}
public void setEid(int eid) {
this.eid = eid;
}
public String getEname( ) {
return ename;
}
public void setEname(String ename) {
this.ename = ename;
}
public double getSalary( ) {
return salary;
}
public void setSalary(double salary) {
this.salary = salary;
}
public String getDeg( ) {
return deg;
}
public void setDeg(String deg) {
this.deg = deg;
}
#Override
public String toString() {
return "Employee [eid=" + eid + ", ename=" + ename + ", salary=" + salary + ", deg=" + deg + "]";
}
}
Whats seems to be the problem? can anyone help? ive been figuring this out of a day now.
Problem solved: i shouldn't be using resource local because i was running it in an app server. thanks for the help anyway. well appreciated
When you set transaction-type="RESOURCE_LOCAL" in persistence.xml config file, it means that YOU (=your application's code) will take care of creating EntityManager and also will handle transactions yourself. In such case what you can demand to be injected by your underlying container is EntityManagerFactory and you can do it by using #PersistenceUnit annotation. On such object you simply call createEntityManager() that gives you EntityManager.
If you want to use EntityManager supplied by the container you must specify transaction-type="JTA". Then you annotate EntityManager exactly as in your code, and do not care of creating, committing or rolling back a transaction. It will be done by the container that will use JTA transaction and decide when to create, commit or rollback it.
Those two ways are commonly known as respectively Application Managed EntityManager and Container Managed EntityManager
You can find more details on how to work with each of two ways of handling transactions here or here
You dont have <provider> in your persistence.xml.. Try adding it.
Ex:
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
or <provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider> or
<provider>org.hibernate.ejb.HibernatePersistence</provider>
depending on your container.
HTH

no persistence provider for entitymanager named - tried everything

I'm new to JPA, and i got this infamous error "no persistence provider for entitymanager named". I search far and wide on google, and tried every single solution available, to no extent i'm afraid.
Stack Trace
javax.persistence.PersistenceException: No Persistence provider for EntityManager named suplink
at javax.persistence.Persistence.createEntityManagerFactory(Unknown Source)
at javax.persistence.Persistence.createEntityManagerFactory(Unknown Source)
at com.supinfo.suplink.util.PersistenceManager.getEntityManagerFactory(PersistenceManager.java:13)
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="suplink" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/SupLink" />
<property name="hibernate.hbm2ddl.auto" value="update" />
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5Dialect" />
</properties>
<class>com.supinfo.suplink.entity.User</class>
</persistence-unit>
PersistenceManager
public class PersistenceManager {
private static EntityManagerFactory emf;
private PersistenceManager() { }
public static EntityManagerFactory getEntityManagerFactory() {
if(emf == null) {
emf = Persistence.createEntityManagerFactory("suplink");
}
return emf;
}
public static void closeEntityManagerFactory() {
if(emf != null && emf.isOpen()) emf.close();
}
}
Thanks for your help :)
try to remove the transaction-type="RESOURCE_LOCAL"
works on my machine without this code
Good luck for your graded exercise, try code underneath ;)
public class PersistenceManager {
private static final EntityManagerFactory emf;
private static final ThreadLocal<EntityManager> threadLocal;
private static final Logger logger;
static {
emf = Persistence.createEntityManagerFactory("SupLink");
threadLocal = new ThreadLocal<EntityManager>();
logger = Logger.getLogger("SupLink");
logger.setLevel(Level.ALL);
}
public static EntityManager getEntityManager() {
EntityManager manager = threadLocal.get();
if (manager == null || !manager.isOpen()) {
manager = emf.createEntityManager();
threadLocal.set(manager);
}
return manager;
}
public static void closeEntityManager() {
EntityManager em = threadLocal.get();
threadLocal.set(null);
if (em != null)
em.close();
}
public static void beginTransaction() {
getEntityManager().getTransaction().begin();
}
public static void commit() {
getEntityManager().getTransaction().commit();
}
public static void rollback() {
getEntityManager().getTransaction().rollback();
}
public static Query createQuery(String query) {
return getEntityManager().createQuery(query);
}
public static void log(String info, Level level, Throwable ex) {
logger.log(level, info, ex);
}
}

JPA java.lang.IllegalArgumentException: Object: [ id=XYZ ] is not a known entity type

I am faceing the following problem:
when i run my programme i get the following exceptions:
java.lang.IllegalArgumentException: Object: dviaufgabe1.MeinArtikel[
id=25 ] is not a known entity type. at
org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4128)
at
org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:406)
at dviaufgabe1.DVIAufgabe1.persist(DVIAufgabe1.java:78) at
dviaufgabe1.DVIAufgabe1.erstelleBasisDaten(DVIAufgabe1.java:55) at
dviaufgabe1.DVIAufgabe1.main(DVIAufgabe1.java:22)
or (for auto gen keys)
java.lang.IllegalArgumentException: Object: dviaufgabe1.MeinArtikel[
id=null ] is not a known entity type. at
org.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObjectForPersist(UnitOfWorkImpl.java:4128)
at
org.eclipse.persistence.internal.jpa.EntityManagerImpl.persist(EntityManagerImpl.java:406)
at dviaufgabe1.DVIAufgabe1.persist(DVIAufgabe1.java:78) at
dviaufgabe1.DVIAufgabe1.erstelleBasisDaten(DVIAufgabe1.java:56) at
dviaufgabe1.DVIAufgabe1.main(DVIAufgabe1.java:22)
MeinArtikel.java
#Entity
public class MeinArtikel implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long artikelNummer;
private String name;
private String beschreibung;
private long preis;
private long lagerbestand;
public Long getArtikelNummer() {
return artikelNummer;
}
public String getBeschreibung() {
return beschreibung;
}
public long getLagerbestand() {
return lagerbestand;
}
public String getName() {
return name;
}
public long getPreis() {
return preis;
}
public void setBeschreibung(String beschreibung) {
this.beschreibung = beschreibung;
}
public void setLagerbestand(long lagerbestand) {
this.lagerbestand = lagerbestand;
}
public void setName(String name) {
this.name = name;
}
public void setPreis(long preis) {
this.preis = preis;
}
public void setArtikelNummer(Long id) {
this.artikelNummer = id;
}
#Override
public int hashCode() {
int hash = 0;
hash += (artikelNummer != null ? artikelNummer.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the artikelNummer fields are not set
if (!(object instanceof MeinArtikel)) {
return false;
}
MeinArtikel other = (MeinArtikel) object;
if ((this.artikelNummer == null && other.artikelNummer != null) || (this.artikelNummer != null && !this.artikelNummer.equals(other.artikelNummer))) {
return false;
}
return true;
}
#Override
public String toString() {
return "dviaufgabe1.MeinArtikel[ id=" + artikelNummer + " ]";
}
main class:
public class DVIAufgabe1 {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
erstelleBasisDaten();
}
public static void erstelleBasisDaten() {
MeinArtikel a1 = new MeinArtikel();
// a1.setArtikelNummer(23L);
a1.setName("Bachelor of Science - Informatik (WH)");
a1.setBeschreibung("Informatik Bachelor der Westfälischen Hochschule");
a1.setPreis(0L);
a1.setLagerbestand(100L);
MeinArtikel a2 = new MeinArtikel();
// a2.setArtikelNummer(24L);
a2.setName("Master of Science - Informatik (WH)");
a2.setBeschreibung("Informatik Master der Westfälischen Hochschule");
a2.setPreis(100L);
a2.setLagerbestand(50L);
MeinArtikel a3 = new MeinArtikel();
// a3.setArtikelNummer(25L);
a3.setName("Master of Science - Informatik (TU München)");
a3.setBeschreibung("Informatik Master der TU München");
a3.setPreis(10000L);
a3.setLagerbestand(5L);
MeinArtikel a4 = new MeinArtikel();
// a4.setArtikelNummer(26L);
a4.setName("Abitur NRW");
a4.setBeschreibung("Abitur der Klasse 13");
a4.setPreis(1000L);
a4.setLagerbestand(500L);
persist(a1);
persist(a2);
persist(a3);
persist(a4);
}
public static void persist(Object object) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("DVIAufgabe1PU");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
try {
em.persist(object);
em.getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
em.getTransaction().rollback();
} finally {
em.close();
}
}
persictence.xml
<?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="DVIAufgabe1PU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>dviaufgabe1. MeinArtikel</class>
<class>dviaufgabe1.MeineKategorie</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:derby://localhost:1527/DVIAufgabe1"/>
<property name="javax.persistence.jdbc.password" value="myuser"/>
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.ClientDriver"/>
<property name="javax.persistence.jdbc.user" value="myuser"/>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
</properties>
</persistence-unit>
</persistence>
Firstly, you should delete the space in the persistence.xml, right before "MeinArtikel" in the first tag class. Then after
<class>dviaufgabe1.MeineKategorie</class>
add this line
<exclude-unlisted-classes>false</exclude-unlisted-classes>
you are missing a space in the persistence.xml, right before "MeinArtikel"