Java – why doesn’t JPA automatically generate an ID for my row?
I want to use the sequence policy to automatically generate IDS, but I'm breaking my mind to make it work I have no idea why I can't let it happen
That's what I did First, I have an entity:
@Entity @SequenceGenerator(name="VlasnikSeq",sequenceName="VLA_SEQ") public class Vlasnik implements Serializable { @Id @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="VlasnikSeq") private Long id; //...
In persistence I have its mapping in XML:
<?xml version="1.0" encoding="UTF-8"?> <persistence version="2.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_2_0.xsd"> <persistence-unit name="sampleAplication"> <class>entities.Vlasnik</class> <class>entities.Ljubimac</class> </persistence-unit> </persistence>
When I use the eclipse function to generate tables for entities, I get this:
As you can see, the table has been created, but there is no sequence table I also noticed the following message in the console, and JPA is creating the table:
I think the next step is to try running the application and see if I can create some rows But when I try to stick to something, I get an exception and say:
Therefore, I conclude that for some reason, I need this table, so from the perspective of database management, I try to execute the following query:
CREATE SEQUENCE VLA_SEQ;
But I received the following message:
I'm completely confused I don't know what to do. I just want to automatically generate the entity ID when creating a new row in dB
This is the first time I use GlassFish 3.1. I don't remember in version 3.0. I can even use @ generatedvalue I appreciate some help
Solution
To use generatedvalue, you must specify a policy and generator By default, the policy is auto and the generator is empty
Available policies are defined by generationtype:
public enum GenerationType { TABLE,SEQUENCE,IDENTITY,AUTO };
The most common method is to specify sequence or identity
>For databases using sequence (such as Oracle and HSQLDB), you must also use the sequencegenerator annotation:
Public class MyClass{
@Id @GeneratedValue(strategy=GenerationType.SEQUENCE,generator="SEQMYCLASSID") @SequenceGenerator(name="SEQMYCLASSID",sequenceName="SEQMYCLASSID") private Long id;
}
If you have automatic DDL enable, you do not need to create a sequence because the JPA provider will do this for you If not, you must do it manually like this:
CREATE SEQUENCE SEQMYCLASSID;
>For databases that do not use queues and use identity columns such as Microsoft SQL server, you need to specify identity as the policy:
Public class MyClass{
@Id @GeneratedValue(strategy=GenerationType.IDENTITY) private Long id;
}