springboot postgresql create data without sequence - spring

jdk1.8.0_202.jdk
psql -V 12.1
There is a problem creating and saving a postgresql object. When trying to create the object's id value is empty. I don't know why. Please tell me what to check.
package com.interpark.lab.tour.geolocation.model;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.vladmihalcea.hibernate.type.json.JsonBinaryType;
import lombok.Data;
import org.hibernate.annotations.GenericGenerator;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
import org.hibernate.annotations.TypeDefs;
import org.locationtech.jts.geom.Geometry;
import javax.persistence.*;
import java.io.Serializable;
import java.util.HashMap;
import java.util.List;
#Data
#Entity
#Table(name = "expedia_region_union")
#JsonInclude(JsonInclude.Include.NON_NULL)
#TypeDefs({
#TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
})
public class ExpediaRegionUnion {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column( columnDefinition = "uuid", updatable = false )
private String regionId;
#Column(columnDefinition = "region_type")
private String regionType;
#Column(columnDefinition = "region_name")
private String regionName;
#Column(columnDefinition = "region_name_full")
private String regionNameFull;
#Transient
private String regionDescriptor;
#Column(columnDefinition = "country_code")
private String countryCode;
#Column(columnDefinition = "coordinates")
private String coordinates;
#Column(columnDefinition = "center_longitude")
private String centerLongitude;
#Column(columnDefinition = "center_latitude")
private String centerLatitude;
#Type(type = "jsonb")
#Column(columnDefinition = "continent")
private HashMap continent;
#Type(type = "jsonb")
#Column(columnDefinition = "add_continent")
private List addContinent;
#Column(columnDefinition = "ancestors")
private String ancestors;
#Column(columnDefinition = "descendants")
private String descendants;
#Column(columnDefinition = "region_name_kr")
private String regionNameKr;
#Column(columnDefinition = "region_name_full_kr")
private String regionNameFullKr;
#Transient
#Column(columnDefinition = "parent_city_flag")
private String parentCityFlag;
#Transient
#Column(columnDefinition = "parent_city")
private String parentCity;
#Transient
#Column(columnDefinition = "boundaries")
private Geometry boundaries;
#Type(type = "jsonb")
#Column(name = "country")
private HashMap country;
#Column(columnDefinition = "city_ancestors")
private String cityAncestors;
#Type(type = "jsonb")
#Column(columnDefinition = "ancestors_info")
private List ancestorsInfo;
#Column(columnDefinition = "synonym")
private String synonym;
#Column(columnDefinition = "coordinates_nearby")
private String coordinatesNearby;
#Column(columnDefinition = "coordinates_nearby_auto")
private String coordinatesNearbyAuto;
#Type(type = "jsonb")
#Column(columnDefinition = "nearest_airport")
private HashMap nearestAirport;
#Type(type = "jsonb")
#Column(columnDefinition = "nearest_airport_in_country")
private HashMap nearestAirportInCountry;
#Type(type = "jsonb")
#Column(columnDefinition = "codes")
private HashMap codes;
#Type(type = "jsonb")
#Column(columnDefinition = "airport")
private List airport;
#Transient
private String countryCodeLower;
#Transient
#Type(type = "boolean")
#Column(columnDefinition = "display")
private Boolean display;
#Type(type = "jsonb")
#Column(columnDefinition = "jsonn")
private HashMap jsonn;
#Column(name = "jsonn_updated", columnDefinition = "BOOLEAN")
private Boolean jsonnUpdated;
#Column(name = "in_use", columnDefinition = "BOOLEAN")
private Boolean inUse;
#Column(name = "source_time")
private String sourceTime;
#Column(name = "city_home_flag")
private String cityHomeFlag;
#Column(columnDefinition = "source_from")
private String sourceFrom;
#Column(columnDefinition = "region_code")
private String regionCode;
#Column(columnDefinition = "sub_class")
private String subClass;
#Transient
private boolean selected;
}
I don't know why but, like this, When inserting, the region_id value is empty.
Hibernate: insert into expedia_region_union (add_continent, airport, ancestors, ancestors_info, center_latitude, center_longitude, city_ancestors, city_home_flag, codes, continent, coordinates, coordinates_nearby, coordinates_nearby_auto, country, country_code, descendants, in_use, jsonn, jsonn_updated, nearest_airport, nearest_airport_in_country, region_code, region_name, region_name_full, region_name_full_kr, region_name_kr, region_type, source_from, source_time, sub_class, synonym) values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
What I don't understand is, as you can see below, it's made and put in like other things.
public void save(Map paramBean) throws JsonProcessingException {
ExpediaRegionUnion insert = new ExpediaRegionUnion();
insert.setRegionId("INTERPARK" + System.currentTimeMillis());
insert.setRegionType(paramBean.get("regionType") + "");
insert.setRegionName(paramBean.get("regionName") + "");
Can't I create an object without using auto increment? Because I thought I didn't need a sequence. Please let me know if I am wrong.
Hibernate: select currval('expedia_region_union_region_id_seq')
SQL Error: 0, SQLState: 42P01
오류: "expedia_region_union_region_id_seq" 이름의 릴레이션(relation)이 없습니다
Why hibernate wants sequences that I don't even need?

I delegated primary key generation to the database using GenerationType.IDENTITY. But I shouldn't have done that. Because the data in my table already created were not auto-incremented numeric ids. They were based on the Openstreetmap's local id. I write answers for such people.
as #Olivier Depriester says, using GenerationType.AUTO works well. I followed this article.
https://vladmihalcea.com/uuid-identifier-jpa-hibernate/
This is how I create uuid directly through a class in springboot without leaving pk creation in the database.
in psql, you type this.
CREATE EXTENSION IF NOT EXISTS "uuid-ossp";
that extension makes you uuid-generator.
you just copy this. Place the files in the appropriate directory.
public class PostgreSQLUUIDGenerationStrategy
implements UUIDGenerationStrategy {
#Override
public int getGeneratedVersion() {
return 4;
}
#Override
public UUID generateUUID(
SharedSessionContractImplementor session) {
return ((Session) session).doReturningWork(connection -> {
try(
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(
"select uuid_generate_v4()"
)
) {
while (resultSet.next()) {
return (UUID) resultSet.getObject(1);
}
}
throw new IllegalArgumentException("Can't fetch a new UUID");
});
}
}
in your entity class, you change configuration.
#Id
#GeneratedValue(
strategy = GenerationType.AUTO,
generator = "pg-uuid"
)
#GenericGenerator(
name = "pg-uuid",
strategy = "uuid2",
parameters = #org.hibernate.annotations.Parameter(
name = "uuid_gen_strategy_class",
value = "whatever.your.package.PostgresQLUUIDGenerationUtils"
)
)
private String regionId;
and this is mine.

Related

JPA-Spring Repository #OneToOne save/create new child object when the parent object already exists is not working

I got this strange issue when I tried to save a child object of a #OneToOne relationship when the parent object it already exist. Something like that:
Please find below the description of the problem.
I'm using spring-boot with JPA
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.6.3</version>
<relativePath /> <!-- lookup parent from repository -->
</parent>
The DB schema diagram looks like
The spring implementation looks like that:
AND THE PROBLEM (the cardnumber, even is not null, I check debugging) it is saved NULL (??!!)
Also please note a trick I used to make the save working. I have to manually check (into DB schema) as not null (uncheck the NN of the cardnumber column on fcrd_clients - child table).
Additionally I'll attach the source code to make easy the code modifications suggestions:
PARENT OBJECT source code
#Entity(name = "FcrdRandcrdnr")
#Table(name = "fcrd_randcrdnr")
public class FcrdRandcrdnr {
#Id
#Column(name = "CARDNUMBER", length = 15)
private Long cardnumber;
#Column(name = "FLG_CRDNRISSUED", length = 1)
private int flgCrdnrissued;
#Column(name = "DT_CREATE")
private Timestamp dtCreate;
#Temporal(TemporalType.TIMESTAMP)
#Column(name = "DT_UPDATE")
private Date dtUpdate;
public FcrdRandcrdnr() {
}
...
}
CHILD OBJECT source code
import javax.persistence.CascadeType;
...
import javax.persistence.OneToOne;
import com.fasterxml.jackson.annotation.JsonIgnore;
#Entity(name = "FcrdClient")
#Table(name = "fcrd_clients")
public class FcrdClient {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "IDCLIENT")
private Long idClient;
#OneToOne
#MapsId("CARDNUMBER")
#JoinColumn(name = "CARDNUMBER",
foreignKey = #ForeignKey(name = "FK_1TO1_P_RANDCRDNR_C_CLIENT"))
#JsonIgnore
private FcrdRandcrdnr fcrdRandcrdnr;
#OneToMany(mappedBy = "fcrdClient", cascade = CascadeType.ALL, orphanRemoval = true)
#JsonIgnore
private List<FcrdBarcodecard> fcrdBarcodecards = new ArrayList<>();
#Column(name = "APP_USE_COUNTER", length = 9)
private int appUseCounter;
#Column(name = "APP_VERSION", length = 20)
private String appVersion;
#Column(name = "DT_CREATE")
private Timestamp dtCreate;
#Column(name = "DT_MODIFIED")
private Timestamp dtModified;
#Column(name = "EMAIL", length = 100)
private String email;
#Column(name = "FACEBOOKID", length = 35)
private String facebookid;
#Column(name = "FIRSTNAME", length = 20)
private String firstname;
#Lob
#Column(name = "GCM_REGID")
private String gcmRegid;
#Column(name = "LASTNAME", length = 20)
private String lastname;
#Column(name = "LOGIN_NAME", length = 15)
private String loginName;
#Column(name = "LOGIN_PASSWORD", length = 520)
private String loginPassword;
#Column(name = "LOGIN_TYPE", length = 50)
private String loginType;
#Column(name = "PHONE_MODEL", length = 50)
private String phoneModel;
#Column(name = "PLATFORM", length = 100)
private String platform;
#Column(name = "SEND_PUBKEY", length = 3)
private int sendPubkey;
#Column(name = "SYSTEM_LANGUAGE", length = 10)
private String systemLanguage;
#Column(name = "TOKEN_PKEY", length = 4000)
private String tokenPkey;
public FcrdClient() {
}
...
public void addBarcodecard(FcrdBarcodecard fcrdBarcodecard) {
fcrdBarcodecards.add(fcrdBarcodecard);
fcrdBarcodecard.setFcrdClient(this);
}
public void removeBarcodecard(FcrdBarcodecard fcrdBarcodecard) {
fcrdBarcodecards.remove(fcrdBarcodecard);
fcrdBarcodecard.setFcrdClient(null);
}
}
THE SERVICE source code
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
#Service
public class FcrdClientService {
#Autowired
FcrdClientRepository fcrdClientRepository;
#Autowired
FcrdRandcrdnrRepository fcrdRandcrdnrRepository;
public List<FcrdClient> findAll(){
return fcrdClientRepository.findAll();
}
/*
* Issue a new card for client
*/
public FcrdClient save(FcrdClient fcrdClient) {
// fetch a card from the table fcrd_randcrdnr
// the cards was randomly created by other mechanism
FcrdRandcrdnr fcrdRandcrdnr
= fcrdRandcrdnrRepository.findByFlgCrdnrissued(0).get(0);
// create new client
FcrdClient client = new FcrdClient();
client.setAppUseCounter(fcrdClient.getAppUseCounter());
client.setFirstname(fcrdClient.getFirstname());
// add the card to the new client
client.setFcrdRandcrdnr(fcrdRandcrdnr);
// save the client to the DB (fcrd_clients)
return fcrdClientRepository.save(client);
}
}

I am not getting unique column using hibernate , for postgresql db

#Entity
#Table(uniqueConstraints={#UniqueConstraint(columnNames={"catgoryId","applcationNo"})})
I tried this explicitly #table
and unique , //but not getting result.
public class DmsDocDetailPojo {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(columnDefinition = "serial")
private Long dmsDocId;
#Column
private String stateCode="AI";
#Column(name = "applicationNo", unique = true,nullable=false)
#NotNull
private String applcationNo;
#Column(name = "catgoryId", unique = true,nullable=false)
private String catgoryId;
#CreationTimestamp
#Column( nullable = false, updatable=false)
private Date doc_uploaded_dt;
#UpdateTimestamp
private Date doc_updated_dt;
#Column(name = "document_file", columnDefinition = "BYTEA")
private byte[] document_file;
#Column
private String fileName;
#Column
private Integer fileSize;
}
check your database primary key it should be an auto increment

Insert data into three table by using JPA #onetomany and #manytoone annotation

I am trying to insert data into three different tables by using JPA Repository with spring boot application. for this purpose i used #onetomany and #manytoone annotation in these three classes:
HouseHold
OwnerDetails
HouseHoldMembers
but when i am trying to insert i am getting the following error.
Hibernate:
select
*
from
household
where
sl_no = ?
2019-10-16 12:24:46.622 INFO 19380 --- [nio-8080-exec-1] c.o.a.a.s.FormServiceImpl : FormServiceImpl saveHouseDetailsWithBase64() is invoked : 234546674
Hibernate:
select
nextval ('house_id_seq')
Hibernate:
select
nextval ('owner_id_seq')
Hibernate:
select
nextval ('mem_id_seq')
Hibernate:
insert
into
household
(area, audio, district, east, gp_name, grid_no, house_dimension, house_photo, id, id_number, id_photo, Khatha_no, latitute, locality_name, longitute, map_photo, north, phone_num, pin, prop_details, prop_type, rent_amount, road_name, sl_no, south, servey_date, survey_no, surveyor_name, taluk, tenant, toilet_available, total_members, vacant_port, village_name, water_facility, west, hid)
values
(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
Hibernate:
insert
into
ownerdetails
(age, education, gender, hid, idname, idnumber, name, oid)
values
(?, ?, ?, ?, ?, ?, ?, ?)
2019-10-16 12:24:46.832 WARN 19380 --- [nio-8080-exec-1] o.h.e.j.s.SqlExceptionHelper : SQL Error: 0, SQLState: 23502
2019-10-16 12:24:46.832 ERROR 19380 --- [nio-8080-exec-1] o.h.e.j.s.SqlExceptionHelper : ERROR: null value in column "hid" violates not-null constraint
Detail: Failing row contains (1, 10, education, male, adhaarcard1, 23424242343, name, null).
2019-10-16 12:24:46.840 ERROR 19380 --- [nio-8080-exec-1] o.h.i.ExceptionMapperStandardImpl : HHH000346: Error during managed flush [org.hibernate.exception.ConstraintViolationException: could not execute statement]
could not execute statement; SQL [n/a]; constraint [hid]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
2019-10-16 12:24:46.848 ERROR 19380 --- [nio-8080-exec-1] c.o.a.a.s.FormServiceImpl : could not execute statement; SQL [n/a]; constraint [hid]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
2019-10-16 12:24:46.849 INFO 19380 --- [nio-8080-exec-1] c.o.a.a.c.FormDataController : FormDataController saveHouseHold() request is completed.
HouseHold.java
#Entity
#Table(name = "household")
public class HouseHold implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "house_id_seq")
#SequenceGenerator(name = "house_id_seq", sequenceName = "house_id_seq", allocationSize = 1)
#Column(name = "hid")
private Long hid;
#NotNull
#Size(max = 100)
#Column(name = "district")
private String district;
#NotNull
#Size(max = 100)
#Column(name = "taluk")
private String taluk;
#NotNull
#Size(max = 100)
#Column(name = "village_name")
private String villageName;
#NotNull
#Column(name = "sl_no")
private Long slNo;
#NotNull
#Size(max = 100)
#Column(name = "Khatha_no")
private String khathaNo;
#NotNull
#Size(max = 50)
#Column(name = "locality_name")
private String localityName;
#NotNull
#Size(max = 50)
#Column(name = "prop_details")
private String propertyDetails;
#NotNull
#Size(max = 50)
#Column(name = "tenant")
private String tenant;
#NotNull
#Size(max = 200)
#Column(name = "house_dimension")
private String houseDimension;
#NotNull
#Size(max = 50)
#Column(name = "east")
private String east;
#NotNull
#Size(max = 50)
#Column(name = "west")
private String west;
#NotNull
#Size(max = 50)
#Column(name = "north")
private String north;
#NotNull
#Size(max = 50)
#Column(name = "south")
private String south;
#NotNull
#Digits(integer = 6, fraction = 2)
#Column(name = "rent_amount")
private BigDecimal rentAmount;
#NotNull
#Size(max = 100)
#Column(name = "vacant_port")
private String vacantPort;
#NotNull
#Size(max = 100)
#Column(name = "gp_name")
private String gpName;
#NotNull
#Size(max = 100)
#Column(name = "prop_type")
private String propertyType;
#NotNull
#Size(max = 100)
#Column(name = "road_name")
private String roadName;
#NotNull
#Column(name = "pin")
private Long pin;
#NotNull
#Column(name = "survey_no")
private Long surveyNo;
#NotNull
#Size(max = 250)
#Column(name = "grid_no")
private String gridNo;
#NotNull
#Size(max = 250)
#Column(name = "id_number")
private String idNumber;
#NotNull
#Size(max = 100)
#Column(name = "area")
private String area;
#NotNull
#Size(max = 3)
#Column(name = "toilet_available")
private String toiletAvailable;
#NotNull
#Size(max = 3)
#Column(name = "water_facility")
private String waterFacility;
#NotNull
#Column(name = "phone_num")
private Long phoneNumber;
#NotNull
#Column(name = "house_photo")
private String housephoto;
#NotNull
#Column(name = "id_photo")
private String idphoto;
#NotNull
#Column(name = "map_photo")
private String mapphoto;
#NotNull
#Column(name = "audio")
private String audio;
#NotNull
#Digits(integer = 3, fraction = 25)
#Column(name = "latitute")
private BigDecimal latitude;
#NotNull
#Digits(integer = 3, fraction = 25)
#Column(name = "longitute")
private BigDecimal longitude;
#NotNull
#Size(max = 100)
#Column(name = "surveyor_name")
private String surveyorName;
#Column(name = "servey_date")
#Temporal(TemporalType.TIMESTAMP)
private Date surveyDate;
#NotNull
#Size(max = 10)
#Column(name = "total_members")
private String totalMembers;
#NotNull
#Column(name = "id")
private Long id;
#JsonIgnore
#Transient
private String serveyStringDate;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "houseHold", fetch = FetchType.EAGER)
private List<OwnerDetails> ownerdetail = new ArrayList<>();
//default constructor
//parameterized constructor
//getter setter
OwnerDetails.java
#Entity
#Table(name = "ownerdetails")
public class OwnerDetails implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "owner_id_seq")
#SequenceGenerator(name = "owner_id_seq", sequenceName = "owner_id_seq", allocationSize = 1)
#Column(name = "oid")
private Long oid;
#NotNull
#Size(max = 100)
#Column(name = "name")
private String name;
#NotNull
#Size(max = 100)
#Column(name = "education")
private String education;
#NotNull
#Column(name = "age")
private int age;
#NotNull
#Size(max = 10)
#Column(name = "gender")
private String gender;
#NotNull
#Size(max = 100)
#Column(name = "idname")
private String idName;
#NotNull
#Size(max = 100)
#Column(name = "idnumber")
private String idNumber;
#JsonIgnore
#ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "hid", referencedColumnName = "hid", nullable = false, updatable = false, insertable = true)
#OnDelete(action = OnDeleteAction.CASCADE)
private HouseHold houseHold;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "ownerdetails", fetch = FetchType.EAGER)
private List<HouseHoldMembers> membersdetails = new ArrayList<>();
//default constructor
//parameterized constructor
//getter setter
HouseHoldMembers.java
#Entity
#Table(name = "household_members")
public class HouseHoldMembers implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY, generator = "mem_id_seq")
#SequenceGenerator(name = "mem_id_seq", sequenceName = "mem_id_seq", allocationSize = 1)
#Column(name = "mid")
private Long mid;
#NotNull
#Size(max = 100)
#Column(name = "name")
private String name;
#NotNull
#Size(max = 100)
#Column(name = "education")
private String education;
#NotNull
#Column(name = "age")
private int age;
#NotNull
#Size(max = 10)
#Column(name = "gender")
private String gender;
#NotNull
#Size(max = 100)
#Column(name = "idname")
private String idName;
#NotNull
#Size(max = 100)
#Column(name = "idnumber")
private String idNumber;
#JsonIgnore
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "oid", nullable = false, updatable = false, insertable = true)
#OnDelete(action = OnDeleteAction.CASCADE)
private OwnerDetails ownerdetails;
//default constructor
//parameterized constructor
//getter setter
Dtat.json
{
"district" : "district",
"taluk" : "taluk",
"villageName" : "village name",
"slNo" : 234546674,
"khathaNo" : "35824005",
"localityName" : "localitiyname",
"propertyDetails" : "property Details",
"tenant" : "tenant",
"houseDimension" : "housedimension",
"east":"east",
"west":"west",
"north":"north",
"south":"south",
"rentAmount":2000.45,
"vacantPort":"2342",
"gpId":23112,
"gpName":"gpname",
"propertyType":"proprty type",
"roadName":"road name",
"pin":700003,
"surveyNo":23122,
"gridNo":"23122",
"idNumber":"2321223232232",
"area":"area",
"toiletAvailable":"yes",
"waterFacility":"yes",
"phoneNumber":9999999999,
"housephoto":"",
"mapphoto":"",
"audio":"",
"latitude":"22.453",
"longitude":"88.453",
"surveyorName":"surveyor name",
"serveyStringDate":"2019-10-13 11:25:36",
"totalMembers":"2",
"id":1,
"ownerdetail":
[
{
"name":"name",
"education":"education",
"age":10,
"gender":"male",
"idName":"adhaarcard1",
"idNumber":"23424242343",
"membersdetails":
[
{
"name":"name",
"education":"education",
"age":10,
"gender":"male",
"idName":"adhaarcard2",
"idNumber":"23424242344"
},
{
"name":"name1",
"education":"education1",
"age":11,
"gender":"male",
"idName":"adhaarcard2",
"idNumber":"23424242344"
}
]
}
]
}
also i created repository classes for each entity class. Can someone please help me to solve this error. Thank You in Advance.
[JPA Examplem][One to many and many to one relationship][https://github.com/kuldeepjha/JpaProject/tree/master/demo ]

i want to store the JSON using spring boot with JPA

{ "id" :"3",
"userId": "abc",
"favName": "shashank",
"kpiName": "FavKPI",
"rptId": "529",
"language": "EN",
"selectedControlIdList": [
{
"favouriteId": 3,
"controlId": "3",
"controlName": " ",
"label": "Plant",
"keyValue": "KPI_01_PL_01_1",
"structureType": "LISTBOX"
},
{
"favouriteId": 3,
"controlId": "2",
"controlName": " ",
"label": "Plant12",
"keyValue": "KPI_01",
"structureType": "LISTBOX"
}
]
}
My controller class is
#RequestMapping(value = "/addFavData", method = RequestMethod.POST, consumes =MediaType.APPLICATION_JSON_VALUE, produces =MediaType.APPLICATION_JSON_VALUE)
public void addFavData(#RequestBody FavouriteDTO requestInputMapper) {
favouriteService.addFavouriteData(requestInputMapper);
}
service class
public void addFavouriteData(FavouriteDTO requestInputMapper)
{
favouriteRepository.save(requestInputMapper);
}
And these are entity class !!
#Entity
#Table(name = "favorite", schema = "quality")
public class FavouriteDTO implements Serializable{
private static final long serialVersionUID = -7089417397407966229L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "userId")
private String userId;
#Column(name = "favName")
private String favName;
#Column(name = "kpiName")
private String kpiName;
#Column(name = "rptId")
private String rptId;
#Column(name = "language")
private String language;
#OneToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#JoinColumn(name = "favouriteId")
private List<DefaultControlsDTO> selectedControlIdList;
}
And
#Entity
#Table(name = "favoriteControls", schema = "quality")
public class DefaultControlsDTO implements Serializable {
private static final long serialVersionUID = 8720721227933753311L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "favouriteId")
private Integer favouriteId;
#Column(name = "controlId")
private String controlId;
#Column(name = "controlName")
private String controlName;
#Column(name = "label")
private String label;
#Column(name = "keyValue")
private String keyValue;
#Column(name = "structureType")
private String structureType;
}
here the id is auto genrated. and the favouriteId is same as id.
so how can i store the data as id is auto genrated and i need to put the same favourite id as in id. so how can i store the data in the data base
so i have given my entity class. i have two entity Favorite and DefaultFavuorite Entity.so how can i store the data
You can tell Hibernate, and any other JPA implementation, to cascade certain operations you perform on an entity to its associated child entities. The only thing you have to do is to define the kind of operation you want to cascade to the child entities.
The following code snippet shows an example in which I cascade the persist operation of the Author entity to all associated Book entities.
#Entity
public class Author {
…
#ManyToMany(mappedBy=”authors”, cascade = CascadeType.PERSIST)
private List<Book> books = new ArrayList<Book>();
…
}
When you now create a new Author and several associated Book entities, you just have to persist the Author entity.
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
Author a = new Author();
a.setFirstName(“John”);
a.setLastName(“Doe”);
Book b1 = new Book();
b1.setTitle(“John’s first book”);
a.getBooks().add(b1);
Book b2 = new Book();
b2.setTitle(“John’s second book”);
a.getBooks().add(b2);
em.persist(a);
em.getTransaction().commit();
em.close();
As you can see in the log output, Hibernate cascades the operation to the associated Book entities and persists them as well.
15:44:28,140 DEBUG [org.hibernate.SQL] – insert into Author (firstName, lastName, version, id) values (?, ?, ?, ?)
15:44:28,147 DEBUG [org.hibernate.SQL] – insert into Book (publisherid, publishingDate, title, version, id) values (?, ?, ?, ?, ?)
15:44:28,150 DEBUG [org.hibernate.SQL] – insert into Book (publisherid, publishingDate, title, version, id) values (?, ?, ?, ?, ?)

Erroneous POST and PATCH handling of associations with Spring Data Rest

Spring Data Rest is showing a real puzzling behavior when updating an embedded association. In my example there is an entity Customer which has a _OneTo_Many_ relation to an entity Phones. The Phones are correctly shown as embedded array by a GET to the customers/50 entity-resource. But neither the PUT nor the PATCH show the expected results.
public class Customer {
public static final String TABLE_NAME = "CUSTOMER";
public static final String SEQUENCE_NAME = "S_CUSTOMER";
public static final String DISPLAY_NAME_COLUMN = "DISPLAY_NAME";
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE,
generator = "s_customer")
#SequenceGenerator(name = "s_customer", sequenceName = "S_CUSTOMER",
allocationSize = 50)
private Long id;
#NotEmpty
#Column(name = "DISPLAY_NAME")
private String displayName;
#OneToMany(mappedBy = "owner")
private List<Phone> phones;
#Version
private Long version;
}
public class Phone {
public static final String TABLE_NAME = "PHONE";
public static final String SEQUENCE_NAME = "S_PHONE";
public static final String OWNER_COLUMN = "OWNER";
public static final String PHONE_TYPE_COLUMN = "PHONE_TYPE";
public static final String NUMBER_COLUMN = "NUMBER";
enum PhoneType {
MOBILE, HOME, OFFICE
}
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "s_phone_number")
#SequenceGenerator(name = "s_phone_number", sequenceName = SEQUENCE_NAME, allocationSize = 50)
private Long id;
#ManyToOne
#JoinColumn(name = OWNER_COLUMN)
private Customer owner;
#Enumerated(EnumType.STRING)
#Column(name = PHONE_TYPE_COLUMN)
private PhoneType phoneType;
#NotEmpty
#Column(name = NUMBER_COLUMN)
private String number;
#Version
private Long version;
}
A POST to the entity /customer/50 produces a correct Update to the Customer, but the Insert to the Phone does not contain the foreign key to the customer:
[EL Fine]: sql: 2016-06-23
11:41:25.149--ClientSession(1317378011)--Connection(497905718)--Thread(Thread[http-nio-8081-exec-1,5,main])--UPDATE
CUSTOMER SET DISPLAY_NAME = ?, VERSION = ? WHERE ((ID = ?) AND
(VERSION = ?)) bind => [bla, 1, 50, 0] [EL Fine]: sql: 2016-06-23
11:41:25.15--ClientSession(1317378011)--Connection(497905718)--Thread(Thread[http-nio-8081-exec-1,5,main])--INSERT
INTO PHONE (ID, NUMBER, PHONE_TYPE, VERSION, OWNER) VALUES (?, ?, ?,
?, ?) bind => [1, 12345, MOBILE, 1, null]
This is the body of the PUT request:
{
"displayName": "bla",
"phones": [
{
"number": "12345",
"phoneType": "MOBILE"
}
]
}
So, Spring Data Rest correctly interprets the PUT as an update of the Customer and an insert into the Phone table, but just "forgets" about the relation. I assume this is a bug. Or is there something I forgot?
Btw: The PATCH behaves similar. There is again not foreign key in the phone record.
Edit:
The code of the CustomerRepository:
#Repository
public interface CustomerDao extends PagingAndSortingRepository<Customer, Long> {
List<Customer> findByDisplayName(#Param("name") String name);
}

Resources