Configuring Kundera with HBase - java

I currently have an HBase/Hadoop cluster running without issues, and I am fairly familiar with these products. I recently heard about Kundera, and it looks to be a very powerful tool that I would like to use.
However, I cannot seem to find any documentation/tutorials/examples for setting up Kundera with HBase. I have tried some of the materials I happened to come across, but they have failed so egregiously that I am under the impression that it wasn't relevant.
Essentially I don't know where to begin. I'm not worried about somebody explaining to me any kind of advanced level stuff, but I just cannot get this thing configured.
If anybody can point me in the right direction I would greatly appreciate it.
TLDR: I have an HBase cluster running and want to use Kundera with it and I have no clue where to begin whatsoever. Thanks.

You can start here https://github.com/impetus-opensource/Kundera and https://github.com/impetus-opensource/Kundera/wiki
Kundera is JPA compliant , it's pretty easy and straight forward to setup. wiki has enough documentation / examples to get you started. Kundera dev team is very active here as well.
Just create your persistence.xml as shown
https://github.com/impetus-opensource/Kundera/wiki/Common-Configuration
and hbase specific options
https://github.com/impetus-opensource/Kundera/wiki/HBase-Specific-Features

Kundera + Hbase Configuration in Eclipse
Start your Hbase configuration on linux or others
create Dynamic web project
Add the following jar into Libraries of the project
1)asm-4.0.jar
2)cglib-2.1.jar
3)commons-lang-2.5.jar
4)commons-logging-1.1.1.jar
5)hadoop-core-1.0.0.jar
6)hbase-0.94.4.jar
7)jts-1.11.jar
8)kundera-core-2.5.1.jar
9)kundera-hbase-2.5.jar
10)log4j-1.2.16.jar
11)lucene-core-3.5.0.jar
12)xstream-1.3.1.jar
13)zookeeper-3.3.2.jar
Add the persistence.xml file as following
<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="hbase_pu">
<provider>com.impetus.kundera.KunderaPersistence</provider>
<class>com.fvrl.MyObject</class>
<properties>
<property name="kundera.nodes" value="your host ip"/>
<property name="kundera.port" value="port"/>
<property name="kundera.keyspace" value="KunderaExamples"/>
<property name="kundera.dialect" value="hbase"/>
<property name="kundera.client.lookup.class" value="com.impetus.client.hbase.HBaseClientFactory" />
<property name="kundera.client.property" value="yourxmlfilepath" />
<property name="kundera.ddl.auto.prepare" value="update" />
</properties>
</persistence-unit>
</persistence>
Above xml file path must be place in proper place.
Make your Entity Class as below
#Entity
#Table(name = "MyObject", schema = "KunderaExamples#hbase_pu")
#NamedQueries({
#NamedQuery(name="findAll", query="select c from MyObject c")
})
public class MyObject
{
#Id
private String id;
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 getSecondname() {
return secondname;
}
public void setSecondname(String secondname) {
this.secondname = secondname;
}
private String firstname;
private String secondname;
}
Run Your Project through main method
public static void main(String[] args) {
MyObject myObject = new MyObject();
myObject.setId("0006");
myObject.setFirstname("Nirav");
myObject.setSecondname("shah");
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hbase_pu");
EntityManager em = emf.createEntityManager();
//Save
HBaseJPAImpl hBaseJPAImpl =new HBaseJPAImpl(em);
hBaseJPAImpl.save(myObject);
//retrive
List<MyObject> list= hBaseJPAImpl.findAllDetails();
for(MyObject myObject1 : list){
System.out.println("Row Id : "+myObject1.getId());
System.out.println("First Name : "+myObject1.getFirstname());
System.out.println("Last Name : "+myObject1.getSecondname());
}
}
HBaseJPAImpl Class is following
public class HBaseJPAImpl implements IHBaseJPA
{
public HBaseJPAImpl(EntityManager em) {
// TODO Auto-generated constructor stub
this.em = em;
}
#Inject protected EntityManager em;
#Transactional
public void save(MyObject myObject)
{
// em.persist(myObject));
EntityTransaction entityTransaction = this.em.getTransaction();
entityTransaction.begin();
em.persist(myObject));
entityTransaction.commit();
}
#SuppressWarnings("unchecked")
#Override
#Transactional
public List<MyObject> findAllDetails()
{
Query query = em.createNamedQuery("findAll");
List<MyObject> results = (List<MyObject>) query.getResultList();
return results;
}
}
interface IHBaseJPA is below
public interface IHBaseJPA
{
void save(MyObject contact);`enter code here`
List<MyObject> findAllDetails();
}
if find any queries on the above then contact me

Related

REST Service with NetBeans JPA

I have some difficulties with my first experiments with Web Applications.
I’m using
jdk15.0.1
NetBeans 12.0
MySQL 5.7.19
Payara Server 5.201
Windows 10 build 19041.685
When I create a project Web Application ( Java with Maven > Web Application ), I write my Entity Class, but when I try to generate Persistence unit it does not allow me to use the JTA.
Book.java
#XmlRootElement
#Entity
#NamedQueries({
#NamedQuery(name = "Book.findAll", query = "SELECT d FROM Book d")
})
public class Book implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String title;
private String author;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
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 Book)) {
return false;
}
Book other = (Book) 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 "com.mycompany.test201.Book[ id=" + id + " ]";
}
}
I add New>RESTful Web Services from Patterns...
BookResource.java
#RequestScoped
#Path("book")
public class BookResource {
#PersistenceContext(unitName = "test201pu")
private EntityManager em;
// #Context
// private UriInfo context;
/**
* Creates a new instance of BookResource
*/
public BookResource() {
}
#POST
#Transactional
#Consumes(MediaType.APPLICATION_FORM_URLENCODED)
public void addBook(#FormParam("aut")String autr, #FormParam("titl")String til) {
Book b=new Book();
b.setAuthor(autr);
b.setTitle(til);
em.persist(b);
}
/**
* Retrieves representation of an instance of com.mycompany.test201.BookResource
* #return an instance of java.lang.String
*/
#GET
#Produces(MediaType.APPLICATION_XML)
public List<Book> getXml() {
Query q=em.createNamedQuery("Book.findAll", Book.class);
return q.getResultList();
}
/**
* PUT method for updating or creating an instance of BookResource
* #param content representation for the resource
*/
#PUT
#Consumes(MediaType.APPLICATION_XML)
public void putXml(String content) {
}
}
I am forced to correct by hand the XML from
transaction-type="RESOURCE_LOCAL" to transaction-type="JTA" .
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="test201pu" transaction-type="JTA">
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://localhost:3306/test201?zeroDateTimeBehavior=CONVERT_TO_NULL"/>
<property name="javax.persistence.jdbc.user" value="piero"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="javax.persistence.jdbc.password" value="my_password"/>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
</properties>
</persistence-unit>
</persistence>
Also the checkbox "Include All Entity Classes in ... Module" is always disabled (and the same the other checkbox “Use Java Transaction APIs”)
Finally when I try some transaction, obviously using like JDBC a connection to database MySQL, there’s no tables in database, so I don’t know where the data was stored.

Only one entity generated in database [jee]

i am new in jee
i create two entities with different namedquery.
when i run my application on wildfly 10, only one entity generated in the data base despite when i check my console i find my two entities in jndi.
this is my two classes:
models:
#Entity
#NamedQuery(name="ClientBanque.findAll", query="SELECT client FROM ClientBanque client")
public class ClientBanque implements Serializable {
#Id
int cin;
String prenom;
String nom;
String adress;
//getters and setters
// constructor using fields
}
#NamedQuery(name="CompteBancair.findAll", query="SELECT c FROM CompteBancair c")
public class CompteBancair implements Serializable {
#Id
long rib;
float solde;
// getters, setters, constructor
}
dao:
#Stateless
public class ClientBanqueDAO {
#PersistenceContext
private EntityManager em;
public void persist(ClientBanque client) {
em.persist(client);
}
public List<ClientBanque> getAllCustomers() {
Query q = em.createNamedQuery("ClientBanque.findAll", ClientBanque.class);
List<ClientBanque> resultList = q.getResultList();
return resultList;
}
}
#Stateless
public class CompteBancaireDAO {
#PersistenceContext
private EntityManager em;
public void persistAcount(CompteBancair compte) {
em.persist(compte);
}
public List<CompteBancair> getAllAcount() {
Query q = em.createNamedQuery("CompteBancair.findAll", CompteBancair.class);
List<CompteBancair> resultList = q.getResultList();
return resultList;
}
}
the persistant.xml contains :
<?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_1_0.xsd"
version="1.0">
<persistence-unit name="bank">
<jta-data-source>java:jboss/mysql/bank</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="update"/>
</properties>
</persistence-unit>
</persistence>
what i can do to fix this problem ?

JavaEE JPA returning versions of old data

We are building a REST application using JPA which we have trouble getting to work properly.
The issue is that when doing updates or adding items jpa selects starts returning multiple versions of the changed. For example if Item contains A and is changed to B then changed to C, select queries will return A first run, B second, C third, A fourth etc. Sometimes it wont show directly but holding down f5 on the browser for GET items resource then changing the data always generates this problem.
Ive created a clean sample project which demonstrates this. We use Glassfish 4.1.0 (since there were som other issues with 4.1.1).
Created mysql database 'testdb' Created a table 'item' containing two VARCHAR(45) fields, 'firstName' and 'lastName'.
Created a new maven project based on 'javaee7-essentials-acrhetype'. (https://github.com/AdamBien/javaee7-essentials-archetype)
Added datasource in intellij and generated an Entity bean for this Item entity. Adjusted persistence.xml to include username and password.
Created a simple DTO / Pojo class to receive the PUT data.
Created an ItemResource class.
All in all 4 classes and persistence.xml + pom.xml
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>test.server</groupId>
<artifactId>testdb</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<dependencies>
<dependency>
<groupId>javax</groupId>
<artifactId>javaee-api</artifactId>
<version>7.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.hibernate</groupId>
<artifactId>hibernate-entitymanager</artifactId>
<version>4.3.11.Final</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
</dependency>
</dependencies>
<build>
<finalName>testdb</finalName>
</build>
<properties>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<failOnMissingWebXml>false</failOnMissingWebXml>
</properties>
</project>
Persistence.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://xmlns.jcp.org/xml/ns/persistence" version="2.1">
<persistence-unit name="LocalUnit">
<provider>org.hibernate.ejb.HibernatePersistence</provider>
<class>test.server.entities.ItemEntity</class>
<properties>
<property name="hibernate.connection.url" value="jdbc:mysql://localhost:3306/testdb"/>
<property name="hibernate.connection.driver_class" value="com.mysql.jdbc.Driver"/>
<property name="hibernate.connection.username" value="root" />
<property name="hibernate.connection.password" value="abc123" />
<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>
</persistence-unit>
</persistence>
ItemDTO
public class ItemDTO {
private String firstName;
private String lastName;
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;
}
}
ItemEntity bean (added the namedqueries manually)
#Entity
#NamedQueries({
#NamedQuery(name = "Item.All", query = "SELECT item from ItemEntity item"),
#NamedQuery(name = "Item.Get", query = "SELECT item from ItemEntity item WHERE item.id = :id")
})
#Table(name = "item", schema = "testdb", catalog = "")
public class ItemEntity {
private Integer id;
private String firstName;
private String lastName;
#Id
#Column(name = "id")
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#Basic
#Column(name = "firstName")
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Basic
#Column(name = "lastName")
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
ItemEntity that = (ItemEntity) o;
if (id != null ? !id.equals(that.id) : that.id != null) return false;
if (firstName != null ? !firstName.equals(that.firstName) : that.firstName != null) return false;
if (lastName != null ? !lastName.equals(that.lastName) : that.lastName != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
return result;
}
}
ItemResources class
#Path("items")
public class ItemResources {
private static EntityManagerFactory emf = null;
public ItemResources() {
if(emf == null) {
emf = Persistence.createEntityManagerFactory("LocalUnit");
}
}
public EntityManager getEntityManager() {
return emf.createEntityManager();
}
#GET
#Produces(MediaType.APPLICATION_JSON)
public Response getAllAccounts() {
EntityManager manager = getEntityManager();
Collection<ItemEntity> accounts = null;
try {
accounts = manager.createNamedQuery("Item.All").getResultList();
} catch(Exception e) {
throw new RuntimeException(e);
} finally {
manager.close();
}
return Response.ok().entity(new GenericEntity<Collection<ItemEntity>>(accounts) {}).build();
}
#PUT
#Path("{id}")
#Consumes(MediaType.APPLICATION_JSON)
public Response updateAccount(#PathParam("id") int id, ItemDTO itemDTO) {
EntityManager manager = getEntityManager();
try {
manager.getTransaction().begin();
TypedQuery<ItemEntity> query = manager.createNamedQuery("Item.Get", ItemEntity.class);
query.setParameter("id", id);
ItemEntity account = query.getSingleResult();
account.setFirstName(itemDTO.getFirstName());
account.setLastName(itemDTO.getLastName());
manager.getTransaction().commit();
} catch(Exception e) {
manager.getTransaction().rollback();
throw new RuntimeException(e);
} finally {
manager.close();
}
return Response.ok().entity("OK").build();
}
}
And the main application class (no web.xml, empty beans.xml)
#ApplicationPath("resources")
public class JAXRSConfiguration extends Application {
}
Summarized this dont work. The problem described in the beginning occurs which makes it impossible to use for anything real. Are we missing something here, shouldnt this simple example work?
We have a real application containing this issue and we have some time trying to find out why it behaves like this. We tried different ways of clearing the cache, evicting the factory, tried changing connection isolation, disabling 2ndlevel and query cache in persistence.xml but still got the same issuein the end or traded for more severe db issues. Tried on two different servers running same glassfish versions. So we are at the point if we have to roll back to pure jdbc/sql to get this working.
HOWEVER strangely i have not yet been able to reproduce the issue when deploying in intellij yet. But when deploying the .war file on any server weve tried so far the issue appears. But when officially depolyed it seems the only way to make it work would be to create a new fctory instance for each request then close it when done. Which seems extremely wasteful.
If anyone could help us solve this and thus avoid alot of refactoring we would be forever greatful :) Are we missing something vital that is needed for this to work?

org.hibernate.hql.internal.ast.QuerySyntaxException: table is not mapped

I have example web application Hibernate 4.3.5 + Derby database 10.10.1.1+ Glassfish4.0 with IDE NetBeans 8.0Beta.
I have the next exception:
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: CUSTOMERV is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:189)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:109)
at org.hibernate.hql.internal.ast.tree.FromClause.addFromElement(FromClause.java:95)
at org.hibernate.hql.internal.ast.HqlSqlWalker.createFromElement(HqlSqlWalker.java:331)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElement(HqlSqlBaseWalker.java:3633)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromElementList(HqlSqlBaseWalker.java:3522)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.fromClause(HqlSqlBaseWalker.java:706)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.query(HqlSqlBaseWalker.java:562)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.selectStatement(HqlSqlBaseWalker.java:299)
at org.hibernate.hql.internal.antlr.HqlSqlBaseWalker.statement(HqlSqlBaseWalker.java:247)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.analyze(QueryTranslatorImpl.java:278)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:206)
... 72 more
Form from index.xhtml
<h:panelGrid id="panel1" columns="2" border="1"
cellpadding="5" cellspacing="1">
<f:facet name="header">
<h:outputText value="Add Customer Information"/>
</f:facet>
<h:outputLabel value="First Name:"/>
<h:inputText value="#{customer.firstName}" id="fn"/>
<h:outputLabel value="Last Name:"/>
<h:inputText value="#{customer.lastName}" id="ln"/>
<h:outputLabel value="Email:"/>
<h:inputText value="#{customer.email}" id="eml"/>
<h:outputLabel value="Date of Birth:"/>
<h:inputText value="#{customer.sd}" id="s"/>
<f:facet name="footer">
<h:outputLabel value="#{customer.msg}" id="msg" styleClass="msg"/>
<h:commandButton value="Save" action="#{customer.saveCustomer}">
</h:commandButton>
</f:facet>
</h:panelGrid>
Customer.java
package com.javaknowledge.entity;
import com.javaknowledge.dao.CustomerDao;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.persistence.*;
#ManagedBean
#SessionScoped
public class Customer implements java.io.Serializable {
private Integer custId;
private String firstName;
private String lastName;
private String email;
private Date dob;
private String sd, msg, selectedname;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
public Customer() {
}
public Customer(String firstName, String lastName, String email, Date dob) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
this.dob = dob;
}
public String getSd() {
return sd;
}
public void setSd(String sd) {
this.sd = sd;
}
public Integer getCustId() {
return this.custId;
}
public void setCustId(Integer custId) {
this.custId = custId;
}
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return this.lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
#Column(name = "EMAIL")
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name = "DOB")
public Date getDob() {
return this.dob;
}
public void setDob(Date dob) {
this.dob = dob;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public String getSelectedname() {
return selectedname;
}
public void setSelectedname(String selectedname) {
this.selectedname = selectedname;
}
public void saveCustomer() {
try {
Date d = sdf.parse(sd);
System.out.println(d);
this.dob = d;
} catch (ParseException e) {
e.printStackTrace();
}
CustomerDao dao = new CustomerDao();
dao.addCustomer(this);
this.msg = "Member Info Saved Successfull!";
clearAll();
}
public void updateCustomer() {
try {
Date d = sdf.parse(sd);
System.out.println(d);
this.dob = d;
} catch (ParseException e) {
e.printStackTrace();
}
CustomerDao dao = new CustomerDao();
dao.updateCustomer(this);
this.msg = "Member Info Update Successfull!";
clearAll();
}
public void deleteCustomer() {
CustomerDao dao = new CustomerDao();
dao.deleteCustomer(custId);
this.msg = "Member Info Delete Successfull!";
clearAll();
}
public List<Customer> getAllCustomers() {
List<Customer> users = new ArrayList<Customer>();
CustomerDao dao = new CustomerDao();
users = dao.getAllCustomers();
return users;
}
public void fullInfo() {
CustomerDao dao = new CustomerDao();
List<Customer> lc = dao.getCustomerById(selectedname);
System.out.println(lc.get(0).firstName);
this.custId = lc.get(0).custId;
this.firstName = lc.get(0).firstName;
this.lastName = lc.get(0).lastName;
this.email = lc.get(0).email;
this.dob = lc.get(0).dob;
this.sd = sdf.format(dob);
}
private void clearAll() {
this.firstName = "";
this.lastName = "";
this.sd = "";
this.email = "";
this.custId=0;
}
}
hibernate.cfg.xml
<?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.dialect">org.hibernate.dialect.DerbyDialect</property>
<property name="hibernate.connection.driver_class">org.apache.derby.jdbc.ClientDriver</property>
<property name="hibernate.connection.url">jdbc:derby://localhost:1527/derbyDB</property>
<property name="hibernate.connection.username">user1</property>
<property name="hibernate.connection.password">user1</property>
<property name="hibernate.hbm2ddl.auto">create</property>
<property name="c3p0.min_size">1</property>
<property name="c3p0.max_size">5</property>
<property name="c3p0.timeout">300</property>
<property name="c3p0.max_statements">50</property>
<property name="c3p0.idle_test_period">300</property>
<mapping class="com.javaknowledge.entity.Customer" resource="com/javaknowledge/entity/Customer.hbm.xml"/>
</session-factory>
</hibernate-configuration>
Customer.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.javaknowledge.entity.Customer" table="CUSTOMERV" schema="APP">
<id name="custId" type="java.lang.Integer">
<column name="cust_id" />
<generator class="increment" />
</id>
<property name="firstName" type="string">
<column name="first_name" length="45" not-null="true" />
</property>
<property name="lastName" type="string">
<column name="last_name" length="45" not-null="true" />
</property>
<property name="email" type="string">
<column name="email" length="45" not-null="true" />
</property>
<property name="dob" type="date">
<column name="dob" length="10" not-null="true" />
</property>
</class>
</hibernate-mapping>
Finally I found a mistake! Hope this is useful to someone. When doing a request to the database(in my case it Apache Derby), name of base need write the first letter upper case other in lower case.
This is wrong query:
session.createQuery("select first_name from CUSTOMERV").
This is valid query
session.createQuery("select first_name from Customerv").
And class entity must be same name as database, but I'm not sure.
in HQL query, Don't write the Table name, write your Entity class name in your query like
String s = "from Entity_class name";
query qry = session.createUqery(s);
In my case I just forgot to add nativeQuery = true
#Query( value = "some sql query ...", nativeQuery = true)
For Spring Boot with Spring Data JPA
If you are using the JPA annotations to create the entities and then make sure that the table name is mapped along with #Table annotation instead of #Entity.
Incorrectly mapped :
#Entity(name="DB_TABLE_NAME")
public class DbTableName implements Serializable {
....
....
}
Correctly mapped entity :
#Entity
#Table(name="DB_TABLE_NAME")
public class DbTableName implements Serializable {
....
....
}
hibernate.cfg.xml file should have the mapping for the tables like below. Check if it is missing in your file.
......
<hibernate-configuration>
......
......
<session-factory>
......
<mapping class="com.test.bean.dbBean.testTableHibernate"/>
......
</session-factory>
</hibernate-configuration>
.....
None of the other solution worked for me.
Even if I don't think its the best practice, I Had to add it into the code like this
configuration.addAnnotatedClass(com.myOrg.entities.Person.class);
here
public static SessionFactory getSessionFactory() {
Configuration configuration = new Configuration().configure();
configuration.addAnnotatedClass(com.myOrg.entities.Person.class);
StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
.applySettings(configuration.getProperties());
SessionFactory sessionFactory = configuration.buildSessionFactory(builder.build());
return sessionFactory;
}
May be this will make it more clear, and of course makes sense too.
#Entity
#Table(name = "users")
/**
*
* #author Ram Srinvasan
* Use class name in NamedQuery
* Use table name in NamedNativeQuery
*/
#NamedQueries({ #NamedQuery(name = "findUserByName", query = "from User u where u.name= :name") })
#NamedNativeQueries({ #NamedNativeQuery(name = "findUserByNameNativeSQL", query = "select * from users u where u.name= :name", resultClass = User.class) })
public class User implements Principal {
...
}
There is one more chance to get this exception even we used class name i.e., if we have two classes with same name in different packages. we'll get this problem.
I think hibernate may get ambiguity and throws this exception, so the solution is to use complete qualified name(like com.test.Customerv)
I added this answer that will help in scenario as I mentioned. I got the same scenario got stuck for some time.
I too have faced similar issue when i started to work on Hibernate. All in all i can say is in the createQuery one needs to pass the name of the entity class not the table name to which the entity is mapped to.
In Hibernate,
session.createQuery("select first_name from Customerv").
The Customerv is your Entity Name, not your Table Name
It means your table is not mapped to the JPA.
Either Name of the table is wrong (Maybe case sensitive), or you need to put an entry in the XML file.
Happy Coding :)
Other persons that are using mapping classes for Hibernate, make sure that have addressed correctly to model package in sessionFactory bean declaration in the following part:
<property name="packagesToScan" value="com.mblog.model"></property>
In my case: spring boot 2 ,multiple datasource(default and custom). entityManager.createQuery go wrong: 'entity is not mapped'
while debug, i find out that the entityManager's unitName is wrong(should be custom,but the fact is default)
the right way:
#PersistenceContext(unitName = "customer1") // !important,
private EntityManager em;
the customer1 is from the second datasource config class:
#Bean(name = "customer1EntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
#Qualifier("customer1DataSource") DataSource dataSource) {
return builder.dataSource(dataSource).packages("com.xxx.customer1Datasource.model")
.persistenceUnit("customer1")
// PersistenceUnit injects an EntityManagerFactory, and PersistenceContext
// injects an EntityManager.
// It's generally better to use PersistenceContext unless you really need to
// manage the EntityManager lifecycle manually.
// 【4】
.properties(jpaProperties.getHibernateProperties(new HibernateSettings())).build();
}
Then,the entityManager is right.
But, em.persist(entity) doesn't work,and the transaction doesn't work.
Another important point is:
#Transactional("customer1TransactionManager") // !important
public Trade findNewestByJdpModified() {
//test persist,working right!
Trade t = new Trade();
em.persist(t);
log.info("t.id" + t.getSysTradeId());
//test transactional, working right!
int a = 3/0;
}
customer1TransactionManager is from the second datasource config class:
#Bean(name = "customer1TransactionManager")
public PlatformTransactionManager transactionManager(
#Qualifier("customer1EntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
The whole second datasource config class is :
package com.lichendt.shops.sync;
import javax.persistence.EntityManagerFactory;
import javax.sql.DataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceProperties;
import org.springframework.boot.autoconfigure.orm.jpa.HibernateSettings;
import org.springframework.boot.autoconfigure.orm.jpa.JpaProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.orm.jpa.EntityManagerFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.orm.jpa.JpaTransactionManager;
import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.annotation.EnableTransactionManagement;
#Configuration
#EnableTransactionManagement
#EnableJpaRepositories(entityManagerFactoryRef = "customer1EntityManagerFactory", transactionManagerRef = "customer1TransactionManager",
// 【1】这里写的是DAO层的路径 ,如果你的DAO放在 com.xx.DAO下面,则这里写成 com.xx.DAO
basePackages = { "com.lichendt.customer1Datasource.dao" })
public class Custom1DBConfig {
#Autowired
private JpaProperties jpaProperties;
#Bean(name = "customer1DatasourceProperties")
#Qualifier("customer1DatasourceProperties")
#ConfigurationProperties(prefix = "customer1.datasource")
public DataSourceProperties customer1DataSourceProperties() {
return new DataSourceProperties();
}
#Bean(name = "customer1DataSource")
#Qualifier("customer1DatasourceProperties")
#ConfigurationProperties(prefix = "customer1.datasource") //
// 【2】datasource配置的前缀,对应上面 【mysql的yaml配置】
public DataSource dataSource() {
// return DataSourceBuilder.create().build();
return customer1DataSourceProperties().initializeDataSourceBuilder().build();
}
#Bean(name = "customer1EntityManagerFactory")
public LocalContainerEntityManagerFactoryBean entityManagerFactory(EntityManagerFactoryBuilder builder,
#Qualifier("customer1DataSource") DataSource dataSource) {
return builder.dataSource(dataSource).packages("com.lichendt.customer1Datasource.model") // 【3】这里是实体类的包路径
.persistenceUnit("customer1")
// PersistenceUnit injects an EntityManagerFactory, and PersistenceContext
// injects an EntityManager.
// It's generally better to use PersistenceContext unless you really need to
// manage the EntityManager lifecycle manually.
// 【4】
.properties(jpaProperties.getHibernateProperties(new HibernateSettings())).build();
}
#Bean(name = "customer1TransactionManager")
public PlatformTransactionManager transactionManager(
#Qualifier("customer1EntityManagerFactory") EntityManagerFactory entityManagerFactory) {
return new JpaTransactionManager(entityManagerFactory);
}
}
If you by any chance using java for configuration, you may need to check the below bean declaration if you have package level changes. Eg: com.abc.spring package changed to com.bbc.spring
#Bean
public SessionFactory sessionFactory() {
LocalSessionFactoryBuilder builder = new LocalSessionFactoryBuilder(dataSource());
//builder.scanPackages("com.abc.spring"); //Comment this line as this package no longer valid.
builder.scanPackages("com.bbc.spring");
builder.addProperties(getHibernationProperties());
return builder.buildSessionFactory();
}
Should use Entity class name for em.createQuery method
or
Should use em.createNativeQuery method for native query without entity class
With Entity class:
em.createQuery("select first_name from CUSTOMERV")
Without Entity class or Native query:
em.createNativeQuery("select c.first_name from CUSTOMERV c")
Another solution that worked:
The data access object that actually throwed this exception is
public List<Foo> findAll() {
return sessionFactory.getCurrentSession().createQuery("from foo").list();
}
The mistake I did in the above snippet is that I have used the table name foo inside createQuery. Instead, I got to use Foo, the actual class name.
public List<Foo> findAll() {
return sessionFactory.getCurrentSession().createQuery("from Foo").list();
Thanks to this blog: https://www.arundhaj.com/blog/querysyntaxexception-not-mapped.html
Other persons that are using mapping classes for Hibernate, make sure that have addressed correctly to model package in sessionFactory bean declaration in the following part:
public List<Book> list() {
List<Book> list=SessionFactory.getCurrentSession().createQuery("from book").list();
return list;
}
The mistake I did in the above snippet is that I have used the table name foo inside createQuery. Instead, I got to use Foo, the actual class name.
public List<Book> list() {
List<Book> list=SessionFactory.getCurrentSession().createQuery("from Book").list();
return list;
}
add parameter nativeQuery = true
ex:
#Query(value="Update user set user_name =:user_name,password =:password where user_id =:user_id",nativeQuery = true)
In Apache Derby DB, refrain from using table names as "user" or so because they are reserved keywords on Apache Derby but will work fine on MySql.
In the Query, you must specify the name of the Entity class that you want to fetch the data from in the FROM clause of the Query.
List<User> users=session.createQuery("from User").list();
Here, User is the name of my Java Entity class(Consider the casing of the name as in Java it matters.)
in my case was that i forgot the "nativeQuery = true"
Problem partially was solved. Besides creating jdbc/resource(DB Derby) had to create JDBC Connection Pool for db resource in Glassfish admin console, and check it on pinging. Now all CRUD operation work just fine. I check, object Customer in database adding properly, update and delete too. But in Glassfish output log have same exception:
SEVERE: org.hibernate.hql.internal.ast.QuerySyntaxException: CUSTOMERV is not mapped [select concat(first_name, ' ', last_name) as name from CUSTOMERV]
at org.hibernate.hql.internal.ast.QuerySyntaxException.generateQueryException(QuerySyntaxException.java:96)
at org.hibernate.QueryException.wrapWithQueryString(QueryException.java:120)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.doCompile(QueryTranslatorImpl.java:234)
.......
Caused by: org.hibernate.hql.internal.ast.QuerySyntaxException: CUSTOMERV is not mapped
at org.hibernate.hql.internal.ast.util.SessionFactoryHelper.requireClassPersister(SessionFactoryHelper.java:189)
at org.hibernate.hql.internal.ast.tree.FromElementFactory.addFromElement(FromElementFactory.java:109)
The mistake in my case is that I used session.createQuery() instead of session.createSQLQuery()

JPA reads but doesn't persists

My Java Web App reads data from database but when I try to write something, JPA says ok, but the database does not change. I call "merge" method and the data are not being saved on database, only in memory. I can do a SELECT direct into database and see old data. But the Java Console does not throw any Exception as you can see above.
Java Console:
INFO: [EL Finest]: 2011-10-14 15:02:41.847--UnitOfWork(13027895)--Thread(Thread[http-thread-pool-8080-(6),10,Grizzly])--Merge clone with references user1
Change Password's method that is being called:
public static User changePassword(String username, String oldPassword, String newPassword){
User user = userFacade.find(username);
if(user != null && user.getPassword().equals(oldPassword)){
user.setPassword(newPassword);
userFacade.edit(user); // supposed to save the new password on database, but it's not
// at this point, the user has a new password on memory, but on database the password is still the old one
return user;
}
return null;
}
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="APP1PU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>com.company.User</class>
<properties>
<property name="javax.persistence.jdbc.url" value="jdbc:mysql://127.0.0.1:3306/app1"/>
<property name="javax.persistence.jdbc.password" value="12345"/>
<property name="javax.persistence.jdbc.driver" value="com.mysql.jdbc.Driver"/>
<property name="javax.persistence.jdbc.user" value="root"/>
<property name="eclipselink.logging.level" value="FINEST"/>
</properties>
</persistence-unit>
</persistence>
User.java:
#Entity
#Table(name = "user")
#Cache (
type=CacheType.NONE
)
public class User implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
private String username;
#Basic(optional = false)
private String password;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
UserFacade.java
public class UserFacade {
private EntityManagerFactory emf = Persistence.createEntityManagerFactory("APP1PU");
private EntityManager em;
protected EntityManager getEntityManager() {
if( em == null ){
em = emf.createEntityManager();
}
return em;
}
public void create(User entity) {
getEntityManager().persist(entity);
}
public void edit(User entity) {
getEntityManager().merge(entity);
}
public void remove(User entity) {
getEntityManager().remove(getEntityManager().merge(entity));
}
public User find(Object id) {
return getEntityManager().find(entityClass, id);
}
}
Anyone can figure why this behavior? Or has some suggestion of a test I could do?
Thanks in advance!
Try entityManager.flush() after a write operation. Or start a transaction (entityManager.getTransaction().begin()) before your write operation, and then close it at the end (entityManager.getTransaction().commit())

Categories