Jpa-Mysql

Hi
i am trying to run an application which was running on oracle,since i dint have oracle i am migrating the code to mysql, the entity class has
@SequenceGenerator(name = "BID_SEQUENCE_GENERATOR", sequenceName = "BID_SEQUENCE", initial Value = 1, allocation Size = 1)
@Id
@GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "BID_SEQUENCE_GENERATOR")
annotations ........... in my persistance.xml am using org.hibernate.dialect.MySQLDialect when i deplaoy the application i get error saying that dialect does not support
sequence .After goggling i found that mysql does not support sequence i generated table in mysql by modifying the defination
CREATE TABLE SEQUENCE (
SEQ_NAME VARCHAR(50) NOT NULL,
SEQ_COUNT int(38) AUTO_INCREMENT ,
PRIMARY KEY (SEQ_COUNT));
but i cannot depoly app as mysql dialect does not support sequnce..... is there any alternative.

yes, use auto_increment columns in combination with the IDENTITY generation type. That works flawlessly on MySQL. But it does mean you will have to change all your entities that are currently using a sequence.
  @Id
  @GeneratedValue(strategy=IDENTITY)
  @Column(name="id")
  private int id;

Similar Messages

  • JPA - Mysql - GeneratedValue

    I am using Mysql with Eclipselink 2.0.1 and have the following situation:
    My Entity is using a field declared like this:
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private long referenceNumber;
    The DDL is generated and in my database all tables are created. If I insert a new record within my EJB I am getting as the "referenceNumber" not "1" - I am getting sometimes "50" sometimes "1232". It is a completely random id. Is it possible to get an ID which is starting by 1 and incrementing automatically ?
    I have tried to use GenerationType.IDENTY but this has some problems with cascading operations, so I do not want to use it.

    Hello,
    I just started playing with JPA and mysql. My tables's primary keys use auto-increment option in database. To tell application how to work with these fields I use following statements and everything works perfect after some troubles in the beggining of course :-)) :
    @Entity
    @Table(name = "C_ADRESA_TYP") //, schema = "KMPV"
    public class CiselnikAdresaTyp implements Serializable{
         private static final long serialVersionUID = 1L;
         @Id
         //@Required - cannot be used when using auto-increment and IDENTITY gerenator
         @Hidden
         @Column(name = "PK_ADRESA_TYP", insertable = false, nullable = false, updatable = true)
         @GeneratedValue(strategy=GenerationType.IDENTITY)
         private int pkAdresaTyp;
         @Required
         @Column(name = "KOD", length = 30, nullable = false, updatable = true)
         private String kod;
    .....etc
    In case of you are experiencing still some troubles witch some cascade actions, this could be regarding your foreing keys, exactly on on update on delete actions.
    Hope it'll help.
    archenroot
    Edited by: user8916162 on Nov 9, 2010 11:18 AM

  • Question about the Glassfish Persistance engine

    Goodday,
    I am working with Sun Appserver (glassfish v2). And using entity beans to generate my mysql database and work with the data.
    Now somting catched my eye the last few days if your using the @OneTOne() method. The persistence engine makes the object a could be null. For instance I have the folowing code:
        @Id
        @GeneratedValue
        @Column(name = "Mandatecode", nullable=false)
        public int getMandatecode() { return Mandatecode; }
        public void setMandatecode(int str) { this.Mandatecode = str; }
        @Column(name = "Projectnaam", length=20, nullable=false)
        public String getProjectnaam() { return Projectnaam; }
        public void setProjectnaam(String str) { this.Projectnaam = str; }
        //This should be true but for testing purpuses its left to false.
        @OneToOne()
        @JoinColumn(name="ProjectType")
        public ProjectSoort getProjecttype () { return projecttype; }
        public void setProjecttype (ProjectSoort ps) { this.projecttype = ps; }It would result in the following table:
    Mandatecode
    Projectname
    ProjectType
    But all the collums have may not be null. However I want to ProjectType to be aible to be null in this table. How do I do this?

    I'm not sure what you're asking, but a useful resource that may answer your question is the article [Master the New Persistence Paradigm with JPA|http://www.devx.com/Java/Article/33650/], an article which focuses on JPA , MySQL, and MySQL DDL generation.

  • JPA with MySQL-Data-Source

    Hello Forum,
    I have a question regarding usage of a MySQL-Data-Source in combination with JPA
    on the SAP NetWeaver Application Server, Java ™ EE 5 Edition.
    I have setup a custom datasource like explained in paper:
    "Working with Database Tables, DataSources and JMS Resources"
    - registered the database driver via telnet (Using mysql-connector-java-5.0.3-bin.jar)
    - created the data-sources.xml file underneath the META-INF dir of the EAR project
    [code]
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE data-sources SYSTEM "data-sources.dtd" >
    <data-sources>
      <data-source>
        <data-source-name>titan_cruises_ds</data-source-name>
        <driver-name>mysql-connector-java-5.0.3-bin.jar</driver-name>
         <init-connections>1</init-connections>
         <max-connections>10</max-connections>
         <max-time-to-wait-connection>60</max-time-to-wait-connection>
         <expiration-control>
              <connection-lifetime>600</connection-lifetime>
              <run-cleanup-thread>60</run-cleanup-thread>
         </expiration-control>
         <sql-engine>native_sql</sql-engine>
        <jdbc-1.x>
          <driver-class-name>com.mysql.jdbc.Driver</driver-class-name>
          <url>jdbc:mysql://ourHost.internal.com:3306/practise_titan_cruises</url>
          <user-name>myUser</user-name>
          <password>myPass</password>
        </jdbc-1.x>
      </data-source>
    </data-sources>
    [/code]
    After that I manually created the persistence.xml underneath the META-INF dir of the EJB project.
    [code]
    <persistence xmlns="http://java.sun.com/xml/ns/persistence" version="1.0">
         <persistence-unit name="titan_cruises_pu">
              <jta-data-source>titan_cruises_ds</jta-data-source>
         </persistence-unit>
    </persistence>
    [/code]
    After that I created the Entity named "Cabin" and the corresponding table within the db.
    Entity code:
    [code]
    package de.collogia.beans.pojo.ship;
    import java.io.IOException;
    import java.io.Serializable;
    import javax.persistence.Column;
    import javax.persistence.Entity;
    import javax.persistence.GeneratedValue;
    import javax.persistence.Id;
    import javax.persistence.Table;
    This persisted POJO class models the cabin data.
    <p>
    In this class persistence annotations are placed on the getter methods
    of the attributes. This tells the persistence manager to access them
    via the corresponding get- and set-Methods.</p>
    (Unfortunately this does not work on NetWeaver and I had to place them
    on field level aggain...)
    @author Henning Malzahn ([email protected])
    svn-revision:         $Rev:: 670                                           $:
    svn-lasted-edited-by: $Author:: henning                                    $:
    svn-last-changed:     $Date:: 2007-02-21 21:49:51 +0100 (Wed, 21 Feb 2007) $:
    @Entity
    @Table(name = "cabin")
    public class Cabin implements Serializable {
        /** The generated serial version UID used for serialization. */
        private static final long serialVersionUID = -8522497314498903378L;
        /** The actual version number of this class used for serialization. */
        private static int actualVersion = 1;
        /** The cabin's id. */
        @Id
        @GeneratedValue
        @Column(name = "id")
        private long id;
        /** The cabin's name */
        @Column(name = "name")
        private String name;
        /** The cabin's deck level */
        @Column(name = "deck_level")
        private int deckLevel;
        /** The cabin's ship id */
        @Column(name = "ship_id")
        private int shipId;
        /** The cabin's bed count */
        @Column(name="bed_count")
        private int bedCount;
    /---- Serialization/ Deserialization methods -/
    Method that is responsible for deserialization of the object.
    @param in The <code>ObjectInputStream</code> object to read
              the data from.
    @throws IOException That may occur when reading from the
                        <code>ObjectInputStream</code> object
    @throws ClassNotFoundException That may occur when invoking the default
                                   deserialization mechanism.
        private void readObject(final java.io.ObjectInputStream in)
            throws IOException, ClassNotFoundException {
            /* Invoke default deserialization mechanism. */
            in.defaultReadObject();
            /* Read the actual version number of the class. */
            actualVersion =  in.readInt();
        } // End of readObject()
    Method that is responsible for serialization of the object.
    @param out The <code>ObjectOutputStream</code> object to write
               the data to.
    @throws IOException That may occur when writing to the
                        <code>ObjectOutputStream</code> object.
        private void writeObject(final java.io.ObjectOutputStream out)
            throws IOException {
            /* Invoke default serialization mechanism. */
            out.defaultWriteObject();
            /* Write the actual version number of the class. */
            out.writeInt(actualVersion);
        } // End of writeObject()
    /---- Defining constructors -/
    Private default constructor.
        private Cabin() {
        } // End of default constructor
    Full constructor.
    @param name The cabin's name.
    @param deckLevel The cabin's deck level.
    @param shipId The cabin's ship id.
    @param bedCount The cabin's bed count.
        public Cabin(final String name,
                     final int deckLevel,
                     final int shipId,
                     final int bedCount) {
            this.name = name;
            this.deckLevel = deckLevel;
            this.shipId = shipId;
            this.bedCount = bedCount;
        } // End of full constructor
    /---- Overridden class methods -/
    Returns a string representation of the cabin's data.
    @see java.lang.Object#toString()
        @Override
        public String toString() {
            StringBuffer strBuf = new StringBuffer();
            strBuf.append(this.name);
            strBuf.append("\n");
            strBuf.append(this.deckLevel);
            strBuf.append("\n");
            strBuf.append(this.shipId);
            strBuf.append("\n");
            strBuf.append(this.bedCount);
            return strBuf.toString();
        } // End of toString()
    /---- Defining instance methods -/
    Get method for the member "<code>id</code>".
    @return Returns the id.
        public long getId() {
            return this.id;
    Set method for the member "<code>id</code>".
    HTDODO hm: Check whether it is possible to have setId method
    using private accesss level with NetWeaver JPA-Provider!
    @param id The id to set.
        private void setId(final long id) {
            this.id = id;
    Get method for the member "<code>name</code>".
    @return Returns the name.
        public String getName() {
            return this.name;
    Set method for the member "<code>name</code>".
    @param name The name to set.
        public void setName(final String name) {
            this.name = name;
    Get method for the member "<code>deckLevel</code>".
    @return Returns the deckLevel.
        public int getDeckLevel() {
            return this.deckLevel;
    Set method for the member "<code>deckLevel</code>".
    @param deckLevel The deckLevel to set.
        public void setDeckLevel(final int deckLevel) {
            this.deckLevel = deckLevel;
    Get method for the member "<code>shipId</code>".
    @return Returns the shipId.
        public int getShipId() {
            return this.shipId;
    Set method for the member "<code>shipId</code>".
    @param shipId The shipId to set.
        public void setShipId(final int shipId) {
            this.shipId = shipId;
    Get method for the member "<code>bedCount</code>".
    @return Returns the bedCount.
        public int getBedCount() {
            return this.bedCount;
    Set method for the member "<code>bedCount</code>".
    @param bedCount The bedCount to set.
        public void setBedCount(final int bedCount) {
            this.bedCount = bedCount;
    } // End of class Cabin
    [/code]
    After that I created the TravelAgentBean, a Stateless Session Bean, implementing
    a remote interface that allows construction and persisting of new Cabin objects:
    [code]
    package de.collogia.beans.session.stateless;
    import javax.ejb.Stateless;
    import javax.persistence.EntityManager;
    import javax.persistence.PersistenceContext;
    import de.collogia.beans.pojo.ship.Cabin;
    Class that implements the <code>TravelAgentRemote</code> interface
    and defines the business methods of the TravelAgent service.
    @author Henning Malzahn ([email protected])
    svn-revision:         $Rev:: 670                                           $:
    svn-lasted-edited-by: $Author:: henning                                    $:
    svn-last-changed:     $Date:: 2007-02-21 21:49:51 +0100 (Wed, 21 Feb 2007) $:
    @Stateless
    public class TravelAgentBean implements TravelAgentRemote {
        /** The <code>Log</code> object for this class. */
    //    private static final Log LOGGER;
        /** The <code>PersistenceManager</code> object. */
        @PersistenceContext(unitName = "titan_cruises_pu")
        EntityManager em;
    /---- Static initializer -/
    //    static {
    //        LOGGER = LogFactory.getLog(TravelAgentBean.class);
    //    } // End of static initializer block
    /---- Implementing remote interface methods -/
    {@inheritDoc}
        public void createCabin(final Cabin cabin) {
            this.em.persist(cabin);
        } // End of createCabin()
    } // End of class TravelAgentBean
    [/code]
    After that I created a Controller class containing a main method that looks up the remote
    interface of the TravelAgentBena like explained in document "Accessing Enterprise JavaBeans Using JNDI
    in SAP NetWeaver Application Server, Java ™ EE 5 Edition" written by Validimir Pavlov of SAP NetWeaver
    development team.
    Unfortunately I receive an Exception after invoking the createCabin(...) method.
    On the console of the NWDS I receive:
    [code]
    javax.ejb.EJBException: Exception in getMethodReady() for stateless bean sap.com/test2Earannotation|test2Ejb.jarannotation|TravelAgentBean;
    nested exception is: com.sap.engine.services.ejb3.util.pool.PoolException: javax.ejb.EJBException: Cannot perform injection over bean instance
    Caused by: java.lang.RuntimeException: The persistence unit is inconsistent:
    The entity >>de.collogia.beans.pojo.ship.Cabin<< is mapped to the table >>cabin<<, which does not exist.
    [/code]
    But if I look at the log file located in "C:\NWAS_JAVAEE5\JP1\JC00\j2ee\cluster\server0\log\defaultTrace.0.trc"
    I see the real reason is:
    [code]
    [EXCEPTION]
    #6#1064#42000#You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax
    to use near '"cabin"' at line 1#collnx02.collogia.de:3306:null:practise_titan_cruises#select * from "cabin"#com.mysql.jdbc.exceptions.MySQLSyntaxErrorException:
    You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '"cabin"' at line 1
         at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:936)
         at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2870)
         at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1573)
         at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1665)
         at com.mysql.jdbc.Connection.execSQL(Connection.java:3124)
         at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1149)
         at com.mysql.jdbc.PreparedStatement.executeQuery(PreparedStatement.java:1262)
         at com.sap.sql.jdbc.basic.BasicPreparedStatement.executeQuery(BasicPreparedStatement.java:99)
         at com.sap.sql.jdbc.direct.DirectPreparedStatement.executeQuery(DirectPreparedStatement.java:307)
         at com.sap.sql.jdbc.direct.DirectPreparedStatement.executeQuery(DirectPreparedStatement.java:264)
         at com.sap.engine.services.dbpool.wrappers.PreparedStatementWrapper.executeQuery(PreparedStatementWrapper.java:274)
    [/code]
    My goodness - what a long post - sorry for this - I hope I provided all information
    necessary to deal with the issue.
    Am I thinking in the right direction to blame attribute [code]<sql-engine>native_sql</sql-engine>[/code]
    of file data-sources.xml for the beaviour? Are there any other argument options than native_sql?
    Thanks in Advance!
    Henning Malzahn

    Hi Henning,
    > Despite the fact it's working now I have to do some
    > changes to my code currently
    > developed using JBoss/ Hibernate combination.
    > Hibernate allows you to have the
    > default no-arg constructor with private visibility -
    > any special reason for the fact that
    > only protected is allowed on NetWeaver?
    Here we strictly implemented the checks according to the requirements of the JPA specification. Technically, we could do with private constructors as well. But the JPA specifications requires the constructor to be protected to allow a JPA implementation to subclass entities if needed.
    > The entities in the project are final classes
    > so declaring a ctor protected doesn't really make
    > sense...
    For the same reason, your entities should not be final. Are we missing a check here ?
    > Also the persistence.xml parameter
    >
    hibernate.hbm2ddl.auto
    with the value of
    > create-drop is very useful while
    > developing the app - everytime you deploy the project
    > you get a fresh database.
    > Is there a comparable option for NetWeaver?
    No, unfortunately, there is no comparable option in SAP JPA (yet). We understand that there is a need for forward mapping. We would have liked to delegate this task to the JPA design time (i.e. Dali). However, we had to discover that Dali does not perform this task properly and we can't recommend using it any more.
    Consequently, there is no automatic schema generation in SAP JPA 1.0.
    >
    > Another thing is the extra TMP_SEQUENCE table which
    > isn't necessary using JBoss and
    > Hibernate - what's the reason for that?
    With Hibernate Entity Manager, the id generation strategy in use with GenerationType.AUTO depends on the database dialect. This means that depending on the database dialect, IDENTITY columns, SEQUENCES or generator tables (TableHiLo) are required. As Hibernate has the before mentioned schema generation property this fact can be hidden to the user.
    In SAP JPA, we are always using a table generator if GenerationType.AUTO is used. This allows for better portability across databases. It requires the table TMP_SEQUENCE. As we unfortunately do not have a schema generation capability, the user must create this table.
    Best regards,
    Adrian

  • Can not do JPA/Hibernate ... Reverse Engineering with MySQL

    Hello,
    I'm using MyEclipse 7.1.1 and MySQL 5.1.34. The MySQL connector with java is mysql-connector-java-5.1.7-bin. I tried so many time to generate Hibernate/JPA class by MyEcipse but it still did not work. Here below are my error log (which i copied from workspace error log):
    !ENTRY org.eclipse.core.jobs 4 2 2009-05-29 22:07:20.709 !MESSAGE An internal error occurred during: "Generating Artifacts". !STACK 0 java.util.NoSuchElementException at java.util.HashMap$HashIterator.nextEntry(HashMap.java:844) at java.util.HashMap$ValueIterator.next(HashMap.java:871) at com.genuitec.eclipse.hibernate.tool.MESingleClassExporter.doStart(MESingleClassExporter.java:59) at com.genuitec.eclipse.hibernate.tool.hbm2x.VAbstractExporter.start(VAbstractExporter.java:97) at com.genuitec.eclipse.hibernate.wizards.GenerateArtifactsJob$3.execute(GenerateArtifactsJob.java:582) at org.hibernate.console.execution.DefaultExecutionContext.execute(DefaultExecutionContext.java:64) at org.hibernate.console.ConsoleConfiguration.execute(ConsoleConfiguration.java:95) at com.genuitec.eclipse.hibernate.wizards.GenerateArtifactsJob.run(GenerateArtifactsJob.java:417) at org.eclipse.core.internal.jobs.Worker.run(Worker.java:55)
    These information below are my system information that i copied from Myeclipse Installation Summary:
    *** Date: Friday, May 29, 2009 10:37:27 PM CDT ** System properties: OS=MacOSX OS version=10.5.7 Java version=1.5.0_16 *** MyEclipse details: MyEclipse Enterprise Workbench Version: 7.1.1 Build id: 7.1.1-20090310 *** Eclipse details: MyEclipse Enterprise Workbench Version: 7.1.1 Build id: 7.1.1-20090310 Eclipse Platform Version: 3.4.1.r341_v20080731-9I96EiDElYevwz-p1bP5z-NlAaP7vtX6Utotqsu Build id: M20080911-1700 Eclipse Java Development Tools Version: 3.4.1.r341_v20080709-0800-7o7tEAfEF_U5qyUgrb2HAp539P97 Build id: M20080709-0800 Eclipse Graphical Editing Framework GEF Version: 3.4.1.v20080806-67718083A56B4H2A3213573 Build id: 200809101400 Eclipse RCP Version: 3.4.100.r341_v20080814-989JESIEdAciFYfkZZsBfSwQ2341 Build id: M20080703-0800 Eclipse Plug-in Development Environment Version: 3.4.1.r341_v20080731-7T7U0E9mlRIuGUYviF_VP Build id: M20080703-0800 Eclipse startup command=-os macosx -ws carbon -arch x86 -showsplash -launcher /Library/Genuitec/MyEclipse 7.1 1/myeclipse.app/Contents/MacOS/myeclipse -name Myeclipse --launcher.library /Library/Genuitec/MyEclipse 7.1 1/myeclipse.app/Contents/MacOS//../../../../Common/plugins/org.eclipse.equinox.launcher.carbon.macosx_1.0.101.R34x_v20080731/eclipse_1115.so -startup /Library/Genuitec/MyEclipse 7.1 1/myeclipse.app/Contents/MacOS/../../../../Common/plugins/org.eclipse.equinox.launcher_1.0.101.R34x_v20080819.jar -clean -configuration ../../../configuration -keyring /Users/lamnguyen/.eclipse_keyring -consoleLog -showlocation -vm /System/Library/Frameworks/JavaVM.framework
    Here is my config file:
    <?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="NDProcessorPU" transaction-type="RESOURCE_LOCAL"> <provider>oracle.toplink.essentials.PersistenceProvider</provider>   <properties> <property name = "toplink.jdbc.driver" value = "com.mysql.jdbc.Driver"/> <property name = "toplink.jdbc.url" value = "jdbc:mysql://localhost/netdirs?autoReconnect=true"/> <property name = "toplink.jdbc.user" value = "root"/>   </properties> </persistence-unit>   </persistence>
    Please help me to resolve this problem. I tried so many ways such as: change others mysql connector driver version, refresh, re-install myeclipse... Someone who have any solutions please help me.
    Thank you!

    perhaps posting this question in a forum for MyEclipse would help?
    Or even Hibernate?
    None of these are JDBC related issues really, but probably configuration or setup of those.
    And while I could spend time noting that it is an eclipse error and thus some problem there in the first place...

  • Is it possible to use JPA Catalog & Schema in MySQL?

    Dear All,
    Could anyone explain the difference between JPA Catalog and Schema when using MySQL database? Below is an example where I have successfully used both Catalog and Schema to reference different databases:
    @Table(name="CUSTOMER", catalog="catalogName", schema="")  // Worked
                                          or
    @Table(name="CUSTOMER", catalog="", schema="schemaName")  // Worked
                                       but NOT
    @Table(name="CUSTOMER", catalog="catalogName", schema="schemaName") which resulted the following database exception:
    JDO76609: Got SQLException executing statement "CREATE TABLE catalogName.schemaName....
    com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException...
    Not sure whether MySQL support the use of both Catalog and Schema at the same time, or do they both mean the same thing which is just database instances? In other word, it does not support the idea of defining a Catalog within a Schema, or vice versa. Likewise, MySQL seems to use Catalog/Schema as database instance interchangeably with both on the same level. This means that an application will likely be required to create many database instances to be used in place of Schema.
    My understanding of the use of Catalog and Schema would be: catalogName.schemaName.CUSTOMER or schemaName.catalogName.CUSTOMER but does not reflect how MySQL work.
    It would be interesting to hear from others who has used MySQL as the underlying JPA database.
    Thanks a lot,
    Jack

    I use Photoshop Elements 3 ("Elements" not "Album"). I wasn't aware of an upgrade to PSE 3.2. If I upgrade will the Catalog be converted to a form that is compatible with PSA SE 3.2?

  • Proper JPA mapping for MySQL SET type?

    If I have a MySQL ENUM type, it seems straightforward to map it to "int" in Java. However, what about a MySQL SET type? I don't see an obvious way that that should be mapped to Java. I looked for examples of this, but I couldn't find any.
    if there's a better place to ask questions about this, please direct me.

    Hi Vinod,
    due to performance improvement when using forward only cursor we changed the default for the resultset type from TYPE_SCROLL_SENSITIVE to TYPE_FORWARD_ONLY starting with JDBC driver version 7.6. So I guess the exception comes from a statement where you didn't set the resultset type while creating it. Please check if all of the statements that you want to be scrollable have set the correct resultset type.
    Regards,
    Marco

  • JPA: is it possilble to create a entity class for a MySQL view?

    Thanks in advance.

    Yes, just use the view name instead of the table name in the @Table.
    -- James : http://www.eclipselink.org

  • How can I retrieve selected checkboxes by user into a JPA application?

    Hello, I'm developing an app in JPA, still learning this, I'm displaying some checkboxes which I save into a List, then I separate the selections and put them into an Array, which I convert into String and that's what I store into MySQL table, this is what I have on the index.xhtml file:
    <h:selectManyCheckbox value="#{employee.selectedItems}">
    <f:selectItems var="checkList" value="#{employee.checkboxList()}" itemValue="#{checkList.idTechnology}" itemLabel="#{checkList.name}"></f:selectItems>
    </h:selectManyCheckbox>
    The method checkboxList is in charge of generating the checkboxes and assign a value and name, and the method "selectedItems" is the List<String> that stores the selected checkboxes values, so what I save into the table is something like this: "1,4,6,7" but I don't know how to retrieve the selections and check the checxkboxes according the what the user have on the table:
    This is the method that I use to select all the records from the selected user, this fills all the textfields so I can edit the user, but not the checkboxes, and that's what I need to do:
    public void seleccionarEmpleado(int id_empleado){
    Query q = em.createNamedQuery("Employee.findByIdEmployee");
    q.setParameter("IdEmployee", IdEmployee);
    List<Empleado> listaEmple = q.getResultList();
    for(IdEmployee emple1 : listaEmple){
    emp.setIdEmployee(emple1 .getIdEmployeeo());
    emp.setName(emple1 .getName());
    emp.setLname(emple1 .getLname());
    emp.setTel(emple1 .getTel());
    emp.setAddress(emple1 .getDir());
    emp.setTech(emple1 .getTecha());
    Variable Tech is the one who gets the numbers like "2,3,4" etc, but how can I make the checkboxes to be checked according to these numbers? my english is not so good, thanks in advanced, have a nice day!

    Hello, I'm developing an app in JPA, still learning this, I'm displaying some checkboxes which I save into a List, then I separate the selections and put them into an Array, which I convert into String and that's what I store into MySQL table, this is what I have on the index.xhtml file:
    <h:selectManyCheckbox value="#{employee.selectedItems}">
    <f:selectItems var="checkList" value="#{employee.checkboxList()}" itemValue="#{checkList.idTechnology}" itemLabel="#{checkList.name}"></f:selectItems>
    </h:selectManyCheckbox>
    The method checkboxList is in charge of generating the checkboxes and assign a value and name, and the method "selectedItems" is the List<String> that stores the selected checkboxes values, so what I save into the table is something like this: "1,4,6,7" but I don't know how to retrieve the selections and check the checxkboxes according the what the user have on the table:
    This is the method that I use to select all the records from the selected user, this fills all the textfields so I can edit the user, but not the checkboxes, and that's what I need to do:
    public void seleccionarEmpleado(int id_empleado){
    Query q = em.createNamedQuery("Employee.findByIdEmployee");
    q.setParameter("IdEmployee", IdEmployee);
    List<Empleado> listaEmple = q.getResultList();
    for(IdEmployee emple1 : listaEmple){
    emp.setIdEmployee(emple1 .getIdEmployeeo());
    emp.setName(emple1 .getName());
    emp.setLname(emple1 .getLname());
    emp.setTel(emple1 .getTel());
    emp.setAddress(emple1 .getDir());
    emp.setTech(emple1 .getTecha());
    Variable Tech is the one who gets the numbers like "2,3,4" etc, but how can I make the checkboxes to be checked according to these numbers? my english is not so good, thanks in advanced, have a nice day!

  • Deployement problem in Oracle App Serv with hibernate + JPA and Spring

    Dear All,
         I am facing a problem in deployment of a web application in oracle application server 10g. but the same is working fine with Tomcat. The following Exception. Is being thrown.
         Failed to deploy web application "OraTest". Failed to deploy web application OraTest". . Nested exception Resolution:
    Base Exception:
    java.rmi.RemoteException
    deploy failed!: ; nested exception is:
    oracle.oc4j.admin.internal.DeployerException: Unknown assembly root-tag attribute: version. deploy failed!: ; nested exception is:
    oracle.oc4j.admin.internal.DeployerException: Unknown assembly root-tag attribute: version     I am using the following technologies
    1.     Spring 2.0.7
    2.     Struts 2.0.9
    3.     Hibernate 3.3
    4.     JPA 1.0
    5.     Oracle App Server 10.1.2.0.2
    Web.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/dtd/web-app_2_3.dtd">
    <web-app>
         <display-name>My Application</display-name>
         <filter>
              <filter-name>struts2</filter-name>
              <filter-class>
                   org.apache.struts2.dispatcher.FilterDispatcher
              </filter-class>
         </filter>
         <filter-mapping>
              <filter-name>struts2</filter-name>
              <url-pattern>/*</url-pattern>
         </filter-mapping>
         <welcome-file-list>
              <welcome-file>/index.jsp</welcome-file>
         </welcome-file-list>
         <servlet>
              <servlet-name>dwr-invoker</servlet-name>
              <servlet-class>
                   org.directwebremoting.servlet.DwrServlet
              </servlet-class>
              <init-param>
                   <param-name>debug</param-name>
                   <param-value>true</param-value>
              </init-param>
         </servlet>
         <servlet-mapping>
              <servlet-name>dwr-invoker</servlet-name>
              <url-pattern>/dwr/*</url-pattern>
         </servlet-mapping>
         <listener>
              <listener-class>
                   org.springframework.web.context.ContextLoaderListener
              </listener-class>
         </listener>
         <context-param>
              <param-name>contextConfigLocation</param-name>
              <param-value>
                   /WEB-INF/conf/spring/datasource-context.xml,
                   /WEB-INF/conf/spring/aop-context.xml          
              </param-value>
         </context-param>
    </web-app>
    /Datasource-context.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
         <bean class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor" lazy-init="true"/>
         <!--  following code is for using oracle -->
            <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" lazy-init="true">
              <property name="driverClassName">
                   <value>oracle.jdbc.driver.OracleDriver</value>
              </property>
              <property name="url">
                   <value>jdbc:oracle:thin:@//xxx.xxx.xxx.xxx/mydb</value>
              </property>
              <property name="username">
                   <value>admin</value>
              </property>
              <property name="password">
                   <value>admin</value>
              </property>
         </bean>
         <!--  following code is for using mysql -->
         <!--
         <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource" lazy-init="true">
              <property name="driverClassName">
                   <value>org.gjt.mm.mysql.Driver</value>
              </property>
              <property name="url">
                   <value>jdbc:mysql://192.168.10.157:3306/tpsadmin</value>
              </property>
              <property name="username">
                   <value>tpsadmin</value>
              </property>
              <property name="password">
                   <value>tpsadmin</value>+
              </property>
         </bean>
         -->
         <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" lazy-init="true">
              <property name="persistenceUnitName" value="mkclsetsPersistenceUnit"/>
              <property name="dataSource" ref="dataSource"/>
              <property name="jpaVendorAdapter">
                   <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" lazy-init="true">
                        <property name="database" value="ORACLE"/>               
                        <property name="showSql" value="true"/>
                   </bean>
              </property>
         </bean>
         <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager" lazy-init="true">
              <property name="entityManagerFactory" ref="entityManagerFactory"></property>
         </bean>
         <tx:annotation-driven transaction-manager="transactionManager"/>     
    </beans>Aop-context.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <beans xmlns="http://www.springframework.org/schema/beans"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xmlns:aop="http://www.springframework.org/schema/aop"
        xmlns:tx="http://www.springframework.org/schema/tx"
        xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.0.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.0.xsd
        http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-2.0.xsd">
    <!--  Bean Definition of all the required Interceptors -->
         <bean id="methodLoggingAdvice" class="com.mkcl.sets.common.interceptor.MehodLogInterceptor"/>
         <!--
         <bean id="appCacheManager" class="net.sf.ehcache.CacheManager">
              <constructor-arg index="0" type="java.net.URL" value="classpath:country-ehcache.xml"/>
         </bean>     
         -->
          <!--bean id="methodCacheInterceptor" -->
         <bean id="methodCachingAdvice"
              class="com.mkcl.sets.common.interceptor.MethodCacheInterceptor">
              <property name="cache">
                   <ref local="methodCache" />
              </property>
         </bean>
         <bean id="cacheManager"
              class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
              <property name="configLocation">
                   <value>WEB-INF/conf/other/ehcache.xml</value>
              </property>
         </bean>     
         <bean id="methodCache"
              class="org.springframework.cache.ehcache.EhCacheFactoryBean">
              <property name="cacheManager">
                   <ref local="cacheManager" />
              </property>
              <property name="cacheName">
                   <value>mkclSetsCache</value>
              </property>
         </bean>      
         <!--
         <bean id="methodCachingAdvice" class="interceptor.MethodCachingInterceptor"/>
          -->
         <aop:config>
              <aop:pointcut id="getCountriesPointCut" expression="execution(* com.mkcl.sets.dao.master.impl.LocationDAOImpl.getCountries())"/>          
              <!-- <aop:pointcut id="methodLogPointCut" expression="execution(* com.mkcl.sets.service.master.impl.CategoryServiceImpl.getAllCategories(..))"/> -->
              <aop:pointcut id="methodLogPointCutDao" expression="execution(* com.mkcl.sets.dao..*.*(..))"/>
              <aop:pointcut id="methodLogPointCutService" expression="execution(* com.mkcl.sets.service..*.*(..))"/>
              <aop:advisor id="methodCachingAdvisor" advice-ref="methodCachingAdvice" pointcut-ref="getCountriesPointCut"/>          
              <aop:advisor id="methodLoggingAdvisorDao" advice-ref="methodLoggingAdvice" pointcut-ref="methodLogPointCutDao"/>
              <aop:advisor id="methodLoggingAdvisorService" advice-ref="methodLoggingAdvice" pointcut-ref="methodLogPointCutService"/>
         </aop:config>
    </beans>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_1_0.xsd"
        version="1.0">
         <persistence-unit name="mkclsetsPersistenceUnit" transaction-type="RESOURCE_LOCAL">
              <!-- jta-data-source>mkclDS</jta-data-source-->
              <provider>org.hibernate.ejb.HibernatePersistence</provider>
              <!-- properties>
                   <property name="hibernate.dialect" value="org.hibernate.dialect.Oracle10gDialect"/>
                   <property name="hibernate.transaction.manager_lookup_class" value="org.hibernate.transaction.OC4JTransactionManager"/>
              </properties-->
         </persistence-unit>
    </persistence>Do I need to add some other configuration in the existing files or do I need to add some other configuration files ? Please help to deploy my application.
    Thanks a lot in advance.
    With Best Regards,
    Ishaan
    null

    Did you ever find a solution to this Ishaan?
    I imagine you ended up having to upgrade 10gR2 to 10gR3 at least. Correct?

  • Couldn't persist OneToMany JoinColumn/JoinTable (Unidir) using TopLink JPA

    Hi All,
    I am having a lot of difficulty deploying a OneToMany Unidirectional (Zipcode) record which consist of multiple Zipnames using TopLink on Glassfish v2r2, JDK1.6.0_06, MySQL 5.0, Netbeans 6.1 and Windows XP platform.
    Below are the relevant EJBs snippets:
    Zipcode class
    @Entity
    @Table(name="ZIPCODE")
    public class Zipcode implements Serializable {
    @OneToMany(cascade={CascadeType.ALL}, fetch=FetchType.EAGER)
    @JoinColumn(name="ZIPCODE_ID")    
                 or
        @JoinTable(name="ZIPCODE_ZIPNAME",          
                   joinColumns={@JoinColumn(name="ZIPCODE_ID")},
                   inverseJoinColumns={@JoinColumn(name="ZIPNAME_ID")})
        private Collection<Zipname> zipnames = new ArrayList<Zipname>();
        public Collection<Zipname> getNames()
         return zipnames;
        public void setZipnames(Collection<Zipname> zipnames)
         this.zipnames = zipnames;
    Zipname class does not maintain relationship back to Zipcode.
    public class ZipcodeApplicationClient {
    @PersistenceContext(unitName="GeographicalDB-PU")
    private static EntityManager manager;
        public ZipcodeApplicationClient() {
        public static void main(String[] args) {
            try {
                Zipcode zipcode_1 = new Zipcode();
                zipcode_1.setcode(9001);
                Zipname zipname_1 = new Zipname();
                zipname_1.setName("Harbour Cove");
                zipcode_1.getNames().add(zipname_1);
                // Can add one Zipname record with JoinTable but not JoinColumn
                Zipname zipname_2 = new Zipname();
                zipname_2.setName("Wonderland");
                zipcode_1.getNames().add(zipname_2);
                manager.persist(zipcode_1);   // line 45
    The same deployment error message below was generated from both JoinColumn and JoinTable methods:
    run-deploy:
    run-display-browser:
    run-ac:
    Copying 1 file to C:\Documents and Settings\Jack\GeographicalBean\dist
    Caught an unexpected exception!
    java.lang.NullPointerException
            at client.ZipcodeApplicationClient.main(ZipcodeApplicationClient.java:45)
            at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
            at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
            at java.lang.reflect.Method.invoke(Method.java:597)
            at com.sun.enterprise.util.Utility.invokeApplicationMain(Utility.java:266)
            at com.sun.enterprise.appclient.MainWithModuleSupport.<init>(MainWithModuleSupport.java:449)
            at com.sun.enterprise.appclient.MainWithModuleSupport.<init>(MainWithModuleSupport.java:259)
            at com.sun.enterprise.appclient.Main.main(Main.java:200)
    run-InvestmentBean-app-client:The JoinColumn method would not work for one Zipname record. On the other hand, JoinTable approach would allow us to add a single Zipname record without error out.
    Q1. Can you confirm whether TopLink JPA 1.0 (Glassfish v2r2) support OneToMany JoinColumn Unidirectional at all?
    Q2. Does TopLink JPA 1.0 (Glassfish v2r2) support OneToMany JoinTable Unidirectional? If so, what is the cause of this issue? Otherwise, please make appropriate recommendation steps to take.
    This question has been posted on http://forums.sun.com/thread.jspa?threadID=5330670&tstart=0 and http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=78&t=004489&p=1 earlier in the hope a quicker response.
    Your guidance would be very much appreciated.
    Many thanks,
    Jack

    Hi,
    Below are some more error output from the OneToMany JoinTable Unidirectional approach:
    pre-run-deploy:
    Initial deploying InvestmentBean to C:\Documents and Settings\abc\InvestmentBean\dist\gfdeploy
    Completed initial distribution of InvestmentBean
    Start registering the project's server resources
    Finished registering server resources
    moduleID=InvestmentBean
    deployment started : 0%
    deployment finished : 100%
    Deploying application in domain completed successfully
    Trying to create reference for application in target server completed successfully
    Trying to start application in target server completed successfully
    WARNING:
    JDO76614: Deployment encountered SQL Exceptions:
    JDO76609: Got SQLException executing statement "CREATE TABLE ZIPCODE (ID INTEGER NOT NULL, DIALING_CODE VARCHAR(255), TIME_ZONE VARCHAR(255), CODE INTEGER, NEAREST_AIRPORT VARCHAR(255), LONGITUDE VARCHAR(255), NEAREST_TRAIN_STATION VARCHAR(255), NEAREST_URBAN_CENTRE VARCHAR(255), HOTELS VARCHAR(255), LATITUDE VARCHAR(255), NEARBY_FEATURES VARCHAR(255), COUNCIL VARCHAR(255), LOCALITY VARCHAR(255), PRIMARY KEY (ID))": com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'zipcode' already exists
    JDO76609: Got SQLException executing statement "CREATE TABLE ZIPCODE_ZIPNAME (ZIPCODE_ID INTEGER NOT NULL, ZIPNAME_ID INTEGER NOT NULL, PRIMARY KEY (ZIPCODE_ID, ZIPNAME_ID))": com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'zipcode_zipname' already exists
    JDO76609: Got SQLException executing statement "CREATE TABLE ZIPNAME (ID INTEGER NOT NULL, NAME VARCHAR(255), PRIMARY KEY (ID))": com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Table 'zipname' already exists
    JDO76609: Got SQLException executing statement "ALTER TABLE ZIPCODE_ZIPNAME ADD CONSTRAINT FK_ZIPCODE_ZIPNAME_ZIPCODE_ID FOREIGN KEY (ZIPCODE_ID) REFERENCES ZIPCODE (ID)": java.sql.SQLException: Can't create table '.\geographicaldb\#sql-434_4.frm' (errno: 121)
    JDO76609: Got SQLException executing statement "ALTER TABLE ZIPCODE_ZIPNAME ADD CONSTRAINT FK_ZIPCODE_ZIPNAME_ZIPNAME_ID FOREIGN KEY (ZIPNAME_ID) REFERENCES ZIPNAME (ID)": java.sql.SQLException: Can't create table '.\geographicaldb\#sql-434_4.frm' (errno: 121)Enable of InvestmentBean in target server completed successfully
    Enable of application in all targets completed successfully
    All operations completed successfully
    post-run-deploy:
    run-deploy:
    run-display-browser:
    run-ac:
    Copying 1 file to C:\Documents and Settings\Jack\GeographicalBean\dist
    Caught an unexpected exception!
    java.lang.NullPointerException
    at client.ZipcodeApplicationClient.main(ZipcodeApplicationClient.java:45)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.sun.enterprise.util.Utility.invokeApplicationMain(Utility.java:266)
    at com.sun.enterprise.appclient.MainWithModuleSupport.<init>(MainWithModuleSupport.java:449)
    at com.sun.enterprise.appclient.MainWithModuleSupport.<init>(MainWithModuleSupport.java:259)
    at com.sun.enterprise.appclient.Main.main(Main.java:200)
    run-GeographicalBean-app-client:
    run:
    I would like to correct an earleir comment where I stated that this method did work when adding a single Zipname record. This is no true.
    Thanks,
    Jack

  • GenerationType.AUTO doesn't work correctly with Kodo and MySQL

    Greetings,
    I'm migrating applications from JBoss/Hibernate to WebLogic/Kodo. The following column annotation:
    @Id
    @Column(name="CUSTOMER_ID")
    @GeneratedValue(strategy = GenerationType.AUTO)
    public long getCustomerId()
    is supposed to generate auto-increment primary key in mysql. This is what happens with Hibernate. With Kodo, this seems to be equivalent with GenerationType.TABLE as a table named openjpa_sequence_table is created, containing sequence values. So what should one do in order to be able to use true auto-increment strategy with MySQL and Kodo ?
    Many thanks in advance,
    Nicolas

    Hi Nicolas,
    By setting the generation strategy to AUTO, you're essentially letting the JPA provider choose which strategy to use. It looks like Kodo is using the TABLE strategy by default and Hibernate is using the IDENTITY strategy here. You can set the strategy to IDENTITY if you want Kodo to behave similarly to Hibernate. However, it's worth pointing out that there may be a reason for Kodo not using the IDENTITY strategy by default.
    The docs at: http://edocs.bea.com/wls/docs103/kodo/full/html/ref_guide_pc_oid.html#ref_guide_pc_oid_pkgen_autoinc
    point out the following:
    "Statements inserting into tables with auto-increment / identity columns cannot be batched. After each insert, Kodo must go back to the database to retrieve the last inserted auto-increment value to set back in the persistent object. This can have a negative impact on performance. "
    - Matt

  • JPA with EclipseLink, error Entity cannot be cast to Entity, any help?

    Hello, I'm currently deploying a JPA project with EclipseLink on a MySQL db, it's been working fine, however, I'm receiving a problem of this type:
    java.lang.ClassCastException: beans.Empleado cannot be cast to beans.Empleado
    Where Empleado is my Entity, basically the problem happens here, where I store a result from a SQL select into a List and then assign the results into variables, it was working with no problems before, but now, everytime I run the code, the error shows up, and the only way to make it work at least 2 - 3 times, is restarting the Glassfish Server, here's the code:
    Query q = em.createNamedQuery("Empleado.findByIdEmpleado");
    q.setParameter("idEmpleado", 2);
    List<Empleado> listaEmpleado = q.getResultList();
    for(Empleado empleado1 : listaEmpleado){
    testString = empleado1.getTecnologia();
    But as I said, it was working fine before, so I don't think is actually a code problem, I guess the "cast" reference is happening here:
    for(Empleado empleado1 : listaEmpleado)
    The errors shows up with every function where I make this kind of casting......
    As a comment, I have a similar project at home, and I don't have these problems, this is happening on a project at work, but both project are the same, it's just I'm doing this one at work and the other at home, which is working fine, thanks in advanced, have a nice day, I just hope I was clear about this!
    Edited by: user3538005 on 08-11-2011 09:08 AM

    Hola,
    It's quite strange stuff :) Mainly the exception, beans.Empleado cannot be cast to beans.Empleado.
    I think it's because of some configuration problem, related to classloader:
    EclipseLink has it's own classloader, if your beans.Empleado is loaded by EclipseLink's classloader, and by a different one (default classloader), you will have two beans.Empleado classes in your JVM, and these classes are different, so you cannot cast them :O
    so your eclipselink's classloader has its beans.Empleado(1) class, and after executing your query you have a list with the results each of them in beans.Empleado(1).
    and your dao class, or whatever, tries to cast the beans.Empleado(1) to the default classloader's beans.Empleado(2).
    what did you change in the config when it started not to work?

  • JPA and JSF - Problem persisting object

    Hi all.
    I'm having some trouble with JPA, persisting an object to a MySQL table.
    Let's say I have a simple bean, Message:
    package my.package
    import java.io.Serializable;
    import javax.persistence.Id;
    import javax.persistence.Entity;
    import javax.persistence.Column;
    import javax.persistence.Table;
    import javax.persistence.GeneratedValue;
    import javax.persistence.GenerationType;
    @Entity
    @Table(name="messages")
    public class Message implements Serializable {
         @Id
         @GeneratedValue(strategy=GenerationType.AUTO)
         private int id;
         @Column(name="message_text")
         private String message;
         @Column(name="message_author")
         private String author;
         public String getMessage() {
              return this.message;
         public void setMessage(String message) {
              this.message = message;
         public String getAuthor() {
              return this.author;
         public void setAuthor(String author) {
              this.author = author;
    }And a controller for this Message bean:
    package my.package;
    import javax.annotation.Resource;
    import javax.persistence.Query;
    import javax.persistence.EntityManager;
    import javax.persistence.EntityManagerFactory;
    import javax.persistence.PersistenceUnit;
    import javax.transaction.UserTransaction;
    public class MessageController {
         @PersistenceUnit(unitName="em1")
         private EntityManagerFactory emf;
         @Resource
         private UserTransaction utx;
         private Message message;
         public Message getMessage() {
              return this.message;
         public void setMessage(Message message) {
              this.message = message;
         public String save() {
              EntityManager em = null;
              String returnValue = "";
              try {
                   em = this.emf.createEntityManager();
                   utx.begin();
                   em.persist(this.message);
                   utx.commit();
                   returnValue = "success";
              } catch(Exception e) {
                   e.printStackTrace();
                   returnValue = "failure";
              return returnValue;
    }Relevant code from the faces-config.xml:
    <managed-bean>
         <managed-bean-name>MessageController</managed-bean-name>
         <managed-bean-class>my.package.MessageController</managed-bean-class>
         <managed-bean-scope>request</managed-bean-scope>
         <managed-property>
              <property-name>message</property-name>
              <property-class>my.package.Message</property-class>
              <value>#{Message}</value>
         </managed-property>
    </managed-bean>
    <managed-bean>
         <managed-bean-name>Message</managed-bean-name>
         <managed-bean-class>my.package.Message</managed-bean-class>
         <managed-bean-scope>request</managed-bean-scope>
    </managed-bean>This is my simple 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 ="em1">
             <jta-data-source>jdbc/__glfish</jta-data-source>
        </persistence-unit>
    </persistence>The __glfish resource is all set up via Glassfish to point to my MySQL server, via a MySQLPool.
    Can anyone see what I'm doing wrong? The Message doesn't get added to the table in my database, and I get a NullPointerException in the method MessageController.save() on the property MessageController.message - which I have specified in the faces-config.xml. Shouldn't that be enough? What have I missed?

    Ok, I have (re-)located the problem. It's not my Message property which gets a NullPointerException - it seems like the problem is with my EntityManagerFactory instance. The PersistenceUnit don't get assigned, even though I declare it in my persistence.xml file.
    Maybe it is something wrong with my file structure?
    The .war file have this structure:
    - WEB-INF
         - classes
              - my
                   - package
                        Message.class
                        MessageController.class
         - lib
              [external jars goes here]
              - META-INF
                   persistence.xml
         faces-config.xml
         web.xml
    [*.jsp/*.xhtml goes here]Can anyone see what's wrong?

  • JPA & visual JSF problem

    Hello, everybody :),
    I'm new to Java Web Development, and I'm in big trouble, :) and I'm on the edge of despair. I'll appreciate any help.
    Here is the problem - I've been trying for hours to do something like [ this|http://www.netbeans.org/kb/60/web/web-jpa.html] tutorial example but it is not working for me!
    I've changed it a bit - I'm using MySQL, I created a few Entity classes from the database, I created controllers from them (right click -> JPA controller Classes from Entity Class). I've bounded the table (from the example) as it was said and then I tried to run the application - it started but the table was emplty and in it was written that "No items found". I 100% sure that the table in the database is not empty and there are no error messages.
    I tried to debug the application then I saw that when I go to the updateUsers() mehtod in the entity class controller and I try to get the EntityManager something crashes and I go straight to the calling SessionBean1 with NULL as a user list - can you help me?
    Something more, when I create new Web project and I create the Entity classes from the database - the one that I'm having problem with for the Persistence example, and I create JSP pages for the entity classes - (you know just right click + .....) and the CRUD application is working just fine - I don't understand what is wrong with my trial to use the Java Persistence API Within a Visual Web JSF Application?
    Thanks in advance!
    P.S. Sorry for posting this topic again - I thing is the better place to get answer.
    Edited by: GGeorgieva on Jan 1, 2009 3:40 PM

    You're right again - can you help me with finding the reason for this, I'll paste some of the server log:
    It is the database? I guess? But how could it be - I've been working with that very DB from another Web Java Application?
    So is there a RIGHT way to connect to MySQL DataBase from a JavaSE project, which we have connected to a Web Java Application?
    javax.persistence.PersistenceException: No Persistence provider for EntityManager named aPU: Provider named oracle.toplink.essentials.PersistenceProvider threw unexpected exception at create EntityManagerFactory:                     
    oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException                    
    Local Exception Stack:                     
    Exception [TOPLINK-30005] (Oracle TopLink Essentials - 2.0.1 (Build b04-fcs (04/11/2008))): oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException                    
    Exception Description: An exception was thrown while searching for persistence archives with ClassLoader: WebappClassLoader                    
    delegate: true                    
    repositories:                    
    /WEB-INF/classes/                    
    ----------> Parent Classloader:                    
    EJBClassLoader :                     
    urlSet = []                    
    doneCalled = false                     
    Parent -> java.net.URLClassLoader@f66abc                                        
    Internal Exception: javax.persistence.PersistenceException: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0.1 (Build b04-fcs (04/11/2008))): oracle.toplink.essentials.exceptions.EntityManagerSetupException                    
    Exception Description: predeploy for PersistenceUnit [aPU] failed.                    
    Internal Exception: Exception [TOPLINK-7250] (Oracle TopLink Essentials - 2.0.1 (Build b04-fcs (04/11/2008))): oracle.toplink.essentials.exceptions.ValidationException                    
    Exception Description: [class classes.Person] uses a non-entity [class classes.Phone] as target entity in the relationship attribute [private java.util.Collection classes.Person.phoneCollection].                    
    "     at oracle.toplink.essentials.exceptions.PersistenceUnitLoadingException.exceptionSearchingForPersistenceResources(PersistenceUnitLoadingException.java:143)"                    
    "     at oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider.createEntityManagerFactory(EntityManagerFactoryProvider.java:169)"                    
    "     at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:110)"                    
    Caused by: Exception [TOPLINK-28018] (Oracle TopLink Essentials - 2.0.1 (Build b04-fcs (04/11/2008))): oracle.toplink.essentials.exceptions.EntityManagerSetupException                    
    Exception Description: predeploy for PersistenceUnit [aPU] failed.                    
    Internal Exception: Exception [TOPLINK-7250] (Oracle TopLink Essentials - 2.0.1 (Build b04-fcs (04/11/2008))): oracle.toplink.essentials.exceptions.ValidationException                    
    Exception Description: [class classes.Person] uses a non-entity [class classes.Phone] as target entity in the relationship attribute [private java.util.Collection classes.Person.phoneCollection].                    
    "     at oracle.toplink.essentials.exceptions.EntityManagerSetupException.predeployFailed(EntityManagerSetupException.java:228)"                    
    "     ... 87 more"                    
    Caused by: Exception [TOPLINK-7250] (Oracle TopLink Essentials - 2.0.1 (Build b04-fcs (04/11/2008))): oracle.toplink.essentials.exceptions.ValidationException                    
    Exception Description: [class classes.Person] uses a non-entity [class classes.Phone] as target entity in the relationship attribute [private java.util.Collection classes.Person.phoneCollection].                    
    "     at oracle.toplink.essentials.exceptions.ValidationException.nonEntityTargetInRelationship(ValidationException.java:1140)"                    
    "     at oracle.toplink.essentials.internal.ejb.cmp3.metadata.MetadataValidator.throwNonEntityTargetInRelationship(MetadataValidator.java:321)"                         
    "     ... 86 more"                    
    The following providers:                    
    oracle.toplink.essentials.ejb.cmp3.EntityManagerFactoryProvider                    
    Returned null to createEntityManagerFactory.                    
    "     at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:154)"                    
    "     at javax.persistence.Persistence.createEntityManagerFactory(Persistence.java:83)"                    
    "     at cntrllrs.PersonJpaController.<init>(PersonJpaController.java:33)"

Maybe you are looking for