Siavosh
Siavosh

Reputation: 2354

JPA entity returns null while database is not empty

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?

Upvotes: 0

Views: 1414

Answers (1)

Neil Stockton
Neil Stockton

Reputation: 11531

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.

Upvotes: 2

Related Questions