Hibernate Auto Increment in SQLite - java

I just started learning hibernate and its looking good. I am just stuck with creating a column in a table with auto increment property. Here is how I defined my column in my class:
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column (name="program_id")
protected Integer programid;
The problem here is when the sql query is created it returns an error because the query is incorrect for SQLite. Here is the generated query:
create table program (program_id integer not null auto_increment....)
You see it is written as auto_increment instead of AUTOINCREMENT (ignore case) I already tried Identity and still returns an incorrect sql query.
Is there a correct "strategy" in the annotation to approach this? or is there another setup to have the correct sql query?

Try it
#Id
#Column(name = "program_id")
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Basic
protected Integer programid;

Related

EclipseLink #GeneratedValue(strategy = GenerationType.AUTO creates already exist id

I am developping a java application with postgresql database, I made a manual insert into a table, and now when i try to insert from the application I get the following error:
Detail: Key (id)=(1092770) already exists
I am using eclipseLink as JPA framework and the Id generation strategy is the following:
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="ID")
protected long id = 0L;
Clearly the eclipseLink is not considering the max(Id) in the table, and creates an Id less than the current max(Id).
Is there a way to fix this please
Thanks

Can i use UUID as datatype for id field in model/pojo class using hibernate search

I am trying to implement search functionality using hibernate search for my project which is in spring boot .
I used hibernate search annotations like #Indexed, #Field.
When i use datatype of id Field as Long then search is performed and list of results is returned but in my project UUID is used as datatype for id field which is also primary key .in the case of UUID the result is an empty list.
#Id
#GeneratedValue
private UUID id;
How can i perform search operation using UUID as datatype for id field?
Please use the following code
#Id
#Type(type = "uuid-char") // add column type
#GeneratedValue
#Column(name = "id")
You need to add #Type for the ID column if your using uuid as your data type
I hope it helps you
Thanks
Yes, you can use UUID as a document ID, and it should work out of the box.
If you're not getting any result:
Check you're using a recent version of Hibernate Search (5.11+) and Hibernate ORM (5.4+).
Check that you reindexed your data after changing the type of your ID.
When reindexing, check your logs for indexing failures and report them here.
Test with a very simple query, for example qb.all().createQuery(). If you get results with that query, the problem is with your initial query, not with your identifier.
You can apply #sridhar-karuppusamy's suggestion, but that should only be necessary if you want the database type to be VARCHAR instead of VARBINARY. And that is irrelevant to Hibernate Search.

Problems with #GeneratedValue in the H2 database

Hello StackOverflow Community, I have a problem with the annotation #GenerateValue. I want that JPA generates the values for my ID column. But I have another column where people can write some sort of tasks (todo list).
My code seems like this:
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
and I have a SQL data file that write some data at the beginning in my h2 database:
INSERT INTO task VALUES(1, 'go to the gym');
INSERT INTO task VALUES(2, 'eat with tom');
INSERT INTO task VALUES(3, 'meetup');
INSERT INTO task VALUES(4, 'doing some homeworks');
INSERT INTO task VALUES(5, 'doing some exercise');
INSERT INTO task VALUES(6, 'studying with Mat');
my problem is, when I delete the integer values on my SQL data file, my compiler says always that I have to declare an id for the tasks, but I thought the #GenerateValue automatically generate the id's for me?
You have to use #GeneratedValue(strategy = GenerationType.IDENTITY) or #GeneratedValue(strategy = GenerationType.SEQUENCE) and make sure that you have index or sequence on database level. Also when using auto-generated ids, don't specify them explicitly when inserting.
Correct:
INSERT INTO task(description) VALUES('go to the gym');
but I thought the "#GenerateValue" automatically generate the id's for me?
It's a not the correct assumption, Hibernate just uses ids provided by db. To get it to work you need to create index/sequence for your primary key column.
You're mixing up sql and hibernate. #GeneratedValue is declared in your java code, so that hibernate knows, that when you're persisting an entity without an id, it should be generated by given strategy.
On the other hand you tried to make insertions using sql without passing primary key, so you're explicitly said, that it should be NULL, which is clearly against the constraint.

Hibernate renames some columns at start with Spring Boot 1.4

I'm having some problems with my PostgreSQL database columns on some tables.
If I declare a column of String with a name like a_column_name Hibernate accepts the column of the table with the name a_column_name.
But my problem comes when I declare the column type to Integer or BigDecimal. At start, Hibernate creates a new column of type int4 or numeric(19, 2) with a name like acolumnname with NULL's.
Hibernate: alter table t_myTable add column acolumnname int4
or
Hibernate: alter table t_myTable add column acolumnname numeric(19, 2)
I've tried to set the name-strategy on the config file of Spring boot:
jpa:
show-sql: true
hibernate:
ddl-auto: update
properties:
hibernate.cache.use_second_level_cache: false
hibernate.cache.use_query_cache: false
hibernate.generate_statistics: true
naming.physical-strategy: PhysicalNamingStrategyStandardImpl
But with no result...
So my question is why Hibernate accepts the column name when it's of String type but doesn't like it when it's Integer or BigDecimal.
Regards.
---- Update 1 ----
After search the Entity to post here the code as Veselin Davidov asked, I've noticed that some columns are accepted while others not.
The entities are created from a company framework that parses a JSON with the DB structure (tables, fields, type of fields...) and generates the JAVA entity class. So after see the answer from SAM I've changed the code of the Entity template to add a #Column(name = "your_column_name"). Now, when Hibernate starts, it doesn't add the columns with the wrong names and uses the DB columns.
if your Hibernate entity class is like the following:
#Entity
public class Registration{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Column
#Basic
private String name;
// getters and setters
}
then your registration table will have fields named with "id" and "name" as you have used auto-ddl=update. To avoid that you can specify the column names with #Column(name = "your_column_name") like below:
#Table(name = "registration")
#Entity
public class Registration{
#Id
#Column(name = "r_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Basic
#Column(name = "r_name")
private String name;
// getters and setters
}
If you are using Intellij IDEA then the IDE can generate the required Entity class.
You can go to your persistence tab -> right-click on your project name -> Generate Persistence Mapping -> By Database Schema. Then select the tables whose Entity you want to generate. Voila everything comes with ease.
Now coming to your problem, in your Entity class if you set some filed with Integer type then it will update your table to int4 and with allow null. The BigDecimal is also same numeric(10,2) with allow null. To avoid allow null in your database use primitive type int and double.

GeneratedValue in Postgres

I have my entity class mapped like below:
#Entity
#Audited
#Table(name="messages_locale")
public class Locale {
#Id
#GeneratedValue
#Getter #Setter //Project Lombok's annotations, equal to generated getter and setter method
private int id;
(...)
I create clean new database ,and properties:
< prop key="hibernate.hbm2ddl.auto" >create < /prop>
WHY THE HELL (Sorry, almost two days wasted on this bug) after created database, i got a sequence in my postgres db?:
CREATE SEQUENCE hibernate_sequence
INCREMENT 1
MINVALUE 1
MAXVALUE 9223372036854775807
START 2
CACHE 1;
ALTER TABLE hibernate_sequence
OWNER TO postgres;
I dont want to have a sequence, I want to have just auto increment auto generated values..
I think the accepted answer from Petar is not correct, or not correct any longer. The auto-increment in Postgres is handled through SERIAL pseudo type, that’s correct. However, the mapping that Petar gives will result in the following DDL generated by Hibernate 5.1:
CREATE SEQUENCE users_id_seq START 1 INCREMENT 50;
CREATE TABLE … (
id INT8 NOT NULL,
…
);
This is not using SERIAL, but a Hibernate managed sequence. It is not owned by the table and no default value has been set. Of course, DDL generation is a feature that many people do not use in production (but many take the generated code as a template).
If you hand-write your DDL and actually used SERIAL, then using GenerationType.SEQUENCE may even conflict with the database behaviour. The correct way to map Hibernate with Postgres’ preferred ID strategy is using GenerationType.IDENTITY. Incidentally, the code is also much shorter and more readable:
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
Long id;
In PostgreSQL auto-increment is handled using the SERIAL pseudo type. You use this type when you execute CREATE TABLE.
Now to the point - this SERIAL pseudo type creates a sequence.
Autoincrement in PostgreSQL is handled using the created sequence. The default value of the id column becomes - nextval('your_sequence_name').
In Hibernate for an User entity:
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "users_seq_gen")
#SequenceGenerator(name = "users_seq_gen", sequenceName = "users_id_seq")
public Long getId() {
return id;
}
Read here:
http://www.postgresql.org/docs/8.4/static/datatype-numeric.html#DATATYPE-SERIAL
http://www.neilconway.org/docs/sequences/

Categories