How to make db handle auto insert sequence id postgesql - java

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.

Related

Spring Data entity column property is always null when reading from the database

On an existing DB table I've added a column and in the JPA entity I've added a property as well.
I've initialized the new db column with default values.
ALTER TABLE MYTABLE ADD NEW_COLUMN VARCHAR2(4000 CHAR);
UPDATE MYTABLE SET NEW_COLUMN = 'AAA';
#Column(name = "NEW_COLUMN", nullable = false)
private String newColumn;
#Query(value = "select * from mytable ", nativeQuery = true)
The query returns all the rows in the table, but the field newColumn is always null, the other fields are populated correctly.
When I do the same query on the command line, the values for the column are there.
What could be the reason that JPA returns null values for that new column?
I found the reason why JPA return null for that new column.
In SQL developer, I initialized the new DB column with value "AAA", but I didn't commit after the SQL finished the update. After I did a commit in SQL Developer, the JPA query returned the value "AAA"

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

Hibernate : Unknown column in field list

I'am trying to do an unidirectional #OneTaMany relationship like in the Hibernate User Guide (2.7.2) but when I try to save the following object in a MariaDB Database:
Filter filter = new Filter("TLS_A320");
filter.addConstraint(new Constraint(ConstraintType.DEPARTURE, "TLS"));
filter.addConstraint(new Constraint(ConstraintType.AIRCRAFT, "A320"));
session.save(filter);
I got this exception :
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'Filter_idFilter' in 'field list'
Here are the 2 classes:
Filter.java
public class Filter {
#Id
#Column(name = "idFilter")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "name")
private String name;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<Constraint> constraintList;
//more code
};
Constraint.java
public class Constraint {
#Id
#Column(name = "idConstraint")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "type")
#Enumerated(EnumType.ORDINAL)
private ConstraintType constraintType;
#Column(name = "value")
private String value;
//more code
}
And here is the tables definition :
CREATE TABLE `Constraint` (
idConstraint INT NOT NULL AUTO_INCREMENT,
type INT NOT NULL,
value VARCHAR(10) NOT NULL,
PRIMARY KEY (idConstraint)
);
CREATE TABLE Filter (
idFilter INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50) UNIQUE NOT NULL,
PRIMARY KEY (idFilter)
);
CREATE TABLE Filter_Constraint (
idFilter INT UNIQUE NOT NULL,
idConstraint INT NOT NULL,
CONSTRAINT fk_Filter_Constraint_Filter FOREIGN KEY (idFilter) REFERENCES Filter(idFilter),
CONSTRAINT fk_Filter_Constraint_Constraint FOREIGN KEY (idConstraint) REFERENCES `Constraint`(idConstraint)
);
It seems to me that that Filter and Constraint insertions are fine and the exception happens when inserting in the Filter_Constraint table :
DEBUG org.hibernate.SQL - insert into Filter (name) values (?)
DEBUG org.hibernate.id.IdentifierGeneratorHelper - Natively generated identity: 4
DEBUG org.hibernate.SQL - insert into `Constraint` (type, value) values (?, ?)
DEBUG org.hibernate.id.IdentifierGeneratorHelper - Natively generated identity: 5
DEBUG org.hibernate.SQL - insert into `Constraint` (type, value) values (?, ?)
DEBUG org.hibernate.id.IdentifierGeneratorHelper - Natively generated identity: 6
DEBUG org.hibernate.SQL - insert into `Filter_Constraint` (Filter_idFilter, `constraintList_idConstraint`) values (?, ?)
DEBUG org.hibernate.engine.jdbc.spi.SqlExceptionHelper - could not execute statement [n/a]
DEBUG com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'Filter_idFilter' in 'field list'
I'am pretty new to Hibernate and I just can't figure out what I did wrong.
You didn't define any join column or inverse join column on constraintList, hence Hibernate will autogenerate column names which most probably results in the name Filter_idFilter.
The entity name will be part of the name since Constraints could have an id field with the same name, i.e. idFilter. Of course you know that isn't the case but Hibernate doesn't (or at least the column name generation code isn't that complex) and hence it has to assume that could be the case.
The same is true for join table names so you'll probably want to use #JoinTable along with the definition of join columns and inverse join columns on constraintList. However, since the relation is OneToMany anyways, why don't you add a back reference to Constraint, add the filter's id to table Constraint and get rid of the join table entirely?

Java Hibernate AutoIncrement Identity set ID to start 0 mySQL

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

hibernate and oracle sequence GenericGenerator creates gap

I've mapped my class as follow (omitted other fields as only ID matters):
#Entity
#Table(name = "MODEL_GROUP")
#Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
public class SettlementModelGroup implements Serializable
{
#Id
#GeneratedValue(generator = "MODEL_GROUP_SEQ", strategy = GenerationType.SEQUENCE)
#GenericGenerator(name = "MODEL_GROUP_SEQ",
strategy = "sequence",
parameters = #Parameter(name = "sequence", value = "SEQ_MODEL_GROUP_MODEL_GROUP_ID"))
#Column(name = "MODEL_GROUP_ID", nullable = false)
private Integer modelId;
}
when I'm saving new object:
Integer modelGroupId = sessionFactory.getCurrentSession().save( modelGroup );
System.out.println( modelGroupId );
ID is set as for example 23, but when I look at the database it is actually 24. This is leading to many problems, as I'm using this ID later on. Any idea why it is making this gap?
SQL logs show that everything is fine (I thinks so):
Hibernate:
select
SEQ_MODEL_GROUP_MODEL_GROUP_ID.nextval
from
dual
Hibernate:
insert
into
MODEL_GROUP
(DOMAIN_ID, DESCRIPTION, NAME, PERIOD_TYPE_ID, MODEL_GROUP_TYPE_ID, STATUS_ID, OWNER_ID, MODEL_GROUP_ID)
values
(?, ?, ?, ?, ?, ?, ?, ?)
Trigger and Sequence:
CREATE SEQUENCE "SEQ_MODEL_GROUP_MODEL_GROUP_ID"
INCREMENT BY 1
START WITH 1
NOMAXVALUE
MINVALUE 1
NOCYCLE
NOCACHE
NOORDER
;
CREATE OR REPLACE TRIGGER "TRG_MODEL_GROUP_MODEL_GROUP_ID"
BEFORE INSERT
ON "MODEL_GROUP"
FOR EACH ROW
WHEN (NEW."MODEL_GROUP_ID" is NULL)
BEGIN
SELECT "SEQ_MODEL_GROUP_MODEL_GROUP_ID".NEXTVAL
INTO :NEW."MODEL_GROUP_ID"
FROM DUAL;
END;
Apparently, when Hibernate ask your database for nextValue of ID, it fires also Trigger. So when I ask for ID, I've got number 23 but when actually saving to database by commiting transaction, it is increased again so I've got 24. Solution is described here:
HIbernate issue with Oracle Trigger for generating id from a sequence
To make it work correctly, I changed Trigger:
CREATE OR REPLACE TRIGGER "TRG_MODEL_GROUP_MODEL_GROUP_ID"
BEFORE INSERT
ON "MODEL_GROUP"
FOR EACH ROW
WHEN (NEW."MODEL_GROUP_ID" is NULL)
BEGIN
SELECT "SEQ_MODEL_GROUP_MODEL_GROUP_ID".NEXTVAL
INTO :NEW."MODEL_GROUP_ID"
FROM DUAL;
END;

Categories

Resources