Description
i simply want to implement ORM using Hibernate with mysql but the only
methods that are working are adding a single object to the database, returning
a list of objects, returning a list of objects by a keyword but deleting an
object and updating an object are not functioning!
any suggestion?
the table is created in the database with no problem :)
Entity
package dao;
import java.io.Serializable;
import javax.persistence.Entity;
import javax.persistence.Id;
#Entity
public class Produit implements Serializable{
private static final long serialVersionUID = 8314029847799979249L;
#Id
private int ref;
private String desig;
private double prix;
private int quant;
public Produit() {}
public int getId() {
return ref;
}
public void setId(int ref) {
this.ref = ref;
}
public String getDesig() {
return desig;
}
public void setDesig(String desig) {
this.desig = desig;
}
public double getPrix() {
return prix;
}
public void setPrix(double prix) {
this.prix = prix;
}
public int getQuant() {
return quant;
}
public void setQuant(int quant) {
this.quant = quant;
}
}
Interface
package dao;
import java.util.List;
public interface InterfaceProduit {
public void addProduit(Produit produit);
public Produit getProduit(int id);
public List<Produit> getListProduit();
public List<Produit> getListProduitbykw(String mc);
public void updateProduit(Produit p);
public void deleteProduit(int id);
}
Iplementation
package dao;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import javax.persistence.Query;
import javax.transaction.Transactional;
#Transactional
public class ImplInterfProduit implements InterfaceProduit{
EntityManager manager;
public ImplInterfProduit() {
EntityManagerFactory factory = Persistence.createEntityManagerFactory("sample");
manager = factory.createEntityManager();
}
public void addProduit(Produit produit) {
EntityTransaction transaction = manager.getTransaction();
transaction.begin();
try {
manager.persist(produit);
transaction.commit();
}catch(Exception ex) {
transaction.rollback();
ex.printStackTrace();
}
}
public Produit getProduit(int id) {
Produit p = manager.find(Produit.class, id);
return p;
}
public List<Produit> getListProduit() {
Query query = manager.createQuery("SELECT p FROM Produit p");
return query.getResultList();
}
public List<Produit> getListProduitbykw(String mc) {
Query query = manager.createQuery("SELECT p FROM Produit p where
p.desig LIKE :x");
query.setParameter("x", "%"+mc+"%");
return query.getResultList();
}
public void updateProduit(Produit p) {
manager.merge(p);
}
public void deleteProduit(int id) {
Produit p = manager.find(Produit.class, id);
manager.remove(p);
}
}
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="sample">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/product"/>
<property name="hibernate.connection.username" value="product"/>
<property name="hibernate.connection.password" value="product"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.hbm2ddl.auto" value="update"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.MySQL5InnoDBDialect"/>
</properties>
</persistence-unit>
</persistence>
Main
package dao;
public class MainApp {
public static void main(String[] args) {
Produit p = new Produit();
p.setId(9114);
p.setDesig("telecom");
p.setPrix(654.77);
p.setQuant(40);
ImplInterfProduit implProd = new ImplInterfProduit();
implProd.addProduit(p);
implProd.updateProduit(p);
implProd.deleteProduit(8760);
}
}
POM
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.yusfi</groupId>
<artifactId>jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-core</artifactId>
<version>5.4.10.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.5.Final</version>
</dependency>
<dependency>
<groupId>org.hibernate.javax.persistence</groupId>
<artifactId>hibernate-jpa-2.0-api</artifactId>
<version>1.0.1.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.46</version>
</dependency>
</dependencies>
</project>
Output
Hibernate: insert into Produit (desig, prix, quant, ref) values (?, ?, ?, ?)
Hibernate: select produit0_.ref as ref1_0_0_, produit0_.desig as desig2_0_0_,
produit0_.prix as prix3_0_0_, produit0_.quant as quant4_0_0_ from Produit
produit0_ where produit0_.ref=?
public List<Produit> getListProduit() {
Query query = manager.createQuery("FROM Produit", Produit.class);
return query.getResultList();
}
public List<Produit> getListProduitbykw(String mc) {
Query query = manager.createQuery("FROM Produit P WHERE P.desig LIKE :x", Produit.class);
query.setParameter("x", "%"+mc+"%");
return query.getResultList();
}
Related
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.
When i try to get items in the db i get a error that booking isn't mapped
I tried everything tried to put the #Entity on top and #MappedSuperclass but nothing really worked
This is the error:
SEVERE: Servlet.service() for servlet [be.pxl.tafelboeker.servlets.ConfirmServlet] in context with path [/HerexamensOef] threw exception
java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: booking is not mapped [select b from booking as b where (b.dag=?1 AND b.uur =?2) ]
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:131)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:155)
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:162)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:636)
at org.hibernate.internal.AbstractSessionImpl.createQuery(AbstractSessionImpl.java:23)
at be.pxl.tafelboeker.dao.BoekingDAO.isTafelBeschikbaar(BoekingDAO.java:44)
at be.pxl.tafelboeker.services.BoekingService.isTafelBeschikbaar(BoekingService.java:28)
at be.pxl.tafelboeker.services.BoekingService.boekTafel(BoekingService.java:34)
at be.pxl.tafelboeker.servlets.ConfirmServlet.doPost(ConfirmServlet.java:59)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:292)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:240)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:207)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:212)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:106)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:502)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:141)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:79)
at org.apache.catalina.valves.AbstractAccessLogValve.invoke(AbstractAccessLogValve.java:616)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:88)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:522)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1095)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:672)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.doRun(NioEndpoint.java:1502)
at org.apache.tomcat.util.net.NioEndpoint$SocketProcessor.run(NioEndpoint.java:1458)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Unknown Source)
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: booking is not mapped [select b from booking as b where (b.dag=?1 AND b.uur =?2) ]
at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:79)
at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:103)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:218)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.compile(QueryTranslatorImpl.java:142)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:115)
at org.hibernate.engine.query.spi.HQLQueryPlan.<init>(HQLQueryPlan.java:77)
at org.hibernate.engine.query.spi.QueryPlanCache.getHQLQueryPlan(QueryPlanCache.java:152)
at org.hibernate.internal.AbstractSharedSessionContract.getQueryPlan(AbstractSharedSessionContract.java:526)
at org.hibernate.internal.AbstractSharedSessionContract.createQuery(AbstractSharedSessionContract.java:628)
... 28 more
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: booking is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:171)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:91)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:79)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:321)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3690)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3579)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:718)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:574)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:311)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:259)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:262)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:190)
... 34 more
here some files
Boeking
package be.pxl.tafelboeker.domain;
import java.io.Serializable;
import java.time.LocalDate;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.MappedSuperclass;
import javax.persistence.Table;
#Table(name="booking")
public class Boeking implements Serializable {
#Id
#Column(name="id")
#GeneratedValue
private int id;
#Column(name="naam")
private String naam;
#Column(name="straat")
private String straat;
#Column(name="stad")
private String stad;
#Column(name="uur")
private Integer uur;
#Column(name="dag")
private LocalDate dag;
public Boeking(){
}
public String getStraat() {
return straat;
}
public void setStraat(String straat) {
this.straat = straat;
}
public String getStad() {
return stad;
}
public void setStad(String stad) {
this.stad = stad;
}
public String getNaam() {
return naam;
}
public void setNaam(String naam) {
this.naam = naam;
}
public Integer getUur() {
return uur;
}
public void setUur(Integer uur) {
this.uur = uur;
}
public LocalDate getDag() {
return dag;
}
public void setDag(LocalDate dag){
this.dag = dag;
}
}
persistance
<?xml version="1.0" encoding="UTF-8"?>
<persistence 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"
version="2.1">
<persistence-unit name="booking" transaction-type="RESOURCE_LOCAL">
<properties>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver" />
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost/booking" />
<property name="javax.persistence.jdbc.user" value="root" />
<property name="javax.persistence.jdbc.password" value="" />
<property name="javax.persistence.schema-generation.database.action"
value="none" />
<!-- Hibernate specific -->
<property name="hibernate.show_sql" value="true" />
</properties>
</persistence-unit>
</persistence>
pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>be.pxl</groupId>
<artifactId>HerexamensOef</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>HerexamensOef Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-web-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<dependency>
<groupId>javax.persistence</groupId>
<artifactId>persistence-api</artifactId>
<version>1.0.2</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>5.2.2.Final</version>
</dependency>
</dependencies>
<build>
<finalName>HerexamensOef</finalName>
</build>
</project>
Boeking DAO
package be.pxl.tafelboeker.dao;
import be.pxl.tafelboeker.domain.Boeking;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityManager;
import javax.persistence.Persistence;
import javax.persistence.Query;
import java.time.LocalDate;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
public class BoekingDAO {
private String url;
private String user;
private String password;
EntityManagerFactory emf;
public BoekingDAO(String url, String user, String password) {
this.url = url;
this.user = user;
this.password = password;
}
public void setDriver(String driver)
throws ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
}
private EntityManager getEntityManager() {
emf = Persistence.createEntityManagerFactory("booking");
EntityManager em = emf.createEntityManager();
return em;
}
// TIP : Gebruik TemporalType.DATE voor je query parameter
public boolean isTafelBeschikbaar(LocalDate dag, int uur) {
EntityManager em = getEntityManager();
Query q1 = em.createQuery("select b from booking as b where (b.dag=?1 AND b.uur =?2) ");
q1.setParameter(1, dag);
q1.setParameter(2, uur);
if (q1.getMaxResults() == 0) {
return true;
} else {
return false;
}
}
public void boekTafel(Boeking bean) {
EntityManager em = getEntityManager();
em.persist(bean);
em.close();
emf.close();
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
public String getUser() {
return user;
}
public void setUser(String user) {
this.user = user;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
DriverLoader
package be.pxl.tafelboeker.dao;
public class DriverLoader {
static{
System.out.print("loading database");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("nope");
e.printStackTrace();
}
}
}
I am new in jpa and I am tryingg to write and execute a sample founded here:Sample JPA
This is my table created:
Here is my persistance.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.0" 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_0.xsd">
<persistence-unit name="EmployeeService" transaction-type="RESOURCE_LOCAL">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>ir.ac.sbu.testsimplesql1.Employee</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/library?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="pass"/>
<property name="hibernate.archive.autodetection" value="class"/>
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hbm2ddl.auto" value="update"/>
</properties>
I have auto generate model class from database:
package ir.ac.sbu.testsimplesql1;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.xml.bind.annotation.XmlRootElement;
#Entity
#Table(name = "Employee")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Employee.findAll", query = "SELECT e FROM Employee e"),
#NamedQuery(name = "Employee.findById", query = "SELECT e FROM Employee e WHERE e.id = :id"),
#NamedQuery(name = "Employee.findByFistName", query = "SELECT e FROM Employee e WHERE e.fistName = :fistName"),
#NamedQuery(name = "Employee.findByLastName", query = "SELECT e FROM Employee e WHERE e.lastName = :lastName"),
#NamedQuery(name = "Employee.findByDept", query = "SELECT e FROM Employee e WHERE e.dept = :dept")})
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Column(name = "fistName")
private String fistName;
#Column(name = "lastName")
private String lastName;
#Column(name = "dept")
private String dept;
public Employee() {
}
public Employee(Integer id) {
this.id = id;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFistName() {
return fistName;
}
public void setFistName(String fistName) {
this.fistName = fistName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getDept() {
return dept;
}
public void setDept(String dept) {
this.dept = dept;
}
#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 Employee)) {
return false;
}
Employee other = (Employee) 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 "ir.ac.sbu.testsimplesql1.Employee[ id=" + id + " ]";
}
}
This is my poem.xml: (Dependencies Tag)
<dependencies>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>javax.persistence</artifactId>
<version>2.0.0</version>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.2.8.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.27</version>
</dependency>
<dependency>
<groupId>org.eclipse.persistence</groupId>
<artifactId>eclipselink</artifactId>
<version>2.5.2</version>
</dependency>
</dependencies>
And the last thing is my main function:
public class EmployeeTest {
private static EntityManager em;
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("EmployeeService");
em = emf.createEntityManager();
createEmployee(1, "Saint", "Peter", "Engineering");
createEmployee(2, "Jack", " Dorsey", "Imaginea");
createEmployee(3, "Sam", "Fox", "Imaginea");
}
private static void createEmployee(int id, String firstName, String lastName, String dept) {
em.getTransaction().begin();
Employee emp = new Employee();
emp.setId(id);
emp.setFistName(firstName);
emp.setLastName(lastName);
emp.setDept(dept);
em.persist(emp);
em.getTransaction().commit();
}
}
But when I run this code I face with this error:
I have searched this error bud couldn't understand what should I do. I've also visited this link:
Can not find the declaration of element 'persistence'
javax.persistence.PersistenceException - JPA+Hibernate
and alot more similar questions ....
Can anyone please help me to solve this error?
Thanks in advance for your attention.
You can check your XML against the XSD here : http://www.freeformatter.com/xml-validator-xsd.html
Very useful.
Replace the beginning of your xml with:
<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">
I don't know why, but yours is not validated.
Also, you miss the end of the xml, but i guess it's just a copy/paste error.
This issue is a continuation of this problem: Foreign key as a part of composite primary key and ManyToOne relationship in OpenJPA
OpenJPA is tring to cast my entity class (TableB) to type of its key (long). Why?
Persisting of TableB object without any elements in field rows works fine. The problem begins when 'm adding elements to rows.
TableA.class:
package org.model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.IdClass;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
#Entity
#IdClass(TableA_PK.class)
public class TableA implements Serializable {
#Id
private int fId;
#Id
private String item;
#Id
private String release;
#Id
#ManyToOne
#JoinColumn(name = "b_id")
private TableB tableB;
#Column
private String field1;
#Column
private String field2;
public TableA() {
}
public int getfId() {
return fId;
}
public void setfId(int fId) {
this.fId = fId;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getRelease() {
return release;
}
public void setRelease(String release) {
this.release = release;
}
public TableB getTableB() {
return tableB;
}
public void setTableB(TableB tableB) {
this.tableB = tableB;
}
public String getField1() {
return field1;
}
public void setField1(String field1) {
this.field1 = field1;
}
public String getField2() {
return field2;
}
public void setField2(String field2) {
this.field2 = field2;
}
}
TableA_PK.class:
package org.model;
import java.io.Serializable;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
public class TableA_PK implements Serializable {
private int fId;
private String item;
private String release;
private long tableB;
public TableA_PK() {
}
public int getfId() {
return fId;
}
public void setfId(int fId) {
this.fId = fId;
}
public String getItem() {
return item;
}
public void setItem(String item) {
this.item = item;
}
public String getRelease() {
return release;
}
public void setRelease(String release) {
this.release = release;
}
public long getTableB() {
return tableB;
}
public void setTableB(long tableB) {
this.tableB = tableB;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
TableA_PK rhs = (TableA_PK) obj;
return new EqualsBuilder().append(fId, rhs.fId).append(item, rhs.item)
.append(release, rhs.release).append(tableB, rhs.tableB)
.isEquals();
}
#Override
public int hashCode() {
return new HashCodeBuilder().append(fId).append(item).append(release)
.append(tableB).toHashCode();
}
}
TableB.class:
package org.model;
import java.io.Serializable;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.OneToMany;
import org.apache.commons.lang3.builder.EqualsBuilder;
import org.apache.commons.lang3.builder.HashCodeBuilder;
#Entity
public class TableB implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column
private String name;
#Column
private Date date;
#OneToMany(mappedBy = "tableB", cascade = CascadeType.PERSIST)
private List<TableA> rows;
public TableB() {
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public List<TableA> getRows() {
return rows;
}
public void setRows(List<TableA> rows) {
this.rows = rows;
}
#Override
public boolean equals(Object obj) {
if (obj == null) {
return false;
}
if (obj == this) {
return true;
}
if (obj.getClass() != getClass()) {
return false;
}
TableB rhs = (TableB) obj;
return new EqualsBuilder().append(id, rhs.id).append(name, rhs.name)
.append(date, rhs.date).isEquals();
}
#Override
public int hashCode() {
return new HashCodeBuilder().append(id).append(name).append(date)
.toHashCode();
}
}
JpaTest.class:
package org.model;
import java.util.ArrayList;
import java.util.Date;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
import org.junit.Test;
public class JpaTest {
#Test
public void test() {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("rd-jpa");
EntityManager em = entityManagerFactory.createEntityManager();
EntityTransaction userTransaction = em.getTransaction();
userTransaction.begin();//BEGIN TRANSACTION 1.
TableB tableb = new TableB();
tableb.setDate(new Date());
tableb.setName("tableb2");
em.persist(tableb); // fills tableb id
userTransaction.commit(); //COMMIT 1
userTransaction = em.getTransaction();
userTransaction.begin();//BEGIN TRANSACTION 2.
TableA tableA = new TableA();
tableA.setfId(665);
tableA.setField1("field1");
tableA.setField2("field2");
tableA.setItem("item2");
tableA.setRelease("1");
tableA.setTableB(tableb);
ArrayList<TableA> rows = new ArrayList<TableA>();
rows.add(tableA);
tableb.setRows(rows);
em.persist(tableb);
userTransaction.commit();
em.clear();
em.close();
}
}
Stack Trace after running JpaTest:
<openjpa-2.3.0-r422266:1540826 nonfatal general error> org.apache.openjpa.persistence.PersistenceException: org.model.TableB cannot be cast to java.lang.Number
at org.apache.openjpa.kernel.BrokerImpl.persistAll(BrokerImpl.java:2526)
at org.apache.openjpa.kernel.SingleFieldManager.persist(SingleFieldManager.java:279)
at org.apache.openjpa.kernel.StateManagerImpl.cascadePersist(StateManagerImpl.java:3081)
at org.apache.openjpa.kernel.BrokerImpl.persistInternal(BrokerImpl.java:2648)
at org.apache.openjpa.kernel.BrokerImpl.persist(BrokerImpl.java:2604)
at org.apache.openjpa.kernel.BrokerImpl.persist(BrokerImpl.java:2587)
at org.apache.openjpa.kernel.BrokerImpl.persist(BrokerImpl.java:2491)
at org.apache.openjpa.kernel.DelegatingBroker.persist(DelegatingBroker.java:1077)
at org.apache.openjpa.persistence.EntityManagerImpl.persist(EntityManagerImpl.java:716)
at org.model.JpaTest.test(JpaTest.java:37)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:47)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:271)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:70)
at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)
Caused by: java.lang.ClassCastException: org.model.TableB cannot be cast to java.lang.Number
at org.apache.openjpa.util.ApplicationIds$PrimaryKeyFieldManager.fetchLongField(ApplicationIds.java:669)
at org.apache.openjpa.enhance.org$model$TableA$pcsubclass.pcCopyKeyFieldsToObjectId(Unknown Source)
at org.apache.openjpa.enhance.PCRegistry.copyKeyFieldsToObjectId(PCRegistry.java:169)
at org.apache.openjpa.util.ApplicationIds.fromPKValues(ApplicationIds.java:224)
at org.apache.openjpa.enhance.ReflectingPersistenceCapable.pcNewObjectIdInstance(ReflectingPersistenceCapable.java:277)
at org.apache.openjpa.util.ApplicationIds.create(ApplicationIds.java:427)
at org.apache.openjpa.kernel.BrokerImpl.persistInternal(BrokerImpl.java:2675)
at org.apache.openjpa.kernel.BrokerImpl.persistAll(BrokerImpl.java:2521)
... 32 more
persistence.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<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="rd-jpa" transaction-type="RESOURCE_LOCAL">
<provider>org.apache.openjpa.persistence.PersistenceProviderImpl</provider>
<class>org.model.TableA</class>
<class>org.model.TableB</class>
<properties>
<property name="openjpa.ConnectionURL"
value="jdbc:postgresql://localhost:5432/mydb" />
<property name="openjpa.ConnectionDriverName" value="org.postgresql.Driver" />
<property name="openjpa.ConnectionUserName" value="postgres" />
<property name="openjpa.ConnectionPassword" value="postgres" />
<property name="openjpa.DynamicEnhancementAgent" value="true" />
<property name="openjpa.RuntimeUnenhancedClasses" value="supported" />
<property name="openjpa.jdbc.SynchronizeMappings" value="buildSchema(ForeignKeys=true)" />
</properties>
</persistence-unit>
</persistence>
pom.xml:
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>jpa</groupId>
<artifactId>jpa</artifactId>
<version>0.0.1-SNAPSHOT</version>
<build>
<sourceDirectory>src</sourceDirectory>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source />
<target />
</configuration>
</plugin>
</plugins>
</build>
<dependencies>
<dependency>
<groupId>org.apache.openjpa</groupId>
<artifactId>openjpa-maven-plugin</artifactId>
<version>2.3.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.3.2</version>
</dependency>
<dependency>
<groupId>org.postgresql</groupId>
<artifactId>postgresql</artifactId>
<version>9.3-1102-jdbc41</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
</dependencies>
</project>
Try to get rid of the openjpa.RuntimeUnenhancedClasses property and enhance your Entities properly.
I am new to JPA 2.0 API and I am trying to have a start up with JPA to Mysql transaction but I am enable to do so. And I am not getting any errors.
package com.testjpa.demo;
import java.io.Serializable;
import javax.persistence.*;
/**
* The persistent class for the employee database table.
*
*/
#Entity
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
public Employee() {
}
public Employee(int id) {
this.id = id;
}
public int getId() {
return this.id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
}
Methods to perform CRUD operations
package com.testjpa.demo;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
public class EmployeeService {
/**
* #param args
*/
protected EntityManager em;
public EmployeeService(EntityManager em) {
this.em = em;
}
public Employee findEmployee(int id) {
return em.find(Employee.class, id);
}
public Employee createEmployee(int id, String name) {
Employee emp = new Employee(id);
emp.setName(name);
return emp;
}
public void removeEmployee(int id) {
Employee emp = findEmployee(id);
if (emp != null) {
em.remove(emp);
}
}
public List<Employee> findAllEmployees() {
TypedQuery<Employee> query = em.createQuery("select e from Employee e",
Employee.class);
return query.getResultList();
}
}
Test Class to persist the data into MysQL
package com.testjpa.demo;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class EmployeeTest {
/**
* #param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
EntityManagerFactory emf = Persistence
.createEntityManagerFactory("JPADemo");
EntityManager em = emf.createEntityManager();
EmployeeService service = new EmployeeService(em);
// create and persist an employee
em.getTransaction().begin();
Employee emp = service.createEmployee(2, "John Doe");
em.getTransaction().commit();
System.out.println("Persisted " + emp);
emp = service.findEmployee(2);
System.out.println("Found " + emp);
}
}
I will really appreciate suggestions as i am totally new to this API
Also Persistence.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="JPADemo" transaction-type="RESOURCE_LOCAL">
<class>com.testjpa.demo.Employee</class>
<properties>
<property name="eclipselink.jdbc.batch-writing" value="JDBC"/>
<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="123456"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
</properties>
</persistence-unit>
</persistence>
In your createEmployee method you are instantiating a new Employee POJO but you never persist it with the EntityManager, so Hibernate is not aware of it. Try adding:
em.persist(emp);