Name:
The name of this file is table_autoincrementedId

Hello and Thank you in advance for any assistance.

Purpose:
The project is a Visual web JavaServerFaces project that is in the same folder and that imports the app library. Modeled after the tutorial at
Using Java Persistence API Within a Visual Web JSF Application

The purpose of this code is to populate a JSP table from a MySQL table content (a auto-incremented set of records) using@Entity, entity controller and a persistence unit.

Question:
My question concerning this code is that I am not sure if the @Entity class is getting the Id because the table is bound to the database and displaying the Column names but no data.

errors:
There are no errors related to this code are .

Description
Code description: @Entity class. Some column getters,setters omitted.

@Entity
@Table(name = "content")
@NamedQueries({@NamedQuery(name = "Content.findAll", query = "SELECT c FROM Content c"), @NamedQuery(name = "Content.findById", query = "SELECT c FROM Content c WHERE c.contentPK.id = :id"), @NamedQuery(name = "Content.findByPublisherCode", query = "SELECT c FROM Content c WHERE c.contentPK.publisherCode = :publisherCode"), @NamedQuery(name = "Content.findByBookIsbn", query = "SELECT c FROM Content c WHERE c.bookIsbn = :bookIsbn"), @NamedQuery(name = "Content.findByBookTitle", query = "SELECT c FROM Content c WHERE c.bookTitle = :bookTitle"), @NamedQuery(name = "Content.findByArtist", query = "SELECT c FROM Content c WHERE c.artist = :artist"), @NamedQuery(name = "Content.findBySong", query = "SELECT c FROM Content c WHERE c.song = :song"), @NamedQuery(name = "Content.findByPageNum", query = "SELECT c FROM Content c WHERE c.pageNum = :pageNum")})
public class Content implements Serializable {

    private static final long serialVersionUID = 1L;
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @EmbeddedId
    protected ContentPK contentPK;
    @Column(name = "book_isbn")
    private String bookIsbn;
    @Column(name = "book_title")
    private String bookTitle;
    @Column(name = "artist")
    private String artist;
    @Column(name = "song")
    private String song;
    @Column(name = "page_num")
    private Integer pageNum;

    public Content() {
    }

    public Content(ContentPK contentPK) {
        this.contentPK = contentPK;
    }

    public Content(int id, String publisherCode) {
        this.contentPK = new ContentPK(id, publisherCode);
    }

    public ContentPK getContentPK() {
        return contentPK;
    }

    public void setContentPK(ContentPK contentPK) {
        this.contentPK = contentPK;
    }

Code description:ContentController.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.samples.model;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;

/**
 *
 * @author depot
 */
public class ContentController {

    private EntityManagerFactory emf;

    private EntityManager getEntityManager() {
        if(emf==null){
            emf=Persistence.createEntityManagerFactory("MusicLibraryPersistencePU");
        }
        return emf.createEntityManager();
    }
    public Content[] getContent(){
        EntityManager em = getEntityManager();
        try{
            javax.persistence.Query q=em.createQuery("select c from Content as c");
            return (Content[])q.getResultList().toArray(new Content[0]);
        }finally{
            em.close();
        }
    }
}

Code description:Content.java As I was preparing this question I noticed this class and will have to look at it to understand if the @Id and @GeneratedValue(strategy = GenerationType.IDENTITY) belong here.

[CODE]
/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.samples.model;

import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Embeddable;

/**
 *
 * @author depot
 */
@Embeddable
public class ContentPK implements Serializable {
    @Basic(optional = false)
    @Column(name = "id")
    private int id;
    @Basic(optional = false)
    @Column(name = "publisher_code")
    private String publisherCode;

    public ContentPK() {
    }

    public ContentPK(int id, String publisherCode) {
        this.id = id;
        this.publisherCode = publisherCode;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getPublisherCode() {
        return publisherCode;
    }

    public void setPublisherCode(String publisherCode) {
        this.publisherCode = publisherCode;
    }

    @Override
    public int hashCode() {
        int hash = 0;
        hash += (int) id;
        hash += (publisherCode != null ? publisherCode.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 ContentPK)) {
            return false;
        }
        ContentPK other = (ContentPK) object;
        if (this.id != other.id) {
            return false;
        }
        if ((this.publisherCode == null && other.publisherCode != null) || (this.publisherCode != null && !this.publisherCode.equals(other.publisherCode))) {
            return false;
        }
        return true;
    }

    @Override
    public String toString() {
        return "com.samples.model.ContentPK[id=" + id + ", publisherCode=" + publisherCode + "]";
    }

}

Code description: SessionBean1.java

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.samples.web;

import com.samples.model.Content;
import com.samples.model.ContentController;
import com.sun.rave.web.ui.appbase.AbstractSessionBean;
import javax.faces.FacesException;

/**
 * <p>Session scope data bean for your application.  Create properties
 *  here to represent cached data that should be made available across
 *  multiple HTTP requests for an individual user.</p>
 *
 * <p>An instance of this class will be created for you automatically,
 * the first time your application evaluates a value binding expression
 * or method binding expression that references a managed bean using
 * this class.</p>
 *
 * @version SessionBean1.java
 * @version Created on Mar 13, 2009, 7:02:04 AM
 * @author depot
 */
public class SessionBean1 extends AbstractSessionBean {

    private Content[] content; // <editor-fold defaultstate="collapsed" desc="Managed Component Definition">

    /**
     * <p>Automatically managed component initialization.  <strong>WARNING:</strong>
     * This method is automatically generated, so any user-specified code inserted
     * here is subject to being replaced.</p>
     */
    private void _init() throws Exception {
    }
    // </editor-fold>

    /**
     * <p>Construct a new session data bean instance.</p>
     */
    public SessionBean1() {
    }

    /**
     * <p>This method is called when this bean is initially added to
     * session scope.  Typically, this occurs as a result of evaluating
     * a value binding or method binding expression, which utilizes the
     * managed bean facility to instantiate this bean and store it into
     * session scope.</p>
     * 
     * <p>You may customize this method to initialize and cache data values
     * or resources that are required for the lifetime of a particular
     * user session.</p>
     */
    @Override
    public void init() {
        // Perform initializations inherited from our superclass
        super.init();
        // Perform application initialization that must complete
        // *before* managed components are initialized
        // TODO - add your own initialiation code here
        try {
            _init();
        } catch (Exception e) {
            log("SessionBean1 Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
        }
        updateContent();

        // <editor-fold defaultstate="collapsed" desc="Managed Component Initialization">
        // Initialize automatically managed components
        // *Note* - this logic should NOT be modified
        try {
            _init();
        } catch (Exception e) {
            log("SessionBean1 Initialization Failure", e);
            throw e instanceof FacesException ? (FacesException) e : new FacesException(e);
        }
    // </editor-fold>
    // Perform application initialization that must complete
    // *after* managed components are initialized
    // TODO - add your own initialization code here
    }

    /**
     * <p>This method is called when the session containing it is about to be
     * passivated.  Typically, this occurs in a distributed servlet container
     * when the session is about to be transferred to a different
     * container instance, after which the <code>activate()</code> method
     * will be called to indicate that the transfer is complete.</p>
     *
     * <p>You may customize this method to release references to session data
     * or resources that can not be serialized with the session itself.</p>
     */
    @Override
    public void passivate() {
    }

    /**
     * <p>This method is called when the session containing it was
     * reactivated.</p>
     * 
     * <p>You may customize this method to reacquire references to session
     * data or resources that could not be serialized with the
     * session itself.</p>
     */
    @Override
    public void activate() {
    }

    /**
     * <p>This method is called when this bean is removed from
     * session scope.  Typically, this occurs as a result of
     * the session timing out or being terminated by the application.</p>
     * 
     * <p>You may customize this method to clean up resources allocated
     * during the execution of the <code>init()</code> method, or
     * at any later time during the lifetime of the application.</p>
     */
    @Override
    public void destroy() {
    }

    /**
     * <p>Return a reference to the scoped data bean.</p>
     *
     * @return reference to the scoped data bean
     */
    protected ApplicationBean1 getApplicationBean1() {
        return (ApplicationBean1) getBean("ApplicationBean1");
    }

    public void updateContent() {
        ContentController contentController = new ContentController();
        content = contentController.getContent();
    }

    public Content[] getContent() {
        return content;
    }

    public void setContent(Content[] content) {
        this.content = content;
    }
}

Code description:persistence.xml

Thanks again.
-ceyesuma

Edited 3 Years Ago by Dani: Formatting fixed

Is this table going to work with the entity class I have above?

CREATE TABLE content(
id INTEGER GENERATED ALWAYS AS IDENTITY,

publisher_code          CHAR(2),
book_isbn		char(20),
book_title              char(100), 
artist                  char(150),
song                    char(150),
page_num                INT(4)
);


ALTER TABLE content ADD CONSTRAINT idPK PRIMARY KEY(id);



Description



Code description:Content.java (Entity class)

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package musiclibrarypersistenceapp.app;

import java.io.Serializable;
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;

/**
 *
 * @author depot
 */
@Entity
@Table(name = "content")
@NamedQueries({@NamedQuery(name = "content.findAll", query = "SELECT c FROM content c"), @NamedQuery(name = "content.findById", query = "SELECT c FROM content c WHERE c.id = :id"), @NamedQuery(name = "content.findByPublisherCode", query = "SELECT c FROM content c WHERE c.publisherCode = :publisherCode"), @NamedQuery(name = "content.findByBookIsbn", query = "SELECT c FROM content c WHERE c.bookIsbn = :bookIsbn"), @NamedQuery(name = "content.findByBookTitle", query = "SELECT c FROM content c WHERE c.bookTitle = :bookTitle"), @NamedQuery(name = "content.findByArtist", query = "SELECT c FROM content c WHERE c.artist = :artist"), @NamedQuery(name = "content.findBySong", query = "SELECT c FROM content c WHERE c.song = :song"), @NamedQuery(name = "content.findByPageNum", query = "SELECT c FROM content c WHERE c.pageNum = :pageNum")})
public class Content implements Serializable {
    private static final long serialVersionUID = 1L;
  
    @Column(name = "publisher_code")
    private String publisherCode;
    @Column(name = "book_isbn")
    private String bookIsbn;
    @Column(name = "book_title")
    private String bookTitle;
    @Column(name = "artist")
    private String artist;
    @Column(name = "song")
    private String song;
    @Column(name = "page_num")
    private Integer pageNum;
     @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Basic(optional = false)
    @Column(name = "id")
    private Integer id;

    public Content() {
    }

    public Content(Integer id) {
        this.id = id;
    }

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getPublisherCode() {
        return publisherCode;
    }

    public void setPublisherCode(String publisherCode) {
        this.publisherCode = publisherCode;
    }

    public String getBookIsbn() {
        return bookIsbn;
    }

    public void setBookIsbn(String bookIsbn) {
        this.bookIsbn = bookIsbn;
    }

    public String getBookTitle() {
        return bookTitle;
    }

    public void setBookTitle(String bookTitle) {
        this.bookTitle = bookTitle;
    }

    public String getArtist() {
        return artist;
    }

    public void setArtist(String artist) {
        this.artist = artist;
    }

    public String getSong() {
        return song;
    }

    public void setSong(String song) {
        this.song = song;
    }

    public Integer getPageNum() {
        return pageNum;
    }

    public void setPageNum(Integer pageNum) {
        this.pageNum = pageNum;
    }

    @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 Content)) {
            return false;
        }
        Content other = (Content) 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 "musiclibrarypersistenceapp.app.Content[id=" + id + "]";
    }

}

To fix missing code in last post:




Description



Code description: persistence.xml

<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.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_1_0.xsd">
  <persistence-unit name="MLPPU" transaction-type="RESOURCE_LOCAL">
    <provider>oracle.toplink.essentials.PersistenceProvider</provider>
    <class>musiclibrarypersistenceapp.app.Content</class>
    <properties>
      <property name="toplink.jdbc.user" value="root"/>
      <property name="toplink.jdbc.password" value="ceyesuma"/>
      <property name="toplink.jdbc.url" value="jdbc:mysql://localhost:3306/splashbookdb"/>
      <property name="toplink.jdbc.driver" value="com.mysql.jdbc.Driver"/>
    </properties>
  </persistence-unit>
</persistence>
This article has been dead for over six months. Start a new discussion instead.