Hibernate Auto-Increment not working - java

I have a column in my DB that is set with Identity(1,1) and I can't get hibernate annotations to work for it. I get errors when I try to create a new record.
In my entity I have the following.
#Entity
#Table(schema="dbo", name="MemberSelectedOptions")
public class MemberSelectedOption extends BampiEntity implements Serializable {
#Embeddable
public static class MSOPK implements Serializable {
private static final long serialVersionUID = 1L;
#Column(name="SourceApplication")
String sourceApplication;
#Column(name="GroupId")
String groupId;
#Column(name="MemberId")
String memberId;
#Column(name="OptionId")
int optionId;
#GeneratedValue(strategy=GenerationType.IDENTITY, generator="native")
#Column(name="SeqNo", unique=true, nullable=false)
BigDecimal seqNo;
//Getters and setters here...
}
private static final long serialVersionUID = 1L;
#EmbeddedId
MSOPK pk = new MSOPK();
#Column(name="OptionStatusCd")
String optionStatusCd;
#Column(name="EffectiveDate")
Date effectiveDate;
#Column(name="TermDate")
Date termDate;
#Column(name="SelectionStatusDate")
Date selectionStatusDate;
#Column(name="SysLstUpdtUserId")
String sysLstUpdtUserId = Globals.WS_USER_ID;;
#Column(name="SysLstTrxDtm")
Date sysLstTrxDtm = new Date();
#OneToMany(mappedBy="option")
List<MemberSelectedVariable> variables =
new ArrayList<MemberSelectedVariable>();
//More Getters and setters here...
}
But when I try to add a new record I get the following error.
Cannot insert explicit value for identity column in table 'MemberSelectedOptions' when IDENTITY_INSERT is set to OFF. I don't want to set IDENTIY_INSERT to ON because I want the identity column in the db to manage the values.
The SQL that is run is the following; where you can clearly see the insert.
insert into dbo.MemberSelectedOptions
(OptionStatusCd,
EffectiveDate,
TermDate,
SelectionStatusDate,
SysLstUpdtUserId,
SysLstTrxDtm,
SourceApplication,
GroupId,
MemberId,
OptionId,
SeqNo)
values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
What am I missing?

When you use #Embeddable or #EmbeddedId, the primary key values are supposed to be provided by the application (i.e. made up of non generated values). Your #GeneratedValue annotation is just ignored.

this combination works great for me:
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)

Here is the example to do it
#Id
#Column(name = "col_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long colId;

Possible you need to mark your field with #id and not specify generator property.
As showed in Hibernate Annotation - 2.2.3.1. Generating the identifier property, the next example uses the identity generator:
#Id #GeneratedValue(strategy=GenerationType.IDENTITY)
public Long getId() { ... }

You can't use Generators on composite keys

You can't do it with
Create table manually and everything will be ok.
CREATE TABLE `Forum` (
`name` varchar(255) NOT NULL,
`id` int(11) NOT NULL AUTO_INCREMENT,
`body` varchar(500) DEFAULT NULL,
PRIMARY KEY (name,`id`),
UNIQUE KEY `id` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin2
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.EmbeddedId;
import javax.persistence.Entity;
#Entity
public class Forum implements Serializable {
#EmbeddedId
private ForumCompositePK forumPK;
/**
*
*/
private static final long serialVersionUID = 7070007885798411858L;
#Column(length = 500)
String body;
public String getBody() {
return body;
}
public void setBody(String body) {
this.body = body;
}
public void setForumPK(ForumCompositePK forumPK) {
this.forumPK = forumPK;
}
public ForumCompositePK getForumPK() {
return forumPK;
}
}
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Embeddable;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
#Embeddable
public class ForumCompositePK implements Serializable {
/**
*
*/
private static final long serialVersionUID = 8277531190469885913L;
#Column(unique=true,updatable=false,insertable=false)
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer id;
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
}

Related

org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): com.app.entites.LDetails

I tried many time to insert id value in my table using below code, but it always throwing org.hibernate.id.IdentifierGenerationException: ids for this class must be manually assigned before calling save(): com.app.entites.LDetails
following is the code in entity class
#Column(name="LID")
#GenericGenerator(name="generatedId", strategy="com.app.common.IdGenerator")
#GeneratedValue(generator="generatedId", strategy=GenerationType.SEQUENCE)
#NotNull
private String lId;
i have implemented id generator using IdentifierGenerator as below
public class IdGenerator implements IdentifierGenerator{
private static String id;
#Override
public Serializable generate(SharedSessionContractImplementor session, Object object) throws HibernateException {
Connection con = session.connection();
try {
Statement statement = con.createStatement();
ResultSet rs = statement.executeQuery("select count(ID) from L_DETAILS");
if(rs.next()) {
int i = rs.getInt(1)+1;
this.id="ll"+i;
System.out.println("generated id is "+id);
return "l"+i;
}
}catch(SQLException e) {
e.printStackTrace();
}
return null;
}
}
Use the following approach for Auto-Id generation of Primary key in your entity class :-
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Entity;
#Entity
#Table(name = "your_table_name")
public class YourEntityClass{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private long id;
//other column names
// setter & getter methods
}
After this, whenever you're saving a new record in your table you don't have to generate a new id
You have forgotten to add the #Id annotation on top. The fact you have added the #GeneratedValue annotation does not mean you can spare the #Id annotation. You still need it.

Spring Boot org.hibernate.exception.ConstraintViolationException

I am getting .ConstraintViolationException when I try to persist data using the POST REST API.
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "id" violates not-null constraint
Detail: Failing row contains (null, John Doe, How are you?, I am fine).
I am using #GeneratedValue(strategy = GenerationType.IDENTITY) to auto generate "id" from Hibernate and I am not sure If I am missing any configuration in application.properties. I am using Postgres db.
I tried using GenerationType.AUTO and I was getting hibernate_sequence missing error from postgres.
Thanks!
POST REST API input using Postman
{
"personName": "John Doe",
"question": "How are you?",
"response": "I am fine"
}
questionnaries.sql
CREATE TABLE questionnaries(
id BIGINT PRIMARY KEY,
personName VARCHAR(255) NOT NULL,
question VARCHAR(255) NOT NULL,
response VARCHAR(255) NOT NULL
);
Questionnarie.java #
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
#Entity
#Table(name = "questionnaries")
public class Questionnarie {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private Long id;
#Column(name = "personname")
#NotNull
private String personname;
#Column(name = "question")
#NotNull
private String question;
#Column(name = "response")
#NotNull
private String response;
public Questionnarie() {}
public Questionnarie(#NotNull String personname, #NotNull String question, #NotNull String response) {
super();
this.personname = personname;
this.question = question;
this.response = response;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getPersonname() {
return personname;
}
public void setPersonname(String personname) {
this.personname = personname;
}
public String getQuestion() {
return question;
}
public void setQuestion(String question) {
this.question = question;
}
public String getResponse() {
return response;
}
public void setResponse(String response) {
this.response = response;
}}
application.properties
# ===============================
# = DATA SOURCE
# ===============================
# Set here configurations for the database connection
spring.datasource.jndi-name=java:jboss/datasources/test_data_source
# ===============================
# = JPA / HIBERNATE
# ===============================
# Show or not log for each sql query
spring.jpa.show-sql=true
# Allows Hibernate to generate SQL optimized for a particular DBMS
spring.jpa.properties.hibernate.dialect=org.hibernate.dialect.PostgreSQLDialect
That means your database supports sequences for primary key values. So in your case, you will have to create a Database sequence and then use #GeneratedValue(strategy=GenerationType.AUTO) or #GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq")
#SequenceGenerator(name="seq", sequenceName = "db_seq_name") to generate values for primary key fields.
Also make sure that you add SERIAL to your SQL, so that it looks like: id SERIAL PRIMARY KEY
See the PostgreSQL documentation for the serial data types.
Change your script to:
CREATE TABLE questionnaries(
id BIGINT PRIMARY KEY GENERATED BY DEFAULT AS IDENTITY,
personName VARCHAR(255) NOT NULL,
question VARCHAR(255) NOT NULL,
response VARCHAR(255) NOT NULL
);

hibernate criteria query creating multiple sql

I am facing a very strange issue with hibernate criteria in my application. Below mentioned in the snippet from my source code.
Entity Class
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import org.hibernate.annotations.Cache;
import org.hibernate.annotations.CacheConcurrencyStrategy;
#Entity
#Table(name = "AIRPORT")
#Cache(usage = CacheConcurrencyStrategy.READ_ONLY)
public class Airport implements Serializable {
private static final long serialVersionUID = -7120581694566566178L;
private Long id;
private String countryCode;
private String countryName;
private String cityCode;
private String cityName;
private String airportCode;
private String airportName;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ID", unique = true)
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#Column(name = "COUNTRY_NAME")
public String getCountryName() {
return countryName;
}
public void setCountryName(String countryName) {
this.countryName = countryName;
}
#Column(name = "COUNTRY_CODE", length = 10)
public String getCountryCode() {
return countryCode;
}
public void setCountryCode(String countryCode) {
this.countryCode = countryCode;
}
#Column(name = "CITY_CODE", length = 25)
public String getCityCode() {
return cityCode;
}
public void setCityCode(String cityCode) {
this.cityCode = cityCode;
}
#Column(name = "CITY_NAME")
public String getCityName() {
return cityName;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
#Column(name = "AIRPORT_CODE", unique = true, length = 10)
public String getAirportCode() {
return airportCode;
}
public void setAirportCode(String airportCode) {
this.airportCode = airportCode;
}
#Column(name = "AIRPORT_NAME")
public String getAirportName() {
return airportName;
}
public void setAirportName(String airportName) {
this.airportName = airportName;
}
}
DAO Class
Criteria criteria = getSession().createCriteria(getTemplateClass());
criteria.addOrder(Order.asc("countryCode"));
criteria.addOrder(Order.asc("cityCode"));
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
criteria.setCacheable(true);
return (List<Airport>) criteria.list();
Generated SQL when starting application and querying result
Hibernate: select this_.ID as ID1_12_0_, this_.AIRPORT_CODE as AIRPORT_2_12_0_, this_.AIRPORT_NAME as AIRPORT_3_12_0_, this_.CITY_CODE as CITY_COD4_12_0_, this_.CITY_NAME as CITY_NAM5_12_0_, this_.COUNTRY_CODE as COUNTRY_6_12_0_, this_.COUNTRY_NAME as COUNTRY_7_12_0_ from AIRPORT this_ order by this_.COUNTRY_CODE asc, this_.CITY_CODE asc
If I call same code again and suppose I have 1000 airports list then it executes below query for 1000 times. This behavior is quite strange.
Hibernate: select airport0_.ID as ID1_12_0_, airport0_.AIRPORT_CODE as AIRPORT_2_12_0_, airport0_.AIRPORT_NAME as AIRPORT_3_12_0_, airport0_.CITY_CODE as CITY_COD4_12_0_, airport0_.CITY_NAME as CITY_NAM5_12_0_, airport0_.COUNTRY_CODE as COUNTRY_6_12_0_, airport0_.COUNTRY_NAME as COUNTRY_7_12_0_ from AIRPORT airport0_ where airport0_.ID=?
Hibernate: select airport0_.ID as ID1_12_0_, airport0_.AIRPORT_CODE as AIRPORT_2_12_0_, airport0_.AIRPORT_NAME as AIRPORT_3_12_0_, airport0_.CITY_CODE as CITY_COD4_12_0_, airport0_.CITY_NAME as CITY_NAM5_12_0_, airport0_.COUNTRY_CODE as COUNTRY_6_12_0_, airport0_.COUNTRY_NAME as COUNTRY_7_12_0_ from AIRPORT airport0_ where airport0_.ID=?
Hibernate: select airport0_.ID as ID1_12_0_, airport0_.AIRPORT_CODE as AIRPORT_2_12_0_, airport0_.AIRPORT_NAME as AIRPORT_3_12_0_, airport0_.CITY_CODE as CITY_COD4_12_0_, airport0_.CITY_NAME as CITY_NAM5_12_0_, airport0_.COUNTRY_CODE as COUNTRY_6_12_0_, airport0_.COUNTRY_NAME as COUNTRY_7_12_0_ from AIRPORT airport0_ where airport0_.ID=?
........
........
Even I am using ehcache and even the below line in my criteria.
criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
Any help would be greatly appreciated.
I can think of a few different reasons why this might be occuring:
Your entity has an association defined in it that is configured to eager join by default and you have also specified that the association use FetchMode.SELECT. (This is known as the N+1 Problem)
While the transaction is still open, you are interacting with an association of each Airport object that is set to lazy load. By interacting, I mean, you are using a getter to access the relation, forcing Hibernate to deproxy the associated entity. Since the deproxying is occurring with the transaction still open and the associated entity has not yet been loaded, Hibernate automatically fetches the association for you.
You have written your Airport entity's hashcode or equals methods to use a property of an association that is not eagerly joined and forces hibernate to deproxy, and thus fetch the unloaded entity, while within the transaction.

null not allowed for column in join table with one entity extending another

I have a situation where I have an entity VCenterDistributedVirtualPortgroup which extends VCenterNetwork and both entities are in a OneToMany relationship inside the entity VCenterFolder. I'm getting the following error:
Caused by: org.h2.jdbc.JdbcSQLException: NULL not allowed for column "NETWORK_TYPE"; SQL statement:
insert into folder_network (folder_type, folder_val, distributedVirtualPortgroups_type, distributedVirtualPortgroups_val) values (?, ?, ?, ?) [23502-182]
VCenterNetwork:
#Entity
#Embeddable
#Table(name="network")
#DiscriminatorColumn(name="discriminator")
#DiscriminatorValue("Network")
public class VCenterNetwork
{
#Transient
private Network network;
#Transient
private static Map<MOR, VCenterNetwork> networkMap = new TreeMap<MOR, VCenterNetwork>();
#EmbeddedId
private MOR id;
public MOR getId() {return this.id;}
public void setId(MOR id) {this.id = id;}
...
}
VCenterDistributedVirtualPortgroup:
#Entity
#Table(name="distributedvirtualportgroup")
#DiscriminatorColumn(name="discriminator")
#DiscriminatorValue("DistributedVirtualPortgroup")
public class VCenterDistributedVirtualPortgroup extends VCenterNetwork
{
#Transient
private DistributedVirtualPortgroup distributedVirtualPortgroup;
#Transient
private static Map<MOR, VCenterDistributedVirtualPortgroup> distributedVirtualPortgroupMap = new TreeMap<MOR, VCenterDistributedVirtualPortgroup>();
...
}
VCenterFolder:
#Entity
#Table(name="folder")
public class VCenterFolder
{
#Transient
private Folder folder;
#Transient
private static Map<MOR, VCenterFolder> folderMap = new TreeMap<MOR, VCenterFolder>();
#EmbeddedId
private MOR id;
public MOR getId() {return this.id;}
public void setId(MOR id) {this.id = id;}
#Embedded
#OneToMany(cascade=CascadeType.ALL)
private List<VCenterNetwork> network = new ArrayList<VCenterNetwork>();
public List<VCenterNetwork> getNetwork() {return this.network;}
public void getvirtualNetwork(List<VCenterNetwork> network) {this.network = network;}
#Embedded
#OneToMany(cascade=CascadeType.ALL)
private List<VCenterDistributedVirtualPortgroup> distributedVirtualPortgroups = new ArrayList<VCenterDistributedVirtualPortgroup>();
public List<VCenterDistributedVirtualPortgroup> getDistributedVirtualPortgroups() {return this.distributedVirtualPortgroups;}
public void setDistributedVirtualPortgroups(List<VCenterDistributedVirtualPortgroup> distributedVirtualPortgroups){this.distributedVirtualPortgroups = distributedVirtualPortgroups;}
....
}
This results in a join table that looks like the following:
FOLDER_NETWORK
FOLDER_TYPE - VARCHAR(255) NOT NULL
FOLDER_VAL - VARCHAR(255) NOT NULL
NETWORK_TYPE - VARCHAR(255) NOT NULL
NETWORK_VAL - VARCHAR(255) NOT NULL
DISTRIBUTEDVIRTUALPORTGROUP_TYPE - VARCHAR(255) NOT NULL
DISTRIBUTEDVIRTUALPORTGROUP_TYPE - VARCHAR(255) NOT NULL
I'm new to JPA, but my guess is that a join table is needed for both VCenterFolder-VCenterNetwork and VCenterFolder-VCenterDistributedVirtualPortgroup, but since VCenterDistributedVirtualPortgroup extends VCenterNetwork, it's building one join table with both relations but using a different type/val pair for each relation. I would assume that only one pair will be used at a time with the other being null. That seems to be a problem. It would seem to me that the fields should either be nullable or the two sets of type/val pairs should be merged into one.
I assume there is some way round this, but I sure don't know what it is.
MOR happens to have the members type & val, thus the names in the join table.
I solved the problem by adding the folloing JoinTable on both the network and distributedVirtualPortgroups fields:
#JoinTable
(
name="FOLDER_NETWORK",
joinColumns= {#JoinColumn(name="TYPE", referencedColumnName="TYPE"), #JoinColumn(name="VAL", referencedColumnName="VAL")},
inverseJoinColumns= {#JoinColumn(name="NETWORK_TYPE", referencedColumnName="TYPE"), #JoinColumn(name="NETWORK_VAL", referencedColumnName="VAL")}
)

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