Java Hibernate AutoIncrement Identity set ID to start 0 mySQL - java

i have a simple class like this
public class IdClass
{
private static final long serialVersionUID = 4594459221202802623L;
private Integer id;
public IdClass(){}
public IdClass(Integer id){super();this.id = id;}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ID", unique = true, nullable = false)
public Integer getId(){return this.id;}
public void setId(Integer id){this.id = id;}
}
which have autoIncrement in MYSQL table everything was working smoothly but we need to delete all records in the table to start once again later i save the new first record into de table but the sequence use the last ID generate (+1) before the delete i was wondering if it is possible to set the ID to start from 0 or 1 again...thanks a lot..

You can do it in three ways
Directly Reset Autoincrement Value
ALTER TABLE table_name AUTO_INCREMENT=1;
Truncate Table
TRUNCATE TABLE table_name;
This will reset the auto increment on the table as well as deleting all records from that table.
Drop and Recreate
Table DROP TABLE table_name;
CREATE TABLE table_name { ... };
Source:
How To Reset MySQL Autoincrement Column

Related

PostgresQL and Hibernate Auto Generated (not PK) value

I try to autogenerate value which is not PK, when I do save in DB.
I created Entity with value:
class Entity {
// Other values
#NaturalId
#SequenceGenerator(name = "number_sequence", sequenceName =
"number_sequence")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "number_sequence")
private Long number;
}
And script for sequence:
CREATE SEQUENCE schema.number_sequence AS BIGINT
INCREMENT 1
START 1
OWNED BY table_name.number;
But when I build Entity without number and save it to DB I have an error:
org.postgresql.util.PSQLException: ERROR: null value in column "number" violates not-null
constraint
Detail: Failing row contains (e925b4fb-5147-4754-b949-08d79a6ad764, 2020-06-04
14:31:50.49584+03, null, bd765ef29c3211e98b6b019787d6f1ee,
1e100b1da97b11e98b6b511f0c71b787).
Where I wrong?
Thanks to Kayaman, and SternK. What have I done:
#NaturalId
#Generated(value = GenerationTime.INSERT)
#Column(insertable = false, updatable = false)
private Long number;
on my Entity and:
CREATE SEQUENCE number_sequence AS BIGINT
INCREMENT 1
START 1
OWNED BY table.number;
ALTER TABLE table
ALTER COLUMN number SET DEFAULT nextval('number_sequence');
In my entity. You can add schema.number_seq or schema.table if query above doesn't work

How to make db handle auto insert sequence id postgesql

I had an existed entity (TableEntity.java), the table existed in db, and also the data
Here is how the column id already delcared in TableEntity.java
#Id
#SequenceGenerator(name = "table_name_id_seq", sequenceName = "table_name_id_seq", allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "table_name_id_seq")
#Column(name = "id", nullable = false, updateable = false)
private int id;
In the database, I look at the properties of the table, for id column, the data type is int and set as Not NULL
The previous code, for inserting data to db, is only doing "repository.save()"
But now, I want to use PreparedStatement to insert data to db per batch
Here is how I create the query
String query = "INSERT INTO table_name (column1, column2) values (?, ?)";
the problem is, when the query executed, its violates null constraint for the id column. How to make the database can handle my column id? Since, when I just use repository.save() is work fine, but when I use that (could I say it a native query?) query, that exception appear. How to solve this? or any reference to solve this?
Set a default value for the column:
alter table table_name
alter column id set default nextval('table_name_id_seq');
Now if an INSERT statement does not supply a value for the id column (by not mentioning it), the next sequence value is used to populate the column.

How to create UNIQUE column with JPA?

My POJO is using JPA and when I apply unique value in the column is not working for me I tried to use the UniqueConstraint and also not working for me .
below is my code
#Entity
#Table(name = "users", uniqueConstraints={#UniqueConstraint(columnNames = {"user_id"}),#UniqueConstraint(columnNames = {"username"}),#UniqueConstraint(columnNames = {"email"})})
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="user_id",unique=true,nullable = false)
private int UserId;
#Column(name = "username" ,unique=true,nullable = false)
private String Username;
#Column(name = "email",unique=true ,nullable = false)
private String email;
#Column(name = "firstname",nullable = false)
private String firstname;
#Column(name = "lastname", nullable = false)
private String lastname;
#Column(name = "password", nullable = false)
private String password;
#Column(name = "active")
private int active;
#ManyToMany(cascade=CascadeType.ALL)
#JoinTable(name="user_role", joinColumns=#JoinColumn(name="user_id"), inverseJoinColumns=#JoinColumn(name="role_id"))
private Set<Role> roles;
below is the generated table in the database (MySQL)
| users | CREATE TABLE users (
user_id int(11) NOT NULL,
username varchar(255) NOT NULL,
active int(11) DEFAULT NULL,
email varchar(255) NOT NULL,
firstname varchar(255) NOT NULL,
lastname varchar(255) NOT NULL,
password varchar(255) NOT NULL,
PRIMARY KEY (user_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 |
Hibernate log after spring start
Hibernate: create table users (user_id integer not null, username varchar(255) not null, active integer, email varchar(255) not null, firstname varchar(255) not null, lastname varchar(255) not null, password varchar(255) not null, primary key (user_id)) engine=InnoDB
Hibernate: alter table users drop index UKfnranlqhubvw04boopn028e6
Hibernate: alter table users add constraint UKfnranlqhubvw04boopn028e6 unique (username, email)
Hibernate: alter table users drop index UK_r43af9ap4edm43mmtq01oddj6
Hibernate: alter table users add constraint UK_r43af9ap4edm43mmtq01oddj6 unique (username)
Hibernate: alter table users drop index UK_6dotkott2kjsp8vw4d0m25fb7
Try like this:
#Entity
#Table(name="users",uniqueConstraints=#UniqueConstraint(columnNames={"user_id","username","email"}))
public class Users {
Apparently there's nothing wrong with this code. unique=true in #Column is a shortcut for #UniqueConstraint(columnNames = {"user_id"} and other particular constraints. You could only use one of them except for multiple unique constraints.
But if you are confused why the generated CREATE TABLE doesn't contain these unique constraints, check the log, you can find alter table commands just after CREATE TABLE.
In this case commands could be,
alter table users add constraint UK_some_id unique (username)
alter table users add constraint UK_some_id unique (email)
Hope this help.
I had the same problem here, set length to your unique columns.. It worked here. Do
#Column(name = "userName", length = 50, unique = true)
if you set unique in #Column
that's mean let your JPA provider create the database for you - it will create the unique constraint on the specified column.
But after creating a database, or you alter it once created,
then unique doesn't have any effect
in jpa the id is already unique so to make username and email unique add the statement
unique=true
to the corresponding #Column annotation.
PS : remember the unique cannot be null when insert new item you should drop the table before run the application and remove uniqueConstraints in table annotation
Set the column to have the fixed length make it work because mysql size for unique constrains limited to 1000 bytes
#Column(name = "username", length = 200, unique = true)
Use #javax.persistence.Column(unique = true).
Dont forget to restart your application.
&& you cant alter your column if there are still duplicated values in it.
drop your table, and recreate it with your generated ddl. (if ure not usin springboot)
&& if youre using springboot, go to your application.properties & set spring.jpa.hibernate.ddl-auto to update
This updates the schema if necessary.
The column needs to be non nullable for it to be unique!
#Column(unique = true) will NOT work
#Column(unique = true, nullable = false) will work
If the database or schema already exists before adding the uniqueConstraints then it won't work.
So drop the database or schema and run the application to create new database with these uniqueConstraints
DROP DATABASE database_name;

Spring JPA hibernate postgresql partion and timestamp without timezone

After searching a lot, I have a trouble to save timestamp data in PostgreSQL base using Spring JPA Hibernate.
Here my main table in PostgreSQL, it's a partitionning table :
CREATE TABLE public.archive_traffic_measure
(
measure_point_id integer NOT NULL,
measure_agregation_id integer NOT NULL,
measure_datetime timestamp without time zone NOT NULL,
measure_type_id integer NOT NULL,
any_flow integer,
f_any_flow smallint,
hgv_flow integer,
f_hgv_flow smallint,
occupation_rate smallint,
f_occupation_rate smallint,
average_speed smallint,
f_average_speed smallint,
CONSTRAINT pk_archive_traffic_measure PRIMARY KEY (measure_point_id, measure_agregation_id, measure_datetime, measure_type_id)
)
Here my main entity with spring JPA hibernate with #SQLInsert to suppress the check and don't have the problem with hibernate that no row is insert (because the row is insert in a child table) :
#Entity
#Table(name = "archive_traffic_measure")
#SQLInsert(sql = "INSERT INTO archive_traffic_measure (measure_point_id," +
"measure_agregation_id," +
"measure_datetime," +
"measure_type_id," +
"any_flow," +
"f_any_flow," +
"hgv_flow," +
"f_hgv_flow," +
"occupation_rate," +
"f_occupation_rate," +
"average_speed," +
"f_average_speed) VALUES (?,?,?,?,?,?,?,?,?,?,?,?)", check = ResultCheckStyle.NONE)
public class ArchiveTrafficMeasure implements Serializable {
#EmbeddedId
private ArchiveTrafficMeasureId id;
#Column(name = "any_flow")
private Integer anyFlow;
#Column(name = "f_any_flow")
private Integer F_AnyFlow;
#Column(name = "hgv_flow")
private Integer hgvFlow;
#Column(name = "f_hgv_flow")
private Integer F_hgvFlow;
#Column(name = "occupation_rate")
private Integer occupationRate;
#Column(name = "f_occupation_rate")
private Integer F_occupationRate;
#Column(name = "average_speed")
private Integer averageSpeed;
#Column(name = "f_average_speed")
private Integer F_averageSpeed;
}
And my id's entity with Spring JPA hibernate :
#Embeddable
#Table(name = "archive_traffic_measure")
public class ArchiveTrafficMeasureId implements Serializable {
#Column(name = "measure_point_id")
private int measurePointId;
#Column(name = "measure_agregation_id")
private int measureAgregationId;
#Column(name = "measure_datetime", columnDefinition = "timestamp without time zone")
#Temporal(TemporalType.TIMESTAMP)
private Date measureDateTime;
#Column(name = "measure_type_id")
private int measureType;
}
When I try to insert new data I have this error :
ERROR: column "measure_datetime" is of type timestamp without time zone but
expression is of type integer
The problem is the request be like :
INSERT INTO archive_traffic_measure VALUES (1,2,2018-04-18 17:00:00+01,1,40,null,null,null,null,null,null,null)
So the quote arount the timestamp is missing...
I have try to put the quote in the #SQLInsert "(?,?,'?',?,?,?,?,?,?,?,?,?)" but with that, I have the error :
The column's index is out of bound : 12, number of column : 11.
I have also try "(?,?,''?'',?,?,?,?,?,?,?,?,?)" with double quote
Or "(?,?,?::timestamp,?,?,?,?,?,?,?,?,?)" but nothing is working for far.
Can someone help me ? Thanks in advance.
First, add nullable = false for 'measure_datetime' column definition also remove composite key from #SQLInsert:
#SQLInsert(sql = "INSERT INTO archive_traffic_measure ("any_flow," +
"f_any_flow," +
"hgv_flow," +
"f_hgv_flow," +
"occupation_rate," +
"f_occupation_rate," +
"average_speed," +
"f_average_speed) VALUES (?,?,?,?,?,?,?,?,?)", check = ResultCheckStyle.NONE)
Then, when you persist ArchiveTrafficMeasure, you should set PK as ArchiveTrafficMeasureId and persist it.

JPA Error : Primary Key was detected to be NULL

I have a problem with JPA querying a MySQL table that has a column of type geometry. It contains polygons having sets of latitude and longitude as the coordinates. While executing the nativequery to select from the table, I am getting the following error
Exception Description: The primary key read from the row [ArrayRecord(
=> POLYGON((102.642944444444 2.9757087270706,102.642944444444 2.79805447470818,....
=> 16.0
=> 325990)] during the execution of the query was detected to be null. Primary keys must not contain null.
However the table has no row with primary key as null. This specific row has a very large polygon with 66 coordinates. Not sure if the problem is because of this.
Following are the table column names and types
geomarea - geometry
riskvalue - double
id - int (Autoincrement, Primary Key)
Following is the code in my EJB to read the table.
Query query = em.createNativeQuery("select astext(geomarea) geomarea,riskvalue,id from earthquakeRisk where Contains(geomarea,GeomFromText('POINT(" + node.getLongitude() + " "+node.getLatitude()+")'))",Earthquakerisk.class);
geomList.addAll(query.getResultList());
And here is how the fields are declared in the entity class
public class Earthquakerisk implements Serializable {
private static final long serialVersionUID = 1L;
#Basic(optional = false)
#NotNull
#Lob
#Column(name = "geomArea")
private byte[] geomArea;
#Column(name = "riskvalue")
private Double riskvalue;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
Any idea how to solve this?
I found a solution to the problem. Adding it here in case someone finds it useful.
Solved it by removing the Earthquakerisk.class from the query, and changing my List to List. So the working code is now as follows.
List<Object[]> geomList = new ArrayList<>();
Query query = em.createNativeQuery("select astext(geomarea) geomarea,riskvalue,id from earthquakeRisk where Contains(geomarea,GeomFromText('POINT(" + node.getLongitude() + " "+node.getLatitude()+")'))");
geomList.addAll(query.getResultList());

Categories

Resources