JPA entity returns null while database is not empty - jpa

I am developing a Java web application with I am using netbeans 8 as IDE and glassfissh as the server I am trying to fetch data from Users table in the database I need to use JPA as data model layer for this purpose,
edited
although the Entity is generated by netbeans from a table in the MySQL database which has some rows the resultList which is returned from the executing the query returns no rows from a table in Derby database and it is empty
in the following I provided my Entity Java bean code which is automatically generated by netbeans IDE
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author Home
*/
#Entity
#Table(name = "users")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u"),
#NamedQuery(name = "Users.findById", query = "SELECT u FROM Users u WHERE u.id = :id"),
#NamedQuery(name = "Users.findByName", query = "SELECT u FROM Users u WHERE u.name = :name"),
#NamedQuery(name = "Users.findByEmail", query = "SELECT u FROM Users u WHERE u.email = :email"),
#NamedQuery(name = "Users.findByPassword", query = "SELECT u FROM Users u WHERE u.password = :password"),
#NamedQuery(name = "Users.findByRememberToken", query = "SELECT u FROM Users u WHERE u.rememberToken = :rememberToken"),
#NamedQuery(name = "Users.findByCreatedAt", query = "SELECT u FROM Users u WHERE u.createdAt = :createdAt"),
#NamedQuery(name = "Users.findByUpdatedAt", query = "SELECT u FROM Users u WHERE u.updatedAt = :updatedAt")})
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "name")
private String name;
// #Pattern(regexp="[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message="Invalid email")//if the field contains email address consider using this annotation to enforce field validation
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "email")
private String email;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "password")
private String password;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "remember_token")
private String rememberToken;
#Basic(optional = false)
#NotNull
#Column(name = "created_at")
#Temporal(TemporalType.TIMESTAMP)
private Date createdAt;
#Basic(optional = false)
#NotNull
#Column(name = "updated_At")
#Temporal(TemporalType.TIMESTAMP)
private Date updatedAt;
public Users() {
}
public Users(Integer id) {
this.id = id;
}
public Users(Integer id, String name, String email, String password, String rememberToken, Date createdAt, Date updatedAt) {
this.id = id;
this.name = name;
this.email = email;
this.password = password;
this.rememberToken = rememberToken;
this.createdAt = createdAt;
this.updatedAt = updatedAt;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getRememberToken() {
return rememberToken;
}
public void setRememberToken(String rememberToken) {
this.rememberToken = rememberToken;
}
public Date getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Date createdAt) {
this.createdAt = createdAt;
}
public Date getUpdatedAt() {
return updatedAt;
}
public void setUpdatedAt(Date updatedAt) {
this.updatedAt = updatedAt;
}
#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 Users)) {
return false;
}
Users other = (Users) 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 "some string";
}
}
and this is my Servlet code where I try to get the Users of database
#PersistenceUnit
EntityManagerFactory emf;
emf.createEntityManager().createNamedQuery("Users.findAll").getResultList().size()
but the ResultList did not fetch any data from database
this is the log from the server which shows iit is connected to Derby
Config: Connected: jdbc:derby://localhost:1527/sun-appserv-samples;;create=true
User: APP
Database: Apache Derby Version: 10.10.1.3 - (1557168)
Driver: Apache Derby Network Client JDBC Driver Version: 10.10.2.0 - (1582446)
edited
whil based on configuration I think it is supposed to connect to MySQL this is my glassfish-resources.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE resources PUBLIC "-//GlassFish.org//DTD GlassFish Application Server 3.1 Resource Definitions//EN" "http://glassfish.org/dtds/glassfish-resources_1_5.dtd">
<resources>
<jdbc-connection-pool allow-non-component-callers="false" associate-with-thread="false"
connection-creation-retry-attempts="0" connection-creation-retry-interval-in-seconds="10"
connection-leak-reclaim="false" connection-leak-timeout-in-seconds="0" connection-validation-method="auto-commit"
datasource-classname="com.mysql.jdbc.jdbc2.optional.MysqlDataSource" fail-all-connections="false"
idle-timeout-in-seconds="300" is-connection-validation-required="false" is-isolation-level-guaranteed="true"
lazy-connection-association="false" lazy-connection-enlistment="false" match-connections="false"
max-connection-usage-count="0" max-pool-size="32" max-wait-time-in-millis="60000" name="mysql_mysql_rootPool"
non-transactional-connections="false" pool-resize-quantity="2" res-type="javax.sql.ConnectionPoolDataSource"
statement-timeout-in-seconds="-1" steady-pool-size="8" validate-atmost-once-period-in-seconds="0"
wrap-jdbc-objects="false">
<property name="serverName" value="localhost"/>
<property name="portNumber" value="3306"/>
<property name="databaseName" value="mydatabase"/>
<property name="User" value="root"/>
<property name="Password" value=""/>
<property name="URL" value="jdbc:mysql://localhost:3306/mydatabase"/>
<property name="driverClass" value="com.mysql.jdbc.Driver"/>
</jdbc-connection-pool>
<jdbc-resource enabled="true" jndi-name="realestateConnection" object-type="user" pool-name="mysql_mysql_rootPool"/>
</resources>
and this is my persistence.xml file
<?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="architectsPU" transaction-type="JTA">
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action" value="create"/>
<property name="eclipselink.logging.level" value="FINE"/>
</properties>
</persistence-unit>
</persistence>
edited
please help me how to solve this issue and how can change the config in order to get connected to the right database when deploying the file that tells server which data source to connect is it same as `persistence.xml? and if not where is it located?

As the comments on the question state clearly enough, your JPA provider is using Apache Derby for database rather than what you wanted (mySQL). This is because your persistence.xml doesn't bother specifying what datasource(s) to use. You need to specify jtaDataSource (and maybe also nonJtaDataSource) to point to your JTA MySQL DataSource so then the JPA provider has the information it needs to use your DataSource.

Related

there's no change in h2 table (objects are not created) made by jpa intellij

i wanna create objects with intellij (jpa) system,
but after i create objects,
there's no change in h2 console.
i expect that the objects are made like this, enter image description here
(wanna make ITEM and MOVIE objects)
but what i got is this. enter image description here
these are the codes that i wrote.
package hellojpa;
import javax.persistence.Entity;
#Entity
public class Album extends Item{
private String artist;
}
package hellojpa;
import javax.persistence.Entity;
#Entity
public class Book extends Item{
private String author;
private String isbn;
}
package hellojpa;
import org.hibernate.engine.internal.JoinSequence;
import org.hibernate.mapping.Join;
import javax.persistence.*;
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
public class Item {
#Id
#GeneratedValue
private Long id;
private String name;
private int price;
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 int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
}
package hellojpa;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
public class JpaMain {
public static void main(String[] args){
EntityManagerFactory emf = Persistence.createEntityManagerFactory("hello");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
tx.begin();
try{
Movie movie = new Movie();
movie.setDirector("aaaa");
movie.setActor("bbbb");
movie.setName("바람과 함께 사라지다");
movie.setPrice(10000);
tx.commit();
}catch(Exception e){
tx.rollback();
} finally{
em.close();
}
emf.close();
}
}
package hellojpa;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
#Entity
public class Locker {
#Id
#GeneratedValue
private Long id;
private String name;
#OneToOne(mappedBy = "locker")
private Member member;
}
package hellojpa;
import net.bytebuddy.dynamic.TypeResolutionStrategy;
import org.hibernate.annotations.Fetch;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
public class Member {
#Id #GeneratedValue
#Column(name = "MEMBER_ID")
private Long id;
#Column(name = "USERNAME")
private String username;
#ManyToOne
#JoinColumn(name = "Team_ID",insertable = false, updatable = false)
private Team team;
#OneToOne
#JoinColumn(name ="LOCKER_ID")
private Locker locker;
#OneToMany(mappedBy = "member")
private List<MemberProduct> memberProducts = new ArrayList<>();
public Long getId() {return id;}
public void setId(Long id) {this.id = id;}
public String getUsername() {return username;}
public void setUsername(String username) {this.username = username;}
}
package hellojpa;
import javax.persistence.*;
import java.time.LocalDateTime;
#Entity
public class MemberProduct {
#Id
#GeneratedValue
private Long id;
#ManyToOne
#JoinColumn(name="MEMBER_ID")
private Member member;
#ManyToOne
#JoinColumn(name = "PRODUCT_ID")
private Product product;
private int count;
private int price;
private LocalDateTime orderDateTime;
}
package hellojpa;
import javax.persistence.Entity;
#Entity
public class Movie extends Item{
private String director;
private String actor;
public String getDirector() {
return director;
}
public void setDirector(String director) {
this.director = director;
}
public String getActor() {
return actor;
}
public void setActor(String actor) {
this.actor = actor;
}
}
package hellojpa;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
public class Product {
#Id
#GeneratedValue
private Long id;
private String name;
#OneToMany (mappedBy = "product")
private List<MemberProduct> memberProducts = new ArrayList<>();
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;
}
}
package hellojpa;
public enum RoleType {
GUEST, USER, ADMIN
}
package hellojpa;
import javax.persistence.*;
import java.util.ArrayList;
import java.util.List;
#Entity
public class Team {
#Id #GeneratedValue
#Column(name = "TEAM_ID")
private Long id;
private String name;
#OneToMany
#JoinColumn(name = "TEAM_ID")
private List<Member> members = new ArrayList<>();
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 List<Member> getMembers() {
return members;
}
public void setMembers(List<Member> members) {
this.members = members;
}
}
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="2.2"
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_2.xsd">
<persistence-unit name="hello">
<properties>
<!-- 필수 속성 -->
<property name="javax.persistence.jdbc.driver" value="org.h2.Driver"/>
<property name="javax.persistence.jdbc.user" value="sa"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.jdbc.url" value="jdbc:h2:tcp://localhost/~/test"/>
<property name="hibernate.dialect" value="org.hibernate.dialect.H2Dialect"/>
<!-- 옵션 -->
<property name="hibernate.show_sql" value="true"/>
<property name="hibernate.format_sql" value="true"/>
<property name="hibernate.use_sql_comments" value="10"/>
<property name="hibernate.hbm2ddl.auto" value="create" />
</properties>
</persistence-unit>
</persistence>
You forgot to use the entityManager to persist your new entity. Therefore, jpa does not know about the new entity and nothing is saved.
Just add : em.persist(movie);
The screenshots you provided, in combination with <property name="hibernate.hbm2ddl.auto" value="create" />, suggests that you were not finished creating entity classes when you first run your application. Now if you use hibernate.hbm2ddl.auto = create and there is allready a schema present in your H2, it won't update the schema even though you added one or more entity classes.
The community documentation suggests that you use hibernate.hbm2ddl.auto = update in order to update the schema when the application is run.
Please note that, according to this post, it is not safe to use update in a productive environment.
Despite the best efforts of the Hibernate team, you simply cannot rely on automatic updates in production. Write your own patches, review them with DBA, test them, then apply them manually.
Theoretically, if hbm2ddl update worked in development, it should work in production too. But in reality, it's not always the case.
I hope this helps.

how to Generating Database using jpa , jetty and dao

I'm newbie in JPA, Jetty and Dao.
I use PostgreSQL to my database.
why I can't generate entities into the database after running my project.
my error
java.lang.NullPointerException
at
com.inventory.aset.controller.UserServlet.doGet(UserServlet.java:110)
and my entities do not generate into database.
this my pom files
this my entity class
#Entity
#Table(name = "tbl_users", catalog = "myDb", schema = "", uniqueConstraints = {
#UniqueConstraint(columnNames = {"username"})})
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "EntityUsers.findAll", query = "SELECT u FROM EntityUsers u")
, #NamedQuery(name = "EntityUsers.findByUserId", query = "SELECT u FROM EntityUsers u WHERE u.userId = :userId")
, #NamedQuery(name = "EntityUsers.findByEmail", query = "SELECT u FROM EntityUsers u WHERE u.email = :email")
, #NamedQuery(name = "EntityUsers.findByUsername", query = "SELECT u FROM EntityUsers u WHERE u.username = :username")
, #NamedQuery(name = "EntityUsers.findByPassword", query = "SELECT u FROM EntityUsers u WHERE u.password = :password")
})
public class EntityUsers implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "user_id", nullable = false)
private Long userId;
#Pattern(regexp = "[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?", message = "Invalid email Address")
#Basic(optional = false)
#Column(name = "email", nullable = false, length = 120, unique = true)
private String email;
#Basic(optional = false)
#Column(name = "username", nullable = false, length = 120)//, unique = true
private String username;
#Basic(optional = false)
#Column(name = "password", nullable = false, length = 65)
private String password;
}
this my persistence.xml
<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="inventoryAsetPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<non-jta-data-source>java:app/jdbc/dbinventory</non-jta-data-source>
<class>com.inventory.aset.entity.users.EntityUsers</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<shared-cache-mode>NONE</shared-cache-mode>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.postgresql.Driver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:postgresql://localhost:5432/myDb"/>
<property name="javax.persistence.jdbc.user" value="<users>"/>
<property name="javax.persistence.jdbc.password" value="<password>"/>
<property name="eclipselink.ddl-generation" value="drop-and-create-tables"/>
</properties>
</persistence-unit>
</persistence>
this my Dao
#Stateless
public class EntityUsersDao extends AbstractFacade<EntityUsers> implements EntityUsersLocal {
#PersistenceContext(unitName = "inventoryAsetPU")
private EntityManager em;
public EntityUsersDao() {
super(EntityUsers.class);
}
protected EntityManager EntityCategoriesDao() {
return em;
}
#Override
public void createUser(EntityUsers dataUser) {
em.persist(dataUser);
}
#Override
public void updateUser(EntityUsers dataUser) {
em.merge(dataUser);
}
#Override
public void deleteUser(EntityUsers dataUser) {
em.merge(dataUser);
}
#Override
public void removeUser(long paramLong) {
em.remove(getUsers(paramLong));
}
#Override
public EntityUsers getUsers(long userId) {
return em.find(EntityUsers.class, userId);
}
#Override
public List<EntityUsers> getAllUsers() {
return em.createNamedQuery("EntityUsers.findAll").getResultList();
}
#Override
public List<EntityUsers> findByUsername(String username) {
return em.createQuery("SELECT u FROM EntityUsers u WHERE u.username = \"" + username + "\"").getResultList();
}
#Override
public EntityUsers find(Object paramObject) {
return (EntityUsers) em.find(EntityUsers.class, paramObject);
}
#Override
public int count() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
#Override
protected EntityManager getEntityManager() {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
this my servlet code
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Inside doGet");
PrintWriter out = response.getWriter();
try {
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date now = new Date();
String tgl = sdf.format(now);
String searchField = request.getParameter("searchField");
String searchString = request.getParameter("searchString");
System.out.println("isi searchField: " + searchField);
System.out.println("isi searchString: " + searchString);
String status = request.getParameter("status");
String rows = request.getParameter("rows");
String page = request.getParameter("page");
System.out.println("rows" + rows);
System.out.println("page" + page);
int totalPages = 0;
int totalCount = 0;
if (totalCount > 0) {
if (totalCount % Integer.parseInt(rows) == 0) {
totalPages = totalCount / Integer.parseInt(rows);
} else {
totalPages = totalCount / Integer.parseInt(rows) + 1;
}
} else {
totalPages = 0;
}
Date d2 = sdf.parse(tgl);
String relation = "";
Date tanggalMasuk = null;
Date tanggalGaransi = null;
JSONArray jsonArray = new JSONArray();
//This line error code//
**List<EntityUsers> usersList = usersDao.getAllUsers();**
I have tried it many times but I've been unsuccessful. Please help!

HSQLDB Tables not generating

I have a database using HSQLDB, and my persistence.xml file is not creating the tables as I would expect. Here is my persistence.xml code:
<?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="DanPfeiffer-SE452-ProjectPU" transaction-type="RESOURCE_LOCAL">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<class>java.user.jpa.User</class>
<class>java.score.jpa.Score</class>
<class>java.teeBox.jpa.TeeBox</class>
<class>java.course.jpa.Course</class>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.jdbc.driver" value="org.hsqldb.jdbc.JDBCDriver"/>
<property name="javax.persistence.jdbc.url" value="jdbc:hsqldb:hsql://localhost/mydb"/>
<property name="javax.persistence.jdbc.user" value="SA"/>
<property name="javax.persistence.jdbc.password" value=""/>
<property name="javax.persistence.schema-generation.database.action" value="drop-and-create-tables"/>
<property name="eclipselink.deploy-on-startup" value="true" />
</properties>
</persistence-unit>
</persistence>
I have a few Java Beans written with #Entity annotation. Here's the simplest of those beans.
package main.java.user.jpa;
import java.io.Serializable;
import java.util.Collection;
import javax.persistence.*;
import javax.validation.constraints.NotNull;
import main.java.score.IScore;
import main.java.score.jpa.Score;
import main.java.user.IUser;
#Entity
#NamedQuery(name = "findAllUsers", query = "select u from User u")
public class User implements Serializable, IUser {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int userId;
#NotNull
private String firstName;
#NotNull
private String lastName;
#NotNull
private double handicap;
#OneToMany
private Collection<Score> scores;
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getFirstName() {
return this.firstName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getLastName() {
return this.lastName;
}
public void setId(int id) {
this.userId = id;
}
public int getId() {
return userId;
}
public void setHandicap(double hcp) {
this.handicap = hcp;
}
public double getHandicap() {
return handicap;
}
#Override
public void setScores(Collection<Score> scores) {
if (this.scores != null){
for (Score temp : scores){
this.scores.add(temp);
}
}
else{
this.scores = scores;
}
}
#Override
public Collection<Score> getScores() {
// TODO Auto-generated method stub
return null;
}
public boolean equals(Object object){
boolean result = false;
if (object instanceof User){
User temp = (User)object;
if (temp.getFirstName().equals(this.firstName)
&& temp.getLastName().equals(this.lastName)
&& temp.getHandicap() == this.handicap){
result = true;
}
}
return result;
}
public String toString(){
String result = ("User: \nID: " + this.userId + "\nName:" + this.firstName + " " + this.lastName + " \nHandicap:" + this.handicap);
return result;
}
}
From my understanding, the persistence.xml file should drop and create all of the tables each time the hsqldb.jar file is run.
I haven't found an issue with my connection (it works when I connect, just no data), my persistence file or location. I originally populated the database this way.

Getting java.lang.NoSuchFieldError: ERRORS_IGNORED for hibernate-ogm with mongodb

I am trying to use hibernate-ogm with mongodb and getting no such fieds error
persistence.xml
<persistence-unit name="mongodb-test" transaction-type="JTA">
<provider>org.hibernate.ogm.jpa.HibernateOgmPersistence</provider>
<properties>
<property name="hibernate.ogm.datastore.provider" value="mongodb"></property>
<property name="hibernate.ogm.datastore.host" value="192.168.0.237"></property>
<property name="hibernate.ogm.datastore.create_database" value="true"></property>
<property name="hibernate.ogm.datastore.database" value="anand_test"></property>
<property name="hibernate.ogm.mongodb.connection_timeout" value="5000"></property>
<property name="hibernate.ogm.mongodb.authentication_mechanism" value="PLAIN"></property>
<property name="hibernate.ogm.datastore.document.association_storage" value="IN_ENTITY"></property>
<property name="hibernate.ogm.mongodb.association_document_storage" value="GLOBAL_COLLECTION"></property>
<property name="hibernate.ogm.mongodb.write_concern" value="ACKNOWLEDGED"></property>
<property name="hibernate.ogm.mongodb.read_preference" value="PRIMARY_PREFERRED"></property>
</properties>
</persistence-unit>
Person.java
import javax.persistence.Entity;
import javax.persistence.Id;
import org.bson.types.ObjectId;
import org.hibernate.annotations.Type;
#Entity
public class Person {
#Id
#Type(type = "objectid")
private String id;
private String firstName;
private String lastName;
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 getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public Person(){
}
public Person(String firstName,String lastName){
this.firstName = firstName;
this.lastName = lastName;
}
}
TestMongoconnection.java
import com.mongodb.Person;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
public class TestMongoConnection {
public static void main(String[] args) {
EntityManagerFactory entityManagerFactory = Persistence.createEntityManagerFactory("mongodb-test");
EntityManager manager = entityManagerFactory.createEntityManager();
manager.getTransaction().begin();
Person anandMohan = new Person("Anand","Mohan");
manager.persist(anandMohan);
manager.getTransaction().commit();
manager.close();
}
}
I am having mongodb version 3.0.2 and hibernate-ogm 4.2.0 final with mongodb java version 3.x jars
The problem is with the java jar version of the mongodb as 3.x version is not yet supported have to use 2.x version of it
https://forum.hibernate.org/viewtopic.php?f=31&t=1040127&p=2485319#p2485319

Object: entity.ENTITY[ id=null ] is not a known entity type

this is a similar post to one I have seen before regarding this exception but I am utterly lost. I have yet to persist an entity to a database using JPA, although I have read from tables using it no problem. My setup is Netbeans 7.1 using Glassfish 3.1.1, EclipseLink is my persistence provider. I have a very simple scenario where I just want to test writing a persons name and age into the database and having the id auto increment. Its an MySql database with the fields: Id, FirstName and Age. Heres my code:
Web servlet to take in name and age from html form:
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userPath = request.getServletPath();
if(userPath.equals("/addUser")){
//get request parameters from form
String name = request.getParameter("name");
String age = request.getParameter("age");
//set request attributes to be used by forwarded page
request.setAttribute("name", name);
request.setAttribute("age", age);
//create manager class to add person to database
Manager manager = new Manager();
manager.addPerson(name, age);
userPath = "/result";
}
// use RequestDispatcher to forward request internally
String url = "/WEB-INF/view" + userPath + ".jsp";
try {
request.getRequestDispatcher(url).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
Manager class that takes in name and age, creates a person object and persists it.
public class Manager {
private static final String PERSISTENCE_UNIT_NAME = "FormPU";
private static EntityManagerFactory factory;
public Manager() {
}
public void addPerson(String name, String age) {
factory = Persistence.createEntityManagerFactory(PERSISTENCE_UNIT_NAME);
EntityManager em = factory.createEntityManager();
Persons persons = new Persons();
persons.setName(name);
persons.setAge(age);
em.getTransaction().begin();
em.persist(persons);
em.getTransaction().commit();
em.close();
}
}
Persons entity class:
/**
*
* #author esmiala
*/
#Entity
#Table(name = "persons")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Persons.findAll", query = "SELECT p FROM Persons p"),
#NamedQuery(name = "Persons.findById", query = "SELECT p FROM Persons p WHERE
p.id = :id"),
#NamedQuery(name = "Persons.findByFirstName", query = "SELECT p FROM Persons p
WHERE p.firstName = :firstName"),
#NamedQuery(name = "Persons.findByAge", query = "SELECT p FROM Persons p WHERE
p.age = :age")})
public class Persons implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#NotNull
#Column(name = "Id")
private Integer id;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "FirstName")
private String firstName;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 255)
#Column(name = "Age")
private String age;
public Persons() {
}
public Persons(Integer id) {
this.id = id;
}
public Persons(Integer id, String firstName, String age) {
this.id = id;
this.firstName = firstName;
this.age = age;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getAge() {
return age;
}
public void setAge(String age) {
this.age = age;
}
#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 Persons)) {
return false;
}
Persons other = (Persons) 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 "entity.Persons[ id=" + id + " ]";
}
}
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="FormPU" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/form</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties/>
</persistence-unit>
</persistence>
Note: I have also tried setting exclude-unlisted-classes tag to true and list the class seperately but that didn't work either.
The exception:
WARNING: StandardWrapperValve[Controller]: PWC1406: Servlet.service() for servlet
Controller threw exception
java.lang.IllegalArgumentException: Object: entity.persons[ id=null ] is not a
known entity type.
atorg.eclipse.persistence.internal.sessions.UnitOfWorkImpl.registerNewObject
ForPersist(UnitOfWorkImpl.java:4141)
atorg.eclipse.persistence.internal.jpa.EntityManagerImpl.
persist(EntityManagerImpl.java:368)
at manager.Manager.addPerson(Manager.java:36)
at controller.Controller.doPost(Controller.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:754)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:847)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1523)
...and so on. Any help would be greatly appreciated!
<exclude-unlisted-classes> doesn't work as you would expect - the very presence of this element in persistence.xml disables automatic discovery of #Entity classes, no matter what's inside it.
Also, #Entity(name="persons") is probably not what you want, use #Entity #Table (name="persons") instead.
So you say you can read the class fine, but get an error persisting a new instance?
Can you update an object that you read?
It seems you are having some kind of class loader issue. Somehow you have the class on your classpath twice, or have two different class loaders. The object you are passing to persist is from a different class loader than the one JPA is using. You can check the class loader of what was read, and of the object being persisted to see how they differ.
Have you redeployed you app, or hotdeployed? Does it work if you shut down/restart the server properly. Ensure you are closing your old EntityManagerFactory before redeploying.
Concerning youe concrete problem, try to see if this link helps.
Anyway, the way you are instantiating the EntityManager is not thread safe.
You can see here why. Or, better, you can use NetBeans' wizard for creating JPA controller classes from entity classes, and see how it injects the EntityManager:
#PersistenceContext
private EntityManager em;
See also that the controller classes (the equivalent of your Manager POJO) have the Stateless annotation. This is because you can safely inject an EJB (in this case the EntityManager) only in an object whose lifecycle is managed by the web container (see here for further reference about Accessing Enterprise Beans).