Only one entity generated in database [jee] - java

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 ?

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.

JPA not receiving updated data

I use a managedBean that goes into the db and defines the bean properties with db data. However when I update the db the data I receive in my bean is not updated.
The query in db is like this:
private static final String JPQL_FIND_BY_ID = "SELECT c FROM Category c WHERE c.idcategory=:id";
#Override
public Category findCatById(int id) {
Query query = em.createQuery(JPQL_FIND_BY_ID, Category.class);
query.setParameter("id", id);
Category cat = null;
try {
cat = (Category) query.getSingleResult();
} catch (Exception e) {
e.printStackTrace();
}
return cat;
}
The managed bean I use to get the category asks the ejb to make a lookup in the db:
#ManagedBean
public class CategoryBean {
private String idCategoryStr;
private Category category;
private int id;
#EJB
private CategoryLookUp categoryService;
#PostConstruct
public void init() {
this.category = categoryService.findCatById(id); //id defined in constructor
System.out.println(this.category.getName());//this will give the same
//name before and after db update
}
public CategoryBean() {
FacesContext fc = FacesContext.getCurrentInstance();
Map<String, String> paramsMap = fc.getExternalContext()
.getRequestParameterMap();
this.idCategoryStr = paramsMap.get("id");
try {
id = Integer.parseInt(idCategoryStr);
} catch (Exception e) {
}
}
//get&set
}
If I change the Title of the category in my db, it's gonna be unchanged in my bean even though #PostConstruct is called and the id is correct.
<?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="my-pu" transaction-type="JTA">
<jta-data-source>jdbc/forumcsDS</jta-data-source>
<class>main.java.entities.Category</class>
<class>main.java.entities.Country</class>
<class>main.java.entities.Forum</class>
<class>main.java.entities.Message</class>
<class>main.java.entities.Post</class>
<class>main.java.entities.Thethread</class>
<class>main.java.entities.Usercfg</class>
<class>main.java.entities.Usercredential</class>
<class>main.java.entities.Userinfo</class>
<class>main.java.entities.User</class>
<class>main.java.entities.Friend</class>
</persistence-unit>
</persistence>
Reason that you get old value is that your entity is stored in second level cache. And when you request it second time no database call is executed, but value from memory is returned.
You can disable cache by adding <property name="eclipselink.cache.shared.default" value="false"/> to property section of your persistence.xml

JPA 2.0 not persisting into MySQL

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);

Configuring Kundera with HBase

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

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