How to resolve hibernate table creation while its says unsuccessful creating table - java

I have a domain class name DataList
#Entity
#Table(name = "list_data")
public class ListData {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int id;
#Column(name = "sys_id")
private String sysId;
#Column(name = "name")
private String name;
#Column(name = "detail")
private String detail;
#Column(name = "values")
private String values;
//getters and setters
}
I have some others domain class..
I'm using hibernate 3.6 everything alright.
but somehow Im unsuccessful while creating this table.
2012-02-25 03:31:52,166 ERROR SchemaExport:274 Unsuccessful: create table list_data (id >integer not null auto_increment, detail varchar(255), name varchar(255), sys_id varchar(255), >values varchar(255), primary key (id))
2012-02-25 03:31:52,167 ERROR SchemaExport:275 You have an error in your SQL syntax; check the >manual that corresponds to your MySQL server version for the right syntax to use near 'values >varchar(255), primary key (id))' at line 1
I know my hibernate configuration is fine, I have some other domain class, they are working just fine.

I think that you cannot use values as a column name since it is a MySQL keyword (INSERT INTO ... VALUES() ).

Related

Logical delete and create with Hibernate

#Entity
#Table(name = "Country")
#SQLDelete(sql = "UPDATE Country SET date_deleted=NOW() WHERE code = ?")
#Where(clause = "date_deleted is NULL")
public class Country {
#Id
#Column(name = "code", nullable = false)
private String code;
#Column(name = "description")
private String description;
#Column(name = "date_deleted")
private Date date_deleted;
....
}
When I logic delete an Entity in the database with the code 'U1' and after, I created a new Entity with the same code 'Ü1', occurs an exception "duplicate entry". Has Hibernate an annotation to solve this problem?
edit:
The Error when I insert a new entity with the same code is this:
org.postgresql.util.PSQLException: ERROR: duplicate key value violates
unique constraint "country_pkey" Detail: Key (code)=(AA) already
exists.
The table is:
CREATE TABLE public.country(
code bpchar(2) NOT NULL,
description bpchar(50) NULL,
date_deleted timestamp NULL,
CONSTRAINT country_pkey PRIMARY KEY (code),
CONSTRAINT constraint_country UNIQUE (date_deleted, code) -- I add this constraint
);
Since you manage the code column and you can have multiple entries with the same code, one solution would be to have an id column that is autogenerated.
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
This will enable you to delete an object with the code 'U1' and add another one with the same code.
You can check this great tutorial: https://vladmihalcea.com/the-best-way-to-soft-delete-with-hibernate/

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.

Hibernate is getting wrong ID values when using UUID as primary key

My entity:
#Entity
#Table(name = "eh_portal")
public class PortalEntity {
#Id
#Column(name = "id", columnDefinition = "CHAR(36)")
private UUID id; //java.util.UUID;
#Column(name = "name")
private String name;
#Column(name = "url")
private String url;
// -- Constructor for Hibernate --
protected PortalEntity() {
}
// -- Constructor for new entity in service code --
public PortalEntity(final UUID id) {
this.id = id;
}
.... getters and setters ommited
}
Respository is Spring DATA JPA:
public interface PortalRepository extends CrudRepository<PortalEntity, UUID> {
}
MYSQL 5 Database table definition:
CREATE TABLE `eh_portal` (
`id` char(36) NOT NULL COMMENT 'UUID',
`name` varchar(255) NOT NULL,
`url` varchar(255) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `url_UNIQUE` (`url`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
The problem is, Hibernate is returning obviously wrong data - see screenshots below
Mysql workbench:
Actual web page where I get entities thru Spring Data JPA:
You can see that UUIDs are obviously differrent, while other columns are correct.
What is wrong here? (Spring 4, Hibernate 4, Spring DATA JPA, Mysql 5)
Try using #Type(type="uuid-char").

why i get null at relationship field?

Why if i run this code:
Student st = new Student();
st.setFirstName("First");
st.setLastName("Last");
st.setIndexNr("11");
st.setStudentPK(new StudentPK(0, user.getIdUser()));
studentFacade.create(st);
Mail m = new Mail();
m.setContent("con");
m.setRecipient("rec");
m.setIdMail(0);
mailFacade.create(m);
List<Mail> l = new ArrayList<Mail>();
l.add(m);
st.setMailList(l);
studentFacade.edit(st); // st have mailList property set to l
stud=studentFacade.findByIndex("11"); //after edit and get student he has mailList equal null
Why after persist and edit object i get null at property for OneToMany relationship?
In database MySql i have STUDENT table and MAIL table:
CREATE TABLE IF NOT EXISTS `STUDENT` (
`id_student` MEDIUMINT UNSIGNED NOT NULL AUTO_INCREMENT ,
`first_name` VARCHAR(65) NULL ,
`last_name` VARCHAR(65) NULL ,
`index_nr` VARCHAR(45) NULL
)
ENGINE = InnoDB
CREATE TABLE IF NOT EXISTS `MAIL` (
`id_mail` INT UNSIGNED NOT NULL AUTO_INCREMENT ,
`recipient` TEXT NULL ,
`content` TEXT NULL ,
`sender_student` MEDIUMINT UNSIGNED NULL ,
PRIMARY KEY (`id_mail`) ,
INDEX `fk_STUDENT_id_idx` (`sender_student` ASC) ,
CONSTRAINT `fk_STUDENT`
FOREIGN KEY (`sender_student` )
REFERENCES `jkitaj`.`STUDENT` (`id_student` )
ON DELETE CASCADE
ON UPDATE CASCADE
)
ENGINE = InnoDB
From database i generate entity in netbeans:
#Entity
#Table(name = "STUDENT")
public class Student implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
protected StudentPK studentPK;
#Size(max = 65)
#Column(name = "first_name")
private String firstName;
#Size(max = 65)
#Column(name = "last_name")
private String lastName;
#Size(max = 45)
#Column(name = "index_nr")
private String indexNr;
#OneToMany(mappedBy = "senderStudent",fetch=FetchType.EAGER)
private List<Mail> mailList;
//getters, setters ...
}
public class Mail implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue
#Basic(optional = false)
#Column(name = " id_mail")
private Integer idMail;
#Lob
#Size(max = 65535)
#Column(name = "recipient")
private String recipient;
#Lob
#Size(max = 65535)
#Column(name = "content")
private String content;
#JoinColumn(name = "sender_student", referencedColumnName = "id_student")
#ManyToOne
private Student senderStudent;
//getters, setters...
}
EDIT:
I think i forget about fetch in #OneToMany annotation of Student entity. But when i set in to fetch=FetchType.LAZY i again get null after edit and and get edited object from database. When set fetch=FetchType.EAGER mailList field isn't null. Why ?
Problem is at OpenJPA, when i use fetch=FetchType.LAZY at some property of entity. The problem was with life cycle of enties. All enties must be re-attached to the persistence context.
Same problem is here: OpenJPA - lazy fetching does not work and here: What's the lazy strategy and how does it work?
You have a unique combination of too much information with too little.
If you are actually running that code, then package it up as a complete, runnable example -- yes, it won't run on another machine unless that machine also has a database setup, but it will tell us everything you're doing instead of just the part that you think is important.
Give us the complete error message, don't tell us what it is.
Two important things to remember about posting a question on a site like this: you don't know what's wrong, so you need to give us complete raw data, not half-analysis. And it is generally a waste of time for us to just guess at things.

Hibernate: "Field 'id' doesn't have a default value"

I'm facing what I think is a simple problem with Hibernate, but can't solve it (Hibernate forums being unreachable certainly doesn't help).
I have a simple class I'd like to persist, but keep getting:
SEVERE: Field 'id' doesn't have a default value
Exception in thread "main" org.hibernate.exception.GenericJDBCException: could not insert: [hibtest.model.Mensagem]
at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
[ a bunch more ]
Caused by: java.sql.SQLException: Field 'id' doesn't have a default value
[ a bunch more ]
The relevant code for the persisted class is:
package hibtest.model;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Inheritance;
import javax.persistence.InheritanceType;
#Entity
#Inheritance(strategy = InheritanceType.JOINED)
public class Mensagem {
protected Long id;
protected Mensagem() { }
#Id
#GeneratedValue
public Long getId() {
return id;
}
public Mensagem setId(Long id) {
this.id = id;
return this;
}
}
And the actual running code is just plain:
SessionFactory factory = new AnnotationConfiguration()
.configure()
.buildSessionFactory();
{
Session session = factory.openSession();
Transaction tx = session.beginTransaction();
Mensagem msg = new Mensagem("YARR!");
session.save(msg);
tx.commit();
session.close();
}
I tried some "strategies" within the GeneratedValue annotation but it just doesn't seem to work. Initializing id doesn't help either! (eg Long id = 20L).
Could anyone shed some light?
EDIT 2: confirmed: messing with#GeneratedValue(strategy = GenerationType.XXX) doesn't solve it
SOLVED: recreating the database solved the problem
Sometimes changes made to the model or to the ORM may not reflect accurately on the database even after an execution of SchemaUpdate.
If the error actually seems to lack a sensible explanation, try recreating the database (or at least creating a new one) and scaffolding it with SchemaExport.
If you want MySQL to automatically produce primary keys then you have to tell it when creating the table. You don't have to do this in Oracle.
On the Primary Key you have to include AUTO_INCREMENT. See the example below.
CREATE TABLE `supplier`
(
`ID` int(11) NOT NULL **AUTO_INCREMENT**,
`FIRSTNAME` varchar(60) NOT NULL,
`SECONDNAME` varchar(100) NOT NULL,
`PROPERTYNUM` varchar(50) DEFAULT NULL,
`STREETNAME` varchar(50) DEFAULT NULL,
`CITY` varchar(50) DEFAULT NULL,
`COUNTY` varchar(50) DEFAULT NULL,
`COUNTRY` varchar(50) DEFAULT NULL,
`POSTCODE` varchar(50) DEFAULT NULL,
`HomePHONENUM` bigint(20) DEFAULT NULL,
`WorkPHONENUM` bigint(20) DEFAULT NULL,
`MobilePHONENUM` bigint(20) DEFAULT NULL,
`EMAIL` varchar(100) DEFAULT NULL,
PRIMARY KEY (`ID`)
)
ENGINE=InnoDB DEFAULT CHARSET=latin1;
Here's the Entity
package com.keyes.jpa;
import java.io.Serializable;
import javax.persistence.*;
import java.math.BigInteger;
/**
* The persistent class for the parkingsupplier database table.
*
*/
#Entity
#Table(name = "supplier")
public class supplier implements Serializable
{
private static final long serialVersionUID = 1L;
#Id
**#GeneratedValue(strategy = GenerationType.IDENTITY)**
#Column(name = "ID")
private long id;
#Column(name = "CITY")
private String city;
#Column(name = "COUNTRY")
private String country;
#Column(name = "COUNTY")
private String county;
#Column(name = "EMAIL")
private String email;
#Column(name = "FIRSTNAME")
private String firstname;
#Column(name = "HomePHONENUM")
private BigInteger homePHONENUM;
#Column(name = "MobilePHONENUM")
private BigInteger mobilePHONENUM;
#Column(name = "POSTCODE")
private String postcode;
#Column(name = "PROPERTYNUM")
private String propertynum;
#Column(name = "SECONDNAME")
private String secondname;
#Column(name = "STREETNAME")
private String streetname;
#Column(name = "WorkPHONENUM")
private BigInteger workPHONENUM;
public supplier()
{
}
public long getId()
{
return this.id;
}
public void setId(long id)
{
this.id = id;
}
public String getCity()
{
return this.city;
}
public void setCity(String city)
{
this.city = city;
}
public String getCountry()
{
return this.country;
}
public void setCountry(String country)
{
this.country = country;
}
public String getCounty()
{
return this.county;
}
public void setCounty(String county)
{
this.county = county;
}
public String getEmail()
{
return this.email;
}
public void setEmail(String email)
{
this.email = email;
}
public String getFirstname()
{
return this.firstname;
}
public void setFirstname(String firstname)
{
this.firstname = firstname;
}
public BigInteger getHomePHONENUM()
{
return this.homePHONENUM;
}
public void setHomePHONENUM(BigInteger homePHONENUM)
{
this.homePHONENUM = homePHONENUM;
}
public BigInteger getMobilePHONENUM()
{
return this.mobilePHONENUM;
}
public void setMobilePHONENUM(BigInteger mobilePHONENUM)
{
this.mobilePHONENUM = mobilePHONENUM;
}
public String getPostcode()
{
return this.postcode;
}
public void setPostcode(String postcode)
{
this.postcode = postcode;
}
public String getPropertynum()
{
return this.propertynum;
}
public void setPropertynum(String propertynum)
{
this.propertynum = propertynum;
}
public String getSecondname()
{
return this.secondname;
}
public void setSecondname(String secondname)
{
this.secondname = secondname;
}
public String getStreetname()
{
return this.streetname;
}
public void setStreetname(String streetname)
{
this.streetname = streetname;
}
public BigInteger getWorkPHONENUM()
{
return this.workPHONENUM;
}
public void setWorkPHONENUM(BigInteger workPHONENUM)
{
this.workPHONENUM = workPHONENUM;
}
}
Take a look at GeneratedValue's strategy. It typically looks something like:
#GeneratedValue(strategy=GenerationType.IDENTITY)
you must be using update in your hbm2ddl property. make the changes and update it to Create so that it can create the table.
<property name="hbm2ddl.auto">create</property>
It worked for me.
Dropping the table from the database manually and then re-running the application worked for me. In my case table was not created properly(with constraints) I guess.
I had this issue. My mistake was i had set the insertable and updatable fileds as false and was trying to set the field in the request. This field is set as NON NULL in DB.
#ManyToOne
#JoinColumn(name="roles_id", referencedColumnName = "id", insertable = false, updatable = false, nullable=false)
#JsonBackReference
private Role role;
Later I changed it to - insertable = true, updatable = true
#ManyToOne
#JoinColumn(name="roles_id", referencedColumnName = "id", insertable = true, updatable = true, nullable=false)
#JsonBackReference
//#JsonIgnore
private Role role;
It worked perfectly later.
I came here because of the error message, turns out I had two tables with the same name.
I had the same problem. I found the tutorial Hibernate One-To-One Mapping Example using Foreign key Annotation and followed it step by step like below:
Create database table with this script:
create table ADDRESS (
id INT(11) NOT NULL AUTO_INCREMENT,
street VARCHAR(250) NOT NULL,
city VARCHAR(100) NOT NULL,
country VARCHAR(100) NOT NULL,
PRIMARY KEY (id)
);
create table STUDENT (
id INT(11) NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
entering_date DATE NOT NULL,
nationality TEXT NOT NULL,
code VARCHAR(30) NOT NULL,
address_id INT(11) NOT NULL,
PRIMARY KEY (id),
CONSTRAINT student_address FOREIGN KEY (address_id) REFERENCES ADDRESS (id)
);
Here is the entities with the above tables
#Entity
#Table(name = "STUDENT")
public class Student implements Serializable {
private static final long serialVersionUID = 6832006422622219737L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
}
#Entity
#Table(name = "ADDRESS")
public class Address {
#Id #GeneratedValue
#Column(name = "ID")
private long id;
}
The problem was resolved.
Notice: The primary key must be set to AUTO_INCREMENT
Another suggestion is to check that you use a valid type for the auto-generated field. Remember that it doesn't work with String, but it works with Long:
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
public Long id;
#Constraints.Required
public String contents;
The above syntax worked for generating tables in MySQL using Hibernate as a JPA 2.0 provider.
Just add not-null constraint
I had the same problem. I just added not-null constraint in xml mapping. It worked
<set name="phone" cascade="all" lazy="false" >
<key column="id" not-null="true" />
<one-to-many class="com.practice.phone"/>
</set>
Maybe that is the problem with the table schema. drop the table and rerun the application.
In addition to what is mentioned above, do not forget while creating sql table to make the AUTO INCREMENT as in this example
CREATE TABLE MY_SQL_TABLE (
USER_ID INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY,
FNAME VARCHAR(50) NOT NULL,
LNAME VARCHAR(20) NOT NULL,
EMAIL VARCHAR(50) NOT NULL
);
When your field is not nullable it requires a default value to be specified on table creation. Recreate a table with AUTO_INCREMENT properly initialized so DB will not require default value since it will generate it by itself and never put NULL there.
CREATE TABLE Persons (
Personid int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Age int,
PRIMARY KEY (Personid)
);
https://www.w3schools.com/sql/sql_autoincrement.asp
I solved it changuing #GeneratedValue(strategy = GenerationType.IDENTITY) by #GeneratedValue(strategy = GenerationType.AUTO)
By the way i didn't need to put it to create, just:
spring.jpa.hibernate.ddl-auto: update
Please check whether the Default value for the column id in particular table.if not make it as default
I had the same problem. I was using a join table and all I had with a row id field and two foreign keys. I don't know the exact caused but I did the following
Upgraded MySQL to community 5.5.13
Rename the class and table
Make sure I had hashcode and equals methods
#Entity
#Table(name = "USERGROUP")
public class UserGroupBean implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name = "USERGROUP_ID")
private Long usergroup_id;
#Column(name = "USER_ID")
private Long user_id;
#Column(name = "GROUP_ID")
private Long group_id;
The same exception was thrown if a DB table had an old unremoved column.
For example:
attribute_id NOT NULL BIGINT(20), and attributeId NOT NULL BIGINT(20),
After removing the not used attribute, in my case contractId, the problem was resolved.
This happened to me with a #ManyToMany relationship. I had annotated one of the fields in the relationship with #JoinTable, I removed that and used the mappedBy attribute on #ManyToMany instead.
I tried the code and in my case the code below solve the issue. I had not settled the schema properly
#Entity
#Table(name="table"
,catalog="databasename"
)
Please try to add ,catalog="databasename" the same as I did.
,catalog="databasename"
In my case,
I altered that offending tables and the field "id" in question I made it AUTO_INCREMENT, I still need to figure out why on deployment time it was not making it "AUTO_INCREMENT" so that I have to do it by myself!
What about this:
<set name="fieldName" cascade="all">
<key column="id" not-null="true" />
<one-to-many class="com.yourClass"/>
</set>
I hope it helps you.
Try to change Long object type to long primitive type (if using primitives is ok for you).
I had the same problem and changing type helped me.
I had this issue, by mistake I had placed #Transient annotation above that particular attribute. In my case this error make sense.
"Field 'id' doesn't have a default value" because you didn't declare GenerationType.IDENTITY in GeneratedValue Annotation.
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
This issue is because sometimes you need to again update/create the database or sometimes if you have added the field in db table but not not entity class then it can not insert any null value or zero so this error came.
So check both side.Db and Entity class.
i have got such error in GCP cloud sql when model field didn't match correct table field in db.
Example:
when in model field is fieldName
table in db should have field field_name
Fixing table field name helped me.
I solved similar problem, when I altered the database column type , and did not add auto_increment. After adding back auto_increment in the alter table command (as in my original table creation) it worked
In my case I have not added the below property in my application.properties file:
spring.jpa.database-platform = org.hibernate.dialect.MySQL5InnoDBDialect
And added the following annotation to my entity class's Id column:
#GeneratedValue(strategy = GenerationType.IDENTITY)
And after adding this I have also drop my table manually from datatbase and run my project again that creates a new table with all default constraints for the table.
To delete just delete your schema is a really bad suggestion. There is a problem and it's best to find and fix it.
In my case I was using Envers this creates an Audit table for when entries are updated. But this audit table does not get updated itself it seems when the schema updates (At least not ID and it's relationships)
I just eddited the audit tables offending property and done. Everything back to normal.
To find what the issue is turn the following properties on in application.properties file
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
This will show you what SQL it is trying to executing and hopefully it will provide clarity on real issue.
Add a method hashCode() to your Entity Bean Class and retry it

Categories