Impossible to bypass caches with Hibernate EntityManager - java

Is there a problem in my code ? I cannot retrieve the changes on my User entity without restarting the application.
Here is my persistence.xml:
<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="pu" transaction-type="RESOURCE_LOCAL">
<properties>
<property name = "hibernate.show_sql" value = "true" />
</properties>
</persistence-unit>
</persistence>
I create my EntityManagerFactory this way:
public static EntityManagerFactory entityManagerFactory(String driver, String url, String user, String password, DataSource datasource) {
LocalContainerEntityManagerFactoryBean entityManagerFactory = new LocalContainerEntityManagerFactoryBean();
DBPoolDataSource dataSource = new DBPoolDataSource();
dataSource.setName("pool-ds");
dataSource.setDescription("Pooling DataSource");
dataSource.setDriverClassName(driver);
dataSource.setUrl(url);
dataSource.setUser(user);
dataSource.setPassword(password);
dataSource.setMinPool(5);
dataSource.setMaxPool(10);
dataSource.setMaxSize(30);
dataSource.setIdleTimeout(3600);
dataSource.setValidationQuery("SELECT id FROM test");
entityManagerFactory.setDataSource(datasource);
entityManagerFactory.setPersistenceUnitName("pu");
entityManagerFactory.setJpaDialect(new HibernateJpaDialect());
entityManagerFactory.setJpaVendorAdapter(new HibernateJpaVendorAdapter());
Map<String, Object> props = entityManagerFactory.getJpaPropertyMap();
props.put("hibernate.cache.use_second_level_cache", "false");
props.put("hibernate.cache.use_query_cache", "false");
entityManagerFactory.afterPropertiesSet();
return entityManagerFactory.getObject();
}
Here is my Entity:
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "USER")
public class User {
#Id
private String trigram;
#Column(name = "FIRST_NAME")
private String firstName;
#Column(name = "LAST_NAME")
private String lastName;
public String getTrigram() {
return trigram;
}
public void setTrigram(String trigram) {
this.trigram = trigram;
}
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;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
if (!trigram.equals(user.trigram)) return false;
if (firstName != null ? !firstName.equals(user.firstName) : user.firstName != null) return false;
return lastName != null ? lastName.equals(user.lastName) : user.lastName == null;
}
#Override
public int hashCode() {
int result = trigram.hashCode();
result = 31 * result + (firstName != null ? firstName.hashCode() : 0);
result = 31 * result + (lastName != null ? lastName.hashCode() : 0);
return result;
}
}
Here is my repository:
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.TypedQuery;
public class UserDao {
private EntityManager entityManager;
public UserDao(EntityManager entityManager) {
this.entityManager = entityManager;
}
public User getByTrigram(String trigram) throws NoResultException {
entityManager.getEntityManagerFactory().getCache().evictAll();
TypedQuery<User> q = entityManager.createQuery(
"select u from User u where u.trigram = :trigram", User.class);
q.setParameter("trigram", trigram);
q.setHint("javax.persistence.cache.retrieveMode", CacheRetrieveMode.BYPASS);
return q.getSingleResult();
}
}
-> So the entity doesn't come from L1.
entityManagerFactory.getJpaPropertyMap() contains both:
hibernate.cache.use_second_level_cache=false
hibernate.cache.use_query_cache=false
-> So there should be no L2 nor from query cache.
But still, the changes made directly in my database are retrieved by my repository only after a restart.
Someone has an idea?
Thank you!

By default, Hibernate 4 has disabled L2 cache and query cache, so it's useless to configure hibernate.cache.use_second_level_cache=false and hibernate.cache.use_query_cache=fals.
The entity is cached in the hibernate Session (L1), and if you want to refresh this particular entity according to the underlying database, you can create a method like this:
public void refresh(User user) {
org.hibernate.Session session = entityManager.unwrap(Session.class);
session.refresh(user);
}
and call it after you retrieve the user, this way:
User currentUser = userDao.getByTrigram(login);
userDao.refresh(currentUser);
Hope it helped!

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.

JBoss EAP doesn't generate tables on specified database

i have an issue when attempting to generate table with JBoss EAP 7.2.
My database is named KMT on MS SQL 2014, but when i run the JBoss EAP it creates the table in the system database named "master" despite I specified KMT in my connection-URL.
I created the datasource with the admin console of the JBoss EAP and when testing the connection i got a succes message.
My connection-URL:
JNDI Name: java:/MSSQLDS
Driver Name: sqljdbc42.jar
Connection URL: jdbc:microsoft:sqlserver://localhost:1433;databasename=KMT
My 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="KMT">
<jta-data-source>java:/MSSQLDS</jta-data-source>
<properties>
<property name="hibernate.hbm2ddl.auto" value="create-drop"/>
</properties>
</persistence-unit>
</persistence>
And finally the entity I try to generate inside KMT database:
package be.Alstom.kmt.domaine;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
#SuppressWarnings("serial")
#Entity
#Table(name="designer", schema="kmt")
public class Designer implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column
#NotNull
private String userName;
#Column
#NotNull
private String password;
public Designer() {
}
public Designer(String userName, String password) {
super();
this.userName = userName;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
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;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + id;
result = prime * result + ((password == null) ? 0 : password.hashCode());
result = prime * result + ((userName == null) ? 0 : userName.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Designer other = (Designer) obj;
if (id != other.id)
return false;
if (password == null) {
if (other.password != null)
return false;
} else if (!password.equals(other.password))
return false;
if (userName == null) {
if (other.userName != null)
return false;
} else if (!userName.equals(other.userName))
return false;
return true;
}
}
Here the my MSSQL server. Hibernate create table in systemdatabase/master instead of KMT.

#Delete returns HTTP Status 405 - Method Not Allowed

Hi i am trying to delect some entities from database, but when i use #Delete i get error in browsers, but Get is working. I am using hibernate JPA
Here are my code samples
#Entity
package pl.test.model;
import javax.persistence.*;
import java.util.Collection;
#Entity
public class Mestechnologygroup {
private Integer idTechnologyGroup;
private String name;
private String description;
private Integer number;
private Collection<Mestechnology> mestechnologiesByIdTechnologyGroup;
#Id
#Column(name = "idTechnologyGroup")
public Integer getIdTechnologyGroup() {
return idTechnologyGroup;
}
public void setIdTechnologyGroup(Integer idTechnologyGroup) {
this.idTechnologyGroup = idTechnologyGroup;
}
#Basic
#Column(name = "Name")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#Basic
#Column(name = "Description")
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
#Basic
#Column(name = "Number")
public Integer getNumber() {
return number;
}
public void setNumber(Integer number) {
this.number = number;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Mestechnologygroup that = (Mestechnologygroup) o;
if (idTechnologyGroup != null ? !idTechnologyGroup.equals(that.idTechnologyGroup) : that.idTechnologyGroup != null)
return false;
if (name != null ? !name.equals(that.name) : that.name != null) return false;
if (description != null ? !description.equals(that.description) : that.description != null) return false;
if (number != null ? !number.equals(that.number) : that.number != null) return false;
return true;
}
#Override
public int hashCode() {
int result = idTechnologyGroup != null ? idTechnologyGroup.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (description != null ? description.hashCode() : 0);
result = 31 * result + (number != null ? number.hashCode() : 0);
return result;
}
#OneToMany(mappedBy = "mestechnologygroupByIdTechnologyGroup")
public Collection<Mestechnology> getMestechnologiesByIdTechnologyGroup() {
return mestechnologiesByIdTechnologyGroup;
}
public void setMestechnologiesByIdTechnologyGroup(Collection<Mestechnology> mestechnologiesByIdTechnologyGroup) {
this.mestechnologiesByIdTechnologyGroup = mestechnologiesByIdTechnologyGroup;
}
}
presistance.xml
<?xml version="1.0" encoding="UTF-8"?>
<persistence xmlns="http://java.sun.com/xml/ns/persistence" version="2.0">
<persistence-unit name="testPU" transaction-type="JTA">
<provider>org.hibernate.jpa.HibernatePersistenceProvider</provider>
<class>pl.test.model.Mesattachmentoperation</class>
<class>pl.test.model.Mesattachmenttechnology</class>
<class>pl.test.model.Mesoperation</class>
<class>pl.test.model.Mesoperationdictionary</class>
<class>pl.test.model.Mesoperationstate</class>
<class>pl.test.model.Mesproduct</class>
<class>pl.test.model.Mesproducttype</class>
<class>pl.test.model.Mesproductxoperation</class>
<class>pl.test.model.Mesresource</class>
<class>pl.test.model.Mesresourcexoperation</class>
<class>pl.test.model.Mestechnology</class>
<class>pl.test.model.Mestechnologygroup</class>
<class>pl.test.model.Mesusers</class>
<properties>
<property name="hibernate.connection.driver_class" value="org.postgresql.Driver"/>
<property name="hibernate.connection.url" value="jdbc:postgresql://localhost:5432/mes"/>
<property name="hibernate.connection.username" value="postgres"/>
<property name="hibernate.connection.password" value="xxxx"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL9Dialect"/>
</properties>
</persistence-unit>
</persistence>
Repository with method
package pl.test.repo;
import com.sun.istack.internal.NotNull;
import pl.test.model.Mestechnologygroup;
import pl.test.model.Mesusers;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.TypedQuery;
import javax.transaction.Transactional;
import java.util.List;
import static javax.transaction.Transactional.TxType.REQUIRED;
import static javax.transaction.Transactional.TxType.SUPPORTS;
#Transactional(SUPPORTS)
public class TechnologyGroupRepo {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("testPU");
EntityManager em = entityManagerFactory.createEntityManager();
public Mestechnologygroup find(#NotNull Integer id) {
return em.find(Mestechnologygroup.class, id);
}
public List<Mestechnologygroup> findAll() {
TypedQuery<Mestechnologygroup> query = em.createQuery("from Mestechnologygroup ", Mestechnologygroup.class);
return query.getResultList();
}
#Transactional(REQUIRED)
public void delete(#NotNull Integer id) {
em.remove(em.getReference(Mestechnologygroup.class, id));
}
}
here i use #Delete
package pl.test.rest;
import pl.test.model.Mestechnologygroup;
import pl.test.repo.TechnologyGroupRepo;
import javax.inject.Inject;
import javax.validation.constraints.Min;
import javax.ws.rs.*;
import javax.ws.rs.core.Response;
import java.util.List;
import static javax.transaction.Transactional.TxType.REQUIRED;
import static javax.transaction.Transactional.TxType.SUPPORTS;
import static javax.ws.rs.core.MediaType.APPLICATION_JSON;
#Path("/tg")
public class TechnologyGroupEndpoint{
#Inject
private TechnologyGroupRepo technologyGroupRepo;
#GET
#Path("/{id : \\d+}")
#Produces(APPLICATION_JSON)
public Response getBook(#PathParam("id") #Min(1) Integer id) {
Mestechnologygroup mestechnologygroup = technologyGroupRepo.find(id);
if (mestechnologygroup == null)
return Response.status(Response.Status.NOT_FOUND).build();
return Response.ok(mestechnologygroup).build();
}
#DELETE
#Path("/d/{id : \\d+}")
public Response deleteBook(#PathParam("id") #Min(1) Integer id) {
technologyGroupRepo.delete(id);
return Response.noContent().build();
}
#GET
#Produces(APPLICATION_JSON)
public Response getBooks() {
List<Mestechnologygroup> mestechnologygroups = technologyGroupRepo.findAll();
if (mestechnologygroups.size() == 0)
return Response.status(Response.Status.NO_CONTENT).build();
return Response.ok(mestechnologygroups).build();
}
}
I revice that response in Google chrome
Response
I would appreciate any help :) Thanks in advance;)
The problem that you are facing is because a browser url is always accessed via GET http method. You cannot do for other http methods.
In order to test your DELETE endpoint, you have to do it using a REST client.
A few examples of rest clients: command line: curl, wget. With GUI: Postman, Insomnia.
An example of doing this from the command line:
curl -X DELETE "http://localhost:8080/test-1.0-SNAPSHOT/resources/tg/d/22"
#Delete i get error in browsers, but Get is working.
When you hit url on browser, it takes as GET request.
you can not make any other request than GET by browser, so GET works.
Try using http client tool like postman etc. or curl.

session.save() have some mistake with "unknown entity "

I'm new to hibernate and as I researched. When i want to start my JUnit, this mistake could be occur every time. I guess something wrong with my hbm.xml file. Maybe I am missing something because I'm still new to hibernate.
This is my hbm.xml file.
<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.test.UserEntity" table="user" schema="" catalog="junwa">
<id name="id" column="id"/>
<property name="username" column="username"/>
<property name="gender" column="gender"/>
<property name="birthday" column="birthday"/>
<property name="addres" column="addres"/>
</class>
</hibernate-mapping>
And this is my UserEntity.java file
package com.test;
import javax.persistence.*;
import java.sql.Timestamp;
#Entity
#Table(name = "user", schema = "", catalog = "junwa")
public class UserEntity {
private int id;
private String username;
private String gender;
private Timestamp birthday;
private String addres;
#Id
#Column(name = "id")
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Basic
#Column(name = "username")
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
#Basic
#Column(name = "gender")
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Basic
#Column(name = "birthday")
public Timestamp getBirthday() {
return birthday;
}
public void setBirthday(Timestamp birthday) {
this.birthday = birthday;
}
#Basic
#Column(name = "addres")
public String getAddres() {
return addres;
}
public void setAddres(String addres) {
this.addres = addres;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
UserEntity that = (UserEntity) o;
if (id != that.id) return false;
if (username != null ? !username.equals(that.username) : that.username != null) return false;
if (gender != null ? !gender.equals(that.gender) : that.gender != null) return false;
if (birthday != null ? !birthday.equals(that.birthday) : that.birthday != null) return false;
if (addres != null ? !addres.equals(that.addres) : that.addres != null) return false;
return true;
}
#Override
public int hashCode() {
int result = id;
result = 31 * result + (username != null ? username.hashCode() : 0);
result = 31 * result + (gender != null ? gender.hashCode() : 0);
result = 31 * result + (birthday != null ? birthday.hashCode() : 0);
result = 31 * result + (addres != null ? addres.hashCode() : 0);
return result;
}
}
This is my test file.
/**
* Created by junwa on 2017/4/2.
*/
import com.test.Students;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import java.util.Date;
public class StudentsTest {
private SessionFactory sessionFactory;
private Session session;
private Transaction transaction;
#Before
public void init(){
// create a deploy object
Configuration config = new Configuration().configure();
// create a service licenced object
ServiceRegistry serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
// create a session factory object
sessionFactory = config.buildSessionFactory(serviceRegistry);
// create a sessoin object
session = sessionFactory.openSession();
// start transaction
transaction = session.beginTransaction();
}
#After
public void destroy(){
// commit transaction
transaction.commit();
// close session
session.close();
// close session factory
sessionFactory.close();
}
#Test
public void testSaveStudents(){
// create a object
Students s = new Students(1,"junwa","male",new Date(),"Anhui");
// save object to mysql database
session.save(s);
session.flush();
}
}
This my output
enter image description here
As Faraz Durrani said when you already have done the mapping in hbm.xml file, why do you need annotations for? Or the vice versa.You have to remove one of them. I would say remove hbm.xml file and use Annotations only.
One more thing I have noticed that you are not closing the transection also.
You can't use hbm.xml and annotation at the same time.

Entity Beans inside EJB Project class mapping

I am using Eclipse and Derby database (with Embeeded Driver). As a starting point I am running the asadmin (from glassfish) to start-database from there. The database within eclipse can be pinged, as well as connected to just fine. Having started my EJB project which combines the session beans and entity beans I have ran into the following exception - java.lang.IllegalArgumentException: Unknown entity bean class: class model.Userbay, please verify that this class has been marked with the #Entity annotation.
Just few lines below this error i get pointed to this line of code - Userbay user = emgr.find(model.Userbay.class, username);
Although my feeling is that it could be a problem with the persistence.xml that causes it in the first place.
I would really appreciate any hints/help given towards fixing this annoying problem me and my friend are facing for quite a time now..
The following are the java/xml files;
Persistence.xml (which is stored under ejbModule/META-INF)
<?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="EJBAuctionv2">
<class>model.Userbay</class>
<class>model.Item</class>
<class>model.Category</class>
</persistence-unit>
</persistence>
I've also tried adding the following properties tag - however it grants another error org.apache.derby.client.am.SqlException: Schema 'ADRIAN' does not exist
<properties>
<property name="javax.persistence.jdbc.password" value="test" />
<property name="javax.persistence.jdbc.user" value="adrian" />
<property name="javax.persistence.jdbc.driver" value="org.apache.derby.jdbc.EmbeededDriver" />
<property name="javax.persistence.jdbc.url" value="jdbc:derby:C:/Users/Adrian/MyDB;create=true" />
</properties>
userRegistrationSB.java (Session Bean)
package auction;
import javax.ejb.EJB;
import javax.ejb.LocalBean;
import javax.ejb.Remote;
import javax.ejb.Singleton;
import javax.ejb.Stateful;
import javax.ejb.Stateless;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import model.Userbay;
/**
* Session Bean implementation class userRegistrationSB
*/
#Remote #Stateless
public class userRegistrationSB implements userRegistrationSBRemote {
//#EJB private Userbay user;
#PersistenceContext private EntityManager emgr;
/**
* Default constructor.
*/
public userRegistrationSB() {
// TODO Auto-generated constructor stub
System.out.println("TEST2");
}
#Override
public boolean registerUser(String username, String password, String email,
String firstname, String lastname) {
boolean registered = false;
System.out.println("Registering an user");
Userbay user = emgr.find(model.Userbay.class, username);
if (user != null) {
System.out.println("Username doesn't exist.");
registered = true;
} else {
registered = false;
System.out.println("Username already exists.");
}
return registered;
}
#Override
public boolean userExists(String username) {
// TODO Auto-generated method stub
return false;
}
#Override
public boolean userMatchesPassword(String username, String password) {
// TODO Auto-generated method stub
return false;
}
}
Userbay.java (Entity Bean)
package model;
import java.io.Serializable;
import javax.persistence.*;
import java.util.List;
#Entity #Table (name = "Userbay")
/*#NamedQuery(name="Userbay.findAll", query="SELECT u FROM Userbay u")*/
public class Userbay implements Serializable {
private static final long serialVersionUID = 1L;
#Id #Column(name="USER_NAME")
private String userName;
private String email;
#Column(name="FIRST_NAME")
private String firstName;
#Column(name="LAST_NAME")
private String lastName;
#Column(name="PASSWORD")
private String password;
//bi-directional many-to-one association to Item
#OneToMany(mappedBy="userbay")
private List<Item> items;
public Userbay() {
}
public String getUserName() {
return this.userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
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;
}
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Item> getItems() {
return this.items;
}
public void setItems(List<Item> items) {
this.items = items;
}
public Item addItem(Item item) {
getItems().add(item);
item.setUserbay(this);
return item;
}
public Item removeItem(Item item) {
getItems().remove(item);
item.setUserbay(null);
return item;
}
}
I've also tried adding the following properties tag - however it
grants another error org.apache.derby.client.am.SqlException: Schema
'ADRIAN' does not exist
Have you checked if your database schema was actually created? If it did not, adding the following lines in your persistence.xml might help.
<property name="eclipselink.ddl-generation" value="create-tables" />
<property name="eclipselink.ddl-generation.output-mode" value="database" />
You may also want to undeploy your application manually or if it is your developer machine and this is the only application deployed merely delete content of the applications directory in your domain.

Categories