Unable to find column with logical name with Hibernate - java

Unable to find column with logical name: VERTICAL_MARKET_ID in org.hibernate.mapping.Table(bck_vertical_market) and its related supertables and secondary tables
at org.hibernate.cfg.Ejb3JoinColumn.checkReferencedColumnsType(Ejb3JoinColumn.java:582)
Can anyone help with this fail? None of existing posts help me. My classes which uses VerticalMarket looks like:
#Entity
#Table(name = "BCK_VERTICAL_MARKET")
public class VerticalMarketEntity implements Serializable {
private VerticalMarketID verticalMarketId;
private String name;
public VerticalMarketEntity() {
}
public VerticalMarketEntity(VerticalMarketID verticalMarketId) {
if (Assert.CHECK)
Assert.notNull(verticalMarketId, "Parameter for id must be set");
this.verticalMarketId = verticalMarketId;
}
#EmbeddedId
#AttributeOverride(name = "verticalMarketId", column = #Column(name = "VERTICAL_MARKET_ID", nullable = false, length = 100))
#Attribute(index = 0, primaryKey = true)
public VerticalMarketID getVerticalMarketId() {
return verticalMarketId;
}
#Attribute(index = 1, type = String100TD.class)
#Column(name = "NAME", length = 100)
#Basic
public String getName() {
return name;
}
}
#Entity
#Table(name = "BCK_CERTIFICATE")
public class CertificateEntity {
private VerticalMarketEntity verticalMarket;
#Relation(index = 2, target = VerticalMarketEntity.class)
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "VERTICAL_MARKET", referencedColumnName = "VERTICAL_MARKET_ID")
public VerticalMarketEntity getVerticalMarket() {
return verticalMarket;
}
#Entity
#Table(name = "BCK_OFFERED_SERVICE")
public class OfferedServiceEntity implements Serializable {
private VerticalMarketEntity verticalMarket;
#Relation(index = 2, target = VerticalMarketEntity.class)
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "VERTICAL_MARKET", referencedColumnName = "VERTICAL_MARKET_ID")
public VerticalMarketEntity getVerticalMarket() {
return verticalMarket;
}
}
CREATE TABLEBCK_VERTICAL_MARKET (
VERTICAL_MARKET_ID CHAR(36) NOT NULL,
NAME VARCHAR2(100 CHAR) NOT NULL
)
ALTER TABLE BCK_VERTICAL_MARKET ADD CONSTRAINT PK_VERTICAL_MARKET PRIMARY KEY (VERTICAL_MARKET_ID);
CREATE TABLEBCK_CERTIFICATE (
CERTIFICATE_ID CHAR(36) NOT NULL,
IS_OTHER NUMBER(1) NOT NULL,
VERTICAL_MARKET CHAR(36) NOT NULL,
NAME VARCHAR2(100 CHAR) NOT NULL
);
ALTER TABLE BCK_CERTIFICATE ADD CONSTRAINT PK_CERTIFICATE PRIMARY KEY (CERTIFICATE_ID);
ALTER TABLE BCK_CERTIFICATE ADD CONSTRAINT FK__C_VERTICAL_MARKET_ID
FOREIGN KEY (VERTICAL_MARKET) REFERENCES BCK_VERTICAL_MARKET (VERTICAL_MARKET_ID);
CREATE TABLE BCK_OFFERED_SERVICE (
OFFERED_SERVICE_ID CHAR(36) NOT NULL,
VERTICAL_MARKET CHAR(36) NOT NULL,
OFFERED_SERVICE_TYPE CHAR(36)
) ;
ALTER TABLE BCK_OFFERED_SERVICE ADD CONSTRAINT PK_OFFERED_SERVICES PRIMARY KEY (OFFERED_SERVICE_ID);
ALTER TABLE BCK_OFFERED_SERVICE ADD CONSTRAINT FK___O_S_VERTICAL_MARKET_ID
FOREIGN KEY (VERTICAL_MARKET) REFERENCES BCK_VERTICAL_MARKET (VERTICAL_MARKET_ID);
ALTER TABLE BCK_OFFERED_SERVICE ADD CONSTRAINT FK___O_S_T_ID
FOREIGN KEY (OFFERED_SERVICE_TYPE) REFERENCES BCK_OFFERED_SERVICE_TYPE (OFFERED_SERVICE_TYPE_ID);

Related

JPA Column does not exist

I have an entity B which contains a map of entities <VC, P> in which some of the fields in P, e.g. A is not being linked with my join table and gives the error:
PSQLException: ERROR: column pricing1_.pricing_a does not exist
I am trying to make it such that when I persist my main entity, B, that all of the entities in my map will also be persisted as well (if possible) all in one go.
This error occurs both when I do
bRepo.save(b);
and
pRepo.saveAll(b.getPricing().values()); // by here the values at least exists in its own table (p)
bRepo.save(b);
here is what I have
Main entity B
#Setter
#Getter
#Entity
#Table(name = "b")
public class B implements Serializable {
#Id
#Column(nullable = false)
private String name;
#OneToMany(cascade = CascadeType.ALL)
#JoinTable(
name = "b_p",
joinColumns = #JoinColumn(name = "b_name", referencedColumnName = "name"))
#MapKeyJoinColumns({
#MapKeyJoinColumn(name = "p_c"),
#MapKeyJoinColumn(name = "c_id")
})
private Map<VC, P> pricing = new LinkedHashMap<>();
...
}
The pricing maps key
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "v_c")
public class VC implements Serializable {
#EmbeddedId private VCId vcId;
}
and its (VC) composite key
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
#Embeddable
public class VCId implements Serializable {
#Enumerated(EnumType.STRING)
#Column(name = "p_c")
private PC pC;
#Column(name = "c_id")
private String cId;
}
the pricing map's value
#Setter
#Getter
#NoArgsConstructor
#AllArgsConstructor
#Embeddable
#Entity
#Table(name = "p")
public class P implements Serializable {
#EmbeddedId private PId pId;
}
and its (P) key
#Setter
#Getter
#NoArgsConstructor
#Embeddable
public class PId implements Serializable {
#Column(name = "a")
private BigDecimal a; // complains about this field
#Column(name = "d_a")
private BigDecimal dA; // and will probably complain about this one too
}
My tables
CREATE TABLE b
(
name VARCHAR(100) NOT NULL PRIMARY KEY,
...
);
CREATE TABLE v_c
(
p_c TEXT NOT NULL,
c_id VARCHAR(50) NOT NULL,
PRIMARY KEY (p_c, c_id)
);
CREATE TABLE p
(
a NUMERIC NOT NULL,
d_a NUMERIC NOT NULL DEFAULT 0.0,
PRIMARY KEY (a, d_a)
);
CREATE TABLE b_p
(
b_name VARCHAR(100) NOT NULL,
p_c TEXT NOT NULL,
c_id VARCHAR(50) NOT NULL,
a NUMERIC NOT NULL,
d_a NUMERIC NOT NULL DEFAULT 0.0,
PRIMARY KEY (b_name, p_c, c_id),
FOREIGN KEY (b_name) REFERENCES b (name) ON DELETE CASCADE,
FOREIGN KEY (p_c, c_id) REFERENCES v_c (p_c, c_id) ON DELETE CASCADE,
FOREIGN KEY (a, d_a) REFERENCES p (a, d_a) ON DELETE CASCADE
);
What am I doing wrong?
In the end I made the following changes and it worked:
Replaced the composite ids for p and v_c with auto increment ids AND added another new, auto increment field called pricing_p_id in my b_p table:
CREATE TABLE v_c
(
vc_id BIGSERIAL NOT NULL PRIMARY KEY,
p_c TEXT NOT NULL,
coin_id VARCHAR(50) NOT NULL
);
CREATE TABLE p
(
p_id BIGSERIAL NOT NULL PRIMARY KEY,
a NUMERIC NOT NULL,
d_a NUMERIC NOT NULL DEFAULT 0.0,
vc_id BIGSERIAL,
FOREIGN KEY (vc_id) REFERENCES v_c(vc_id) ON DELETE CASCADE
);
CREATE TABLE b_p
(
b_name VARCHAR(100) NOT NULL,
vc_id BIGSERIAL NOT NULL,
pricing_p_id BIGSERIAL NOT NULL,
PRIMARY KEY (b_name, vc_id, pricing_p_id),
FOREIGN KEY (b_name) REFERENCES b (name) ON DELETE CASCADE,
FOREIGN KEY (vc_id) REFERENCES v_c (vc_id) ON DELETE CASCADE,
FOREIGN KEY (pricing_p_id) REFERENCES p (p_id) ON DELETE CASCADE
);
and then updated the mapping for the pricing field to only look like this:
#OneToMany(cascade = CascadeType.ALL)
#MapKeyJoinColumn(name = "vc_id") // this
private Map<VC, P> pricing = new LinkedHashMap<>();

Hibernate is not mapping object correctly ("Bad value for type" exception) when using compound primary keys in a junction table

I am getting the exception o.h.e.j.s.SqlExceptionHelper | Bad value for type int : 9dac4fd2-a04c-4be7-976b-d880a43ea25a. It seems to want to put a UUID in an Integer field here.
I have the following tables, which admittedly are a bit complex in terms of compound keys:
CREATE TABLE public.event (
id uuid NOT NULL,
...
CONSTRAINT event_pkey PRIMARY KEY (id)
);
CREATE TABLE public.condition_set (
api_id uuid NOT NULL,
version integer NOT NULL,
...,
CONSTRAINT condition_set_pkey PRIMARY KEY (api_id, version)
);
CREATE TABLE public.condition_set_event (
condition_set_api_id uuid NOT NULL,
condition_set_version integer NOT NULL,
event_id uuid NOT NULL,
CONSTRAINT condition_set_event_pkey PRIMARY KEY (condition_set_api_id, condition_set_version, event_id),
CONSTRAINT fk_condition_set FOREIGN KEY (condition_set_api_id, condition_set_version) REFERENCES public.condition_set(api_id, version) ON DELETE CASCADE,
CONSTRAINT fk_event FOREIGN KEY (event_id) REFERENCES public.event(id) ON DELETE CASCADE
);
In my model I have the Event class which is fairly straightforward. The ConditionSet class has a compound primary key matching the database structure, as follows:
#Entity
public class ConditionSet {
#EmbeddedId
private ConditionSetId id;
}
which looks like:
#Embeddable
public class ConditionSetId implements Serializable {
private static final long serialVersionUID = 8110138933878596476L;
private UUID apiId;
private Integer version;
}
The tricky part is the ConditionSetEvent junction table which ALSO consists of a compound key, of which one is the compound key of ConditionSet
#Entity
public class ConditionSetEvent {
#EmbeddedId
private ConditionSetEventId id;
#ManyToOne(fetch = FetchType.LAZY)
#OnDelete(action = OnDeleteAction.CASCADE)
#MapsId("conditionSetId")
#JoinColumns(foreignKey = #ForeignKey(name = "fk_condition_set"), value = {
#JoinColumn(nullable = false, name = "conditionSetApiId"),
#JoinColumn(nullable = false, name = "conditionSetVersion")
})
private ConditionSet conditionSet;
#ManyToOne(fetch = FetchType.LAZY)
#OnDelete(action = OnDeleteAction.CASCADE)
#MapsId("eventId")
#JoinColumn(foreignKey = #ForeignKey(name = "fk_event"))
private Event event;
public ConditionSetEvent(ConditionSet conditionSet, Event event) {
this.conditionSet = conditionSet;
this.event = event;
this.id = new ConditionSetEventId(conditionSet.getId(), event.getId());
}
}
with its EmbeddedId:
#Embeddable
public class ConditionSetEventId implements Serializable {
private static final long serialVersionUID = -6269791751266804667L;
private ConditionSetId conditionSetId;
private UUID eventId;
}
However, if I try to query this junction table with this repository method:
public interface ConditionSetEventRepository extends JpaRepository<ConditionSetEvent, ConditionSetEventId> {
#Query("select cse from ConditionSetEvent cse where cse.id.eventId = :eventId")
List<ConditionSetEvent> findByEventId(UUID eventId);
}
then I get the error as mentioned on top (where the uuid in the exception is a valid ConditionSet.apiId, but that somehow seems to be re-used.
With trace logging:
DEBUG | org.hibernate.SQL | select conditions0_.condition_set_api_id as conditio0_8_, conditions0_.event_id as event_id1_8_, conditions0_.condition_set_api_id as conditio2_8_, conditions0_.condition_set_version as conditio3_8_ from condition_set_event conditions0_ where conditions0_.event_id=?
TRACE | o.h.t.d.sql.BasicBinder | binding parameter [1] as [OTHER] - [be1ec45d-6533-4e77-98b7-f9a357cda052]
TRACE | o.h.t.d.s.BasicExtractor | extracted value ([conditio0_8_] : [OTHER]) - [9dac4fd2-a04c-4be7-976b-d880a43ea25a]
WARN | o.h.e.j.s.SqlExceptionHelper | SQL Error: 0, SQLState: 22003
ERROR | o.h.e.j.s.SqlExceptionHelper | Bad value for type int : 9dac4fd2-a04c-4be7-976b-d880a43ea25a
So it does manage to extract that UUID value initially (the last trace line), but on the next step (for the Integer) it still is trying to use the UUID instead of the Integer.
Am I doing something wrong here?
I don't think you need the #JoinColumns and it is messing up which id column maps to which id field in ConditionSetEventId
#Entity
public class ConditionSetEvent {
#EmbeddedId
private ConditionSetEventId id;
#ManyToOne(fetch = FetchType.LAZY)
#OnDelete(action = OnDeleteAction.CASCADE)
#MapsId("conditionSetId")
private ConditionSet conditionSet;
....

How to implement Composite Primary key and Composite Foreign Key using JPA,Hibernate, Springboot

I searched a lot for this particular problem but i didn''t find any specific solution. I have a Composite Primary Key in one table and one of the field from this composite primary key is the part of the Composite Primary Key of another table. You can say that this particular field is the foreign key in the second table but i a not defining any exclusive Foreign Key constraint in the table definition. There can be multiple Records in the second table for each rec in the first table.i am trying to implement this using SPringBoot-JPA-Hibernate but not being able to do so. Can some body help me here. Here are the detais:-
I have a USER_CREDENTIAL table with following fields:-
CREATE TABLE `INSTITUTION_USER_CREDENTIAL` (
`INSTITUTION_USER_ID INT(10) NOT NULL, -> AutoGeneratd
`INSTITUTION_USER_NAME` VARCHAR(50) NOT NULL,
`INSTITUTION_USER_PASSWORD` VARCHAR(50) NOT NULL,
`FIRST_NAME` VARCHAR(100) NOT NULL,
`MIDDLE_NAME` VARCHAR(100),
`LAST_NAME` VARCHAR(100) NOT NULL,
PRIMARY KEY (`INSTITUTION_USER_ID`,`INSTITUTION_USER_NAME`)
);
2) Here is my second table
CREATE TABLE `INSTITUTION_USER_CREDENTIAL_MASTER` (
`INSTITUTION_ID` INT(10) NOT NULL, -> Autogenerated
`INSTITUTION_USER_ID` INT(10) NOT NULL, -> Coming from
INSTITUTION_USER_CREDENTIAL
`INSTITUTION_USER_ROLE` CHAR(02) NOT NULL,
`INSTITUTION_USER_STATUS` CHAR(02) NOT NULL,
`INSTITUTION_NAME` VARCHAR(200) NOT NULL,
`LAST_UPDT_ID` VARCHAR(100) NOT NULL,
`LAST_UPDT_TS` DATETIME NOT NULL,
PRIMARY KEY(`INSTITUTION_ID`,`INSTITUTION_USER_ID`,`INSTITUTION_USER_ROLE`)
);
Note that i haven't declare any particular foreign key in the second table. I have two #Embeddable Class corresponding to two primary key structure for two different table:-
For the INSTITUTION_USER_CREDENTIAL table:-
#Embeddable
public class InstitutionUserCredentialPrimaryKey implements Serializable{
private static final long serialVersionUID = 1L;
#Column(name = "INSTITUTION_USER_ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private int institutionUserId;
#Column(name = "INSTITUTION_USER_NAME")
private String institutionUserName;
//Getter-Setters removed for clarity
}
Corresponding Entity Class:-
#Entity(name = "INSTITUTION_USER_CREDENTIAL")
public class InstitutionUserCredential {
#EmbeddedId
private InstitutionUserCredentialPrimaryKey
institutionUserCredentialPrimaryKey;
#Column(name = "INSTITUTION_USER_PASSWORD")
private String instituteUserPassword;
#Column(name = "FIRST_NAME")
private String firstname;
#Column(name = "MIDDLE_NAME")
private String middleName;
#Column(name = "LAST_NAME")
private String lastName;
#OneToMany(mappedBy="institutionUserCredential", cascade = CascadeType.ALL)
private List<InstitutionUserCredentialMaster>
institutionUserCredentialMaster;
//Getter-Setter and other part of the code removed for clarity
}
For the INSTITUTION_USER_CREDENTIAL_MASTER table:-
#Embeddable
public class InstituteUserCredentialMasterPrimaryKey implements Serializable
{
private static final long serialVersionUID = 1L;
#Column(name = "INSTITUTION_ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private int institutionId;
#Column(name = "INSTITUTION_USER_ID")
private int institutionUserId;
#Column(name = "INSTITUTION_USER_ROLE")
private String userRole;
//Getter-Setter and other part of the code removed for clarity
}
Entity Class:-
#Entity(name = "INSTITUTION_USER_CREDENTIAL_MASTER")
public class InstitutionUserCredentialMaster {
#EmbeddedId
private InstituteUserCredentialMasterPrimaryKey
instituteUserCredentialMasterPrimaryKey;
#Column(name = "INSTITUTION_USER_STATUS")
private String userStatus;
#Column(name = "INSTITUTION_NAME")
private String institutionName;
#Column(name = "LAST_UPDT_ID")
private String lastUpdateId;
#Column(name = "LAST_UPDT_TS")
private String lastUpdateTimestamp;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumns({
#JoinColumn(name="institutionUserId", referencedColumnName =
"INSTITUTION_USER_ID")
})
private InstitutionUserCredential institutionUserCredential;
//Getter-Setter and other part of the code removed for clarity
}
Note that only 1 field INSTITUTION_USER_ID, is getting used in the Composite PrimaryKey of the InstitutionUserCredentialMaster and is coming from the composite primary key of the InstitutionUserCredential.
When i am running my code this is giving me an error like :-
Invocation of init method failed; nested exception is
org.hibernate.AnnotationException:
referencedColumnNames(INSTITUTION_USER_ID) of com.bnl.application.entity.InstitutionUserCredentialMaster.institutionUserCredential referencing com.bnl.application.entity.InstitutionUserCredential not mapped to a single property
None of the examples i have seen so far involving the Composite Primary key and foreign key doesn't treat any one particular field and is more of the entire key structure. I am using MYSQL and i have checked that we can create table having composite primary key and one of the field from that composite key is foreign key in another table and also part of the Composite Primary key of the second table.
Any pointers appreciated
UPDATE:- In my first post i made a mistake while posting it. I am sorry that institutionUserName became a part of the InstitutionUserCredentialMaster. it was a typo. There is no existence of the intitutionUserName in the InstitutionUserCredentialMaster table. i have fixed that and updated the post.
***** Update based on the input by Niver and Wega *****
Update to the InstitutionUserCredentialMasterPrimaryKey
#Embeddable
public class InstituteUserCredentialMasterPrimaryKey implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name = "INSTITUTION_ID")
#GeneratedValue(strategy=GenerationType.AUTO)
private int institutionId;
#Column(name = "INSTITUTION_USER_ID")
private int institutionUserId;
// Added the institutionUserName
#Column(name = "INSTITUTION_USER_NAME")
private String institutionUserName;
#Column(name = "INSTITUTION_USER_ROLE")
private String userRole;
}
Update to the Entity Class InsstitutionUserCredentialMaster :-
#Entity(name = "INSTITUTION_USER_CREDENTIAL_MASTER")
public class InstitutionUserCredentialMaster {
#EmbeddedId
private InstituteUserCredentialMasterPrimaryKey instituteUserCredentialMasterPrimaryKey;
#Column(name = "INSTITUTION_USER_STATUS")
private String userStatus;
#Column(name = "INSTITUTION_NAME")
private String institutionName;
#Column(name = "LAST_UPDT_ID")
private String lastUpdateId;
#Column(name = "LAST_UPDT_TS")
private String lastUpdateTimestamp;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumns({
#JoinColumn(name="institutionUserId", referencedColumnName = "INSTITUTION_USER_ID"),
#JoinColumn(name="institutionUserName",referencedColumnName = "INSTITUTION_USER_NAME")
})
private InstitutionUserCredential institutionUserCredential;
}
This time i am getting an error like
Invocation of init method failed; nested exception is org.hibernate.DuplicateMappingException: Table [institution_user_credential_master] contains physical column name [institution_user_id] referred to by multiple physical column names: [institutionUserId], [INSTITUTION_USER_ID]
I think that the problem is that you are not referencing the other part of the EmbeddedId in the JoinColumns annotation. You have defined that also the institutionUserName is part of the primary key, so you should mention it as well in the definition of the foreign key in entity InstitutionUserCredentialMaster.

How to make a reflexive one-to-many relationship inside a model?

In the database there is a table having a reflexive one-to-many relationship :
create table structure
(
struct_code varchar2(15) not null,
str_struct_code varchar2(15),
struct_lib varchar2(255),
struct_sigle varchar2(10),
struct_comment clob,
struct_interne smallint default 1,
constraint pk_structure primary key (struct_code)
);
alter table structure add constraint fk_structur_associati_structur foreign key (str_struct_code) references structure (struct_code);
I created the corresponding model :
#Entity
#Table(name = "structure")
public class Structure {
#Id()
#Column(name="struct_code")
private String code;
#Column(name="struct_sigle")
private String sigle;
#Column(name="struct_lib")
private String lib;
#Column(name="struct_interne")
private Integer interne;
#ManyToOne
#JoinColumn(name = "struct_code")
private Structure sousStructure;
public Structure() {
super();
}
public Structure(String code) {
super();
}
// getters and setters
}
But when I built the project then I got the error : mappingexception repeated column in mapping for entity : com.ambre.pta.model.Structure column: struct_code (should be mapped with insert="false" update="false")
So how to write correctly the reflexive relation ?
I do have something like this in place:
#ManyToOne
#JoinColumn(name = "parent_struct_code", nullable = true)
private Structure parentStructure;
#OneToMany(mappedBy = "parentStructure", cascade = CascadeType.REMOVE, fetch=FetchType.LAZY)
private List<Structure> sousStructures = new ArrayList<>();

inserting new row in sqlite using hibernate

Decide to use sqlite with hibernate.
First of all this is only test project.
My entity classes
Address.java
#Entity
#Table(name = "ADDRESS")
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID", length = 3, nullable = false, unique = true)
private Long id;
#Column(name = "NAME", length = 40, nullable = false)
private String name;
#OneToMany(mappedBy = "address", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
private Set<Flat> flats;
Flat
#Entity
#Table(name="FLAT")
public class Flat {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "ID", length = 6, unique = true)
private long id = 1L;
#Column(name = "CRTN_DATE", nullable = false)
private Date creationDate;
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "ADDRESS_ID", nullable = false)
private Address address;
#Column(name = "ROOM_CNT", length = 1)
private int roomCount;
#Column(name = "AREA", length = 4)
private long totalArea;
#Column(name = "PHONE", length = 1)
private String phone;
#Column(name = "PRICE", length = 7)
private float price;
so my problem:
When I try to insert new row like this
Flat flat = new Flat();
flat.setTotalArea(45);
flat.setCreationDate(new Date());
flat.setAddress(addressDAO.getByID(3));
flat.setRoomCount(2);
flat.setPrice(68000);
flat.setPhone("Y");
flat.setImages(new HashSet<ImageStorage>());
flatDAO.save(flat);
I get such output in my console:
Hibernate: insert into FLAT (ADDRESS_ID, CRTN_DATE, PHONE, PRICE, ROOM_CNT, AREA) values (?, ?, ?, ?, ?, ?)
ERROR: [SQLITE_CONSTRAINT] Abort due to constraint violation (NOT NULL constraint failed: FLAT.ID)
as I understand Hibernate didn't add null field (ID) into generated sql query. So maybe someone know how to fix this?
thanks in advance.
UPDATE
dialect I copied from here
dll
CREATE TABLE ADDRESS
(
ID INTEGER PRIMARY KEY NOT NULL,
NAME TEXT NOT NULL
);
CREATE TABLE FLAT
(
ID INTEGER PRIMARY KEY NOT NULL,
CRTN_DATE TEXT NOT NULL,
ADDRESS_ID INTEGER NOT NULL,
ROOM_CNT INTEGER NOT NULL,
AREA REAL NOT NULL,
PHONE TEXT NOT NULL,
PRICE REAL NOT NULL,
FOREIGN KEY (ADDRESS_ID) REFERENCES ADDRESS (ID) DEFERRABLE INITIALLY DEFERRED
);
If you define your ID column as INTEGER PRIMARY KEY you can omit the ID column in your insert statement (which hibernate does in your case).
Take a look at Autoincrement In SQLite
Try this in SQL fiddle (select sqlite database at the top)
Schema
CREATE TABLE flat(id INTEGER PRIMARY KEY, name TEXT);
SQL
INSERT INTO flat(name) VALUES('flat 1');
INSERT INTO flat(id, name) VALUES(2, 'flat 2');
INSERT INTO flat(name) VALUES('flat 3');
select * from flat;
UPDATE
I've never used sqlite but according to the example above your code should work. You've defined your id column as INTEGER PRIMARY KEY and hibernate doesn't include the id column in it's inserts.
Are you sure you haven't enabled "hibernate.hbm2ddl.auto"? The error makes sense (to me at least) if you are generating your tables with hibernate as your dialect isn't using the INTEGER PRIMARY KEY clause for your identity columns: take a look at hasDataTypeInIdentityColumn() and getIdentityColumnString.
please add your custom dialect
public class SQLiteDialect extends Dialect {
public SQLiteDialect() {
registerColumnType(Types.BIT, "integer");
registerColumnType(Types.TINYINT, "tinyint");
registerColumnType(Types.SMALLINT, "smallint");
registerColumnType(Types.INTEGER, "integer");
registerColumnType(Types.BIGINT, "bigint");
registerColumnType(Types.FLOAT, "float");
registerColumnType(Types.REAL, "real");
registerColumnType(Types.DOUBLE, "double");
registerColumnType(Types.NUMERIC, "numeric");
registerColumnType(Types.DECIMAL, "decimal");
registerColumnType(Types.CHAR, "char");
registerColumnType(Types.VARCHAR, "varchar");
registerColumnType(Types.LONGVARCHAR, "longvarchar");
registerColumnType(Types.DATE, "date");
registerColumnType(Types.TIME, "time");
registerColumnType(Types.TIMESTAMP, "timestamp");
registerColumnType(Types.BINARY, "blob");
registerColumnType(Types.VARBINARY, "blob");
registerColumnType(Types.LONGVARBINARY, "blob");
registerColumnType(Types.BLOB, "blob");
registerColumnType(Types.CLOB, "clob");
registerColumnType(Types.BOOLEAN, "integer");
}
public IdentityColumnSupport getIdentityColumnSupport() {
return new SQLiteIdentityColumnSupport();
}
public boolean hasAlterTable() {
return false;
}
public boolean dropConstraints() {
return false;
}
public String getDropForeignKeyString() {
return "";
}
public String getAddForeignKeyConstraintString(String constraintName, String[] foreignKey, String referencedTable, String[] primaryKey, boolean referencesPrimaryKey) {
return "";
}
public String getAddPrimaryKeyConstraintString(String constraintName) {
return "";
}
public String getForUpdateString() {
return "";
}
public String getAddColumnString() {
return "add column";
}
public boolean supportsOuterJoinForUpdate() {
return false;
}
public boolean supportsIfExistsBeforeTableName() {
return true;
}
public boolean supportsCascadeDelete() {
return false;
}
``````
---------------------------------------------------
public class SQLiteIdentityColumnSupport extends IdentityColumnSupportImpl {
#Override
public boolean supportsIdentityColumns() {
return true;
}
#Override
public String getIdentitySelectString(String table, String column, int type)
throws MappingException {
return "select last_insert_rowid()";
}
#Override
public String getIdentityColumnString(int type) throws MappingException {
return "integer";
}
add the property in properties
hibernate.dialect=com.common.config.db.SQLiteDialect // as per you class package
then then configure your hibernate properties with dialect
("hibernate.dialect", dialect);

Categories