0

Hi,

I have a MySQL database I want to access with the Java Persistence API.
The database I use consists of two tables (supplier and product) and is created with a SQL-script I made. Furthermore I generated the database classes (Suppliers and Product) with Netbeans using the "Entity Classes from Database" option.

My problem/question is: I create a new instace of eg. Supplier ( Supplier s = new Supplier() ). I don't need (and want) to specify an id because it is an AUTO_INCREMENT field (see sql-script). When I persist the object s ( em.persist(s) ), the id field doesn't get updated although it does get a value in the database. Even after a commit ( em.commit() ) it doesn't change. Why does this happen and how can I solve this?

MySQL SQL-script:

CREATE TABLE supplier (
    id	    	SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
    name	VARCHAR(30) NOT NULL,

    PRIMARY KEY (id)
) ENGINE = innodb;

CREATE TABLE product (
    id		    SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
    name            VARCHAR(50) NOT NULL,
    supplier_id     SMALLINT UNSIGNED,
    
    PRIMARY KEY (id),
    FOREIGN KEY (supplier_id) REFERENCES supplier (id)
) ENGINE = innodb;

I have a persistence unit called "testPU" which is defined in persistence.xml. Furthermore my db package contains the two database entity classes Supplier and Product. The following is my main class "Test.java".

package main;

import db.*;
import javax.persistence.*;

public class Test {
	public static void main(String[] args) {
		try {
			EntityManagerFactory emf = Persistence.createEntityManagerFactory("testPU");
			EntityManager em = emf.createEntityManager();

			em.getTransaction().begin();

			Supplier s = new Supplier();
			s.setName("supplier");
			em.persist(s);
			em.getTransaction().commit();

			System.out.println("" + s.getId()); 
			/* s.getId() always returns NULL
			 * Why doesn't the id get updated?
			 * How can I solve this?
			 */
			em.close();
			emf.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}

I hope I stated my problem clearly. If not or more code is needed, please ask me ;-).

Thanks for reading and maybe helping me.
Greetz.

2
Contributors
1
Reply
2
Views
8 Years
Discussion Span
Last Post by danielsousa
0

Hey man,

So I had the same problem and I finally figured it out. Netbeans doesn't generate the id generation strategy for you in this case. To fix the problem while using auto increment, add the following code to each of your classes:

@GeneratedValue(strategy=GenerationType.IDENTITY)

basically tells the JPA to get whatever the table key is (AI since you told it that in the db schema)

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.