I'm using Hibernate to create SQLite tables.
I have a table as such
#Entity
class Person(
#Column(unique = true, nullable = false)
val name: String,
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
val id: Int? = null,
)
I see that when the database is created, the unique constraint is added later on via an ALTER request
Hibernate: create table Person (id integer, name varchar(255) not null, primary key (id))
Hibernate: alter table Person add constraint UK_is4vd0f6kw9sw4dxyie5cy9fa unique (name)
Except that SQLite does not seem to support ALTER requests modifying constraints on tables.
So my question is : Is there a way to literally indicate Hibernate to set that uniqueness constraint on table creation? What would be the best way to do it?
I can ensure uniqueness easily later on via code, but I'd rather use the power of the database if I can.
I should add that this is for a personal small application so so far I'm using the update setting for hibernate.hbm2ddl.auto so Hibernate generates the SQL itself. I'm open to other methods but I'd rather avoid them if I can to reduce maintenance.
Gonna answer my own question given that it's not getting much traction :).
SQLite indeed does not support ALTER with constraints, and Hibernate does not (to my knowledge) offer a clean way to use custom SQL.
On top of this, it is not recommended to use Hibernate: hbm2ddl.auto=update in production.
For those reasons, I decided to turn myself to Flyway and write my own SQL. The good news is that adding Flyway provides my database migrations. The bad news is that it's one more dependency to maintain.
What I've done:
Added the flyway dependency in my build.gradle.kts
implementation("org.flywaydb:flyway-core:8.4.3")
Instantiated flyway before hibernate in my code, pointing to the same database:
val flyway = Flyway
.configure()
.dataSource("jdbc:sqlite:test.db", null, null).load()
flyway.migrate()
Added a handwritten SQL migration file in resources/V1__Create_person_and_entries_table.sql
create table Person
(
id integer primary key,
name varchar(255) not null UNIQUE
);
Et voilà!
I wrote a blog post over here with more details and some more reasons to use something like Flyway.
Related
I have PostgreSQL database with multiple schema and I'm using Apache Cayenne to generate Java classes. Problem is that cayenne skips foreign keys on tables in different schema. Example:
Table schema_b.booking that references schema_a.my_user:
create table schema_b.booking
(
id bigserial not null constraint booking_pkey primary key,
address_id integer not null constraint cde_fk references schema_b.address
...,
created_by integer not null constraint abc_fk references schema_a.my_user
);
Generated Java class looks like:
class Booking {
private Long id;
private Address addressId; //this is OK
private Integer createdBy; //NOT OK (Integer instead of MyUser)
}
Console log shows this entry for every FK in different schema:
[INFO] Skip relation: 'null.schema_a.my_user.id <- null.schema_b.booking.created_by # 1' because it related to objects from other catalog/schema
[INFO] relation primary key: 'null.schema_a'
[INFO] primary key entity: 'null.schema_a'
[INFO] relation foreign key: 'null.schema_b'
[INFO] foreign key entity: 'null.schema_b'
The problem is that Booking#createdBy is not MyUser.
I've searched on SO and official documentation, but without success. Is there any way to achieve this? I know that another option is to move all tables into single schema, but that is almost unfeasible for our project.
You are correct, Cayenne just skips cross-schema relationships.
This looks like an obsolete limitation that should be dropped.
If you are doing this only once, you can just add these missing relationships in Cayenne Modeler. If you need to synchronize Cayenne model with your DB periodically, then it's can be harder to overcome.
One option is to skip relationship loading altogether (see docs), and create them manually (or with "Infer relationships" tool in Modeler). In this case all other content (tables and columns) should synchronize just fine. Another option is to wait for 4.1.M2 version of Cayenne that I believe will be ready soon (no exact dates though)
In my spring project, the tables in database are created automatically by Hibernate using my entity classes as base, but I insert some default values in the table manually (using pgAdmin3).
Because that, I am facing now this problem: when I try insert a value via Java code in one of the tables which already have values, I receive a error message, saying the primary key already exists in the database.
Anyone knows how to solve this problem?
UPDATE
That's how I declare my primary key in my class:
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
Call this SQL query once per table to set the sequence to the next free number:
SELECT setval('tblname_id_seq', max(id)) FROM tblname;
tblname being the actual name of the table.
Hibernate may use a different naming convention, or the sequence may have been renamed. If you can't find the sequence behind the serial column, check with (per documentation):
SELECT pg_get_serial_sequence(tblname, column_name)
More details:
Modify Django AutoField start value
How to import a CSV to postgresql that already has ID's assigned?
The problem here might be that you declare the id as a primitive instead of a wrapper.
So instead of:
private int id;
You should have:
private Integer id;
When you create the entity with the id is initialized as 0, instead of NULL.
That's why you get duplicate id constraint violation exceptions.
Only when the id is NULL the AUTO generation strategy will delegate the id assignment to the database.
I am having a problem that hibernate tries to drop foreign keys that dont exist instead of the one that exists. My scenario looks like this.
I want to run a junit tests, before ever test I want to create DB and after ever test I want to drop it. For that I use hibernate create-drop property. However the tricky part is that I want to create my own tables as a way to test newly added sql and verify that it will run fine once I deploy it to the production db server. So what happens is this
Hibernate creates tables automatically
Hibernate creates foreign key relationships
Hibernate runs my drop table scripts (that succeeded since there is no data so no foreign key rule has been broken)
Hibernate runs my create table scripts
Hibernate runs my add foreign constraint scripts
Hibernate runs my insert data scripts
Test is executed
Hibernate tries to remove the foreign key and it fails.
The reason hibernate has not be able to remove it is cause it tried to remove that one that hibernate created and not the one that was created by my scripts.
Any idea how to force hibernate to find out the actual foreign key? Any way to get around this problem?
Thanks everyone
Class for which hibernate creates the table
TodoGroup.java
#Entity
#Table(name = "ToDoGroups")
public class ToDoGroup implements Serializable{
#Id
#GeneratedValue
private Long id;
#Column(name = "Name", length = 50)
private String name;
#ManyToOne
#JoinColumn(name = "UserSettingsId")
#XmlTransient
private UserSettings userSettings;
#OneToMany(mappedBy = "group", cascade = CascadeType.ALL)
private List<ToDoItem> items;
hibernate adding the constraint
alter table ToDoGroups
add constraint FK790BA1FAFE315596
foreign key (UserSettingsId)
references UserSettings
running my own tables that work fine since there is no data so I can remove what hibernate created in order to verify my sql
DROP TABLE IF EXISTS ToDoGroups;
CREATE TABLE ToDoGroups (ID BIGINT NOT NULL IDENTITY, Name VARCHAR(50) NOT NULL, UserSettingsId BIGINT NOT NULL, PRIMARY KEY (ID));
ALTER TABLE ToDoGroups ADD FOREIGN KEY (UserSettingsID) REFERENCES UserSettings (ID);
drop fk it tries to execute
alter table ToDoGroups drop constraint FK790BA1FAFE315596
java.sql.SQLException: Constraint not found FK790BA1FAFE315596 in table: TODOGROUPS in statement [alter table ToDoGroups drop constraint FK790BA1FAFE315596]
tries to remove the table which fails due to the constrain that I have set in my create.sql script
drop table ToDoGroups if exists
java.sql.SQLException: Table is referenced by a constraint in table SYS_REF_SYS_FK_808_810 table: TODOITEMS in statement [drop table ToDoGroups if exists]
Update
I have also noticed that hibernate when it first starts before it creates the tables (so this is way before my scripts are run), tries to remove foreign key in order to drop any table that exists.
So how does hibernate know what foreign key to use? It uses the same key that
first statement it executes
alter table ToDoGroups drop constraint FK790BA1FAFE315596
then it drops all of the tables
drop table ToDoGroups if exists
then it creates table
create table ToDoGroups (
id bigint generated by default as identity (start with 1),
Name varchar(50),
UserSettingsId bigint,
primary key (id)
)
then it adds the same FK
alter table ToDoGroups
add constraint FK790BA1FAFE315596
foreign key (UserSettingsId)
references UserSettings
I think my question here is how does hibernate know what FK to use. It used the same FK in the first drop statement when there was even no table. Later it used that some FK to create the relationship. Shouldn't hibernate first check if the table exists and then tries to determine what is the FK?
As far as I understand, your problem is that your own script and hibernate don't use the same constraint name.
You can specify a constraint name used by hibernate with this annotation on your relationship:
#ForeignKey(name = "fk_UserSettings")
And additionally, in your create.sql:
ALTER TABLE ToDoGroups ADD CONSTRAINT fk_UserSettings FOREIGN KEY (UserSettingsID) REFERENCES UserSettings (ID);
I think my question here is how does hibernate know what FK to use. It used the same FK in the first drop statement when there was even no table. Later it used that some FK to create the relationship. Shouldn't hibernate first check if the table exists and then tries to determine what is the FK?
The foreign key name used by hibernate is the concatenation of
"FK_" + hashcode of referenced entity name + hash code of referenced columns name on that entity.
So it is not a randomly generated key (you will see that it will change if you change your entity name). And that's how hibernate knows the name of the fk to drop (hibernate is expecting that the constraint was created by hibernate with this well known naming strategy).
Hibernate use the name of the constraint to manipulate it. It don't compare the "rule" coded in constraints associated with a table to see if the constraint is already there or not.
I am using Hibernate 4.1.3 (JPA) on the Play! framework. The database is PostgreSQL 8.4.2. The schema was generated using hibernate.hbm2ddl.auto="update".
Short version: I have a class that has an #Id field that is a #GeneratedValue. Sometimes, when persisting it, I get a null-column violation, why?
More details:
I have a really simple class that I want to save to the database, that looks like this:
#Entity
class MyObject {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long id;
#NotNull
public String email;
public Integer total;
}
I usually create an instance of MyObject, I assign a value to email and total fields while id is null and I save it via EntityManager.persist(). Hibernate gets an id for the new object and saves it to the DB.
However sometimes, I get the following stacktrace:
2012-05-19 00:45:16,335 - [ERROR] - from org.hibernate.engine.jdbc.spi.SqlExceptionHelper [SqlExceptionHelper.java:144] in play-akka.actor.actions-dispatcher-6
ERROR: null value in column "id" violates not-null constraint
2012-05-19 00:45:16,350 - [ERROR] - from application in play-akka.actor.actions-dispatcher-6
! #6ad7j3p8p - Internal server error, for request [POST /method] ->
play.core.ActionInvoker$$anonfun$receive$1$$anon$1: Execution exception [[PersistenceException: org.hibernate.exception.ConstraintViolationException: ERROR: null value in column "id" violates not-null constraint]]
How is this possible? How can I track down the problem?
Here's the relevant DDL generated by Hibernate:
CREATE TABLE myobject (
id bigint NOT NULL,
email character varying(255) NOT NULL,
physical integer
);
CREATE SEQUENCE hibernate_sequence
START WITH 1
INCREMENT BY 1
NO MAXVALUE
NO MINVALUE
CACHE 1;
ALTER TABLE ONLY dailydetailedscore
ADD CONSTRAINT dailydetailedscore_pkey PRIMARY KEY (id);
Try the annotation #org.hibernate.annotations.GenericGenerator(name = “test-hilo-strategy”, strategy = “hilo”):
#Id
#org.hibernate.annotations.GenericGenerator(name=“hilo-strategy”, strategy = “hilo”)
#GeneratedValue(generator = ”hilo-strategy”)
As someone noted above, AUTO does not do what you think. It uses the underlying DB to determine how to generate values. It may pick sequences (for oracle), identity column (for mssql), or something else that is db specific.
The approach here uses an internal strategy that Hibernate supplies called "hilo".
See chapter 5 of the Hibernate reference manual dealing with "Generator" for a full description of what each of the supplied ones does.
Neither the OP solution nor Matt's solution worked with my PostgreSQL 9.3.
But this one works:
#SequenceGenerator(name="identifier", sequenceName="mytable_id_seq", allocationSize=1)
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="identifier")
Replace mytable_id_seq with the name of the sequence that generates your id.
Use Hibernate method:- save(String entityName, Object object)
Persist the given transient instance, first assigning a generated identifier.
Do not use :- #GeneratedValue(strategy=GenerationType.IDENTITY) for primary key if you want to persist user define Id.
For detail:-
http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/Session.html#save(java.lang.String
In mycase i was using Identity generation strategy and i have set the wrong data type in Postgres. Following steps i performed to debug the problem.
set
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true in application.properties and Drop the tables.
By this hibernate will automatically create the schema for you on the basis of your data-type.I noticed change in the datatype of id field.
Now when i tried any post requests, everything worked fine.
Env: JPA 1, Hibernate 3.3.x, MySQL 5.x
We auto generate database schema using hbm2ddl export operation. Would it be possible to generate a default value for a certain #Entity member during SQL generation. (e.g. archive field in mytable entity class.
create table mytable (
...
'archive‘ tinyint(1) default ’0 ’,
...
)
There is no portable way to do that and the columnDefinition "trick" is definitely not a good solution. Actually, setting defaults in the generated DDL is just not a good idea, this would require the provider to go back to the database to see the result after an insert1. Better default in your Java code.
1 Just in case, note that you can tell Hibernate to do that using the #Generated annotation.