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.