org.postgresql.util.PSQLException: ERROR: null value in column "id" violates not-null constraint, Id Colums not able generate by sequcece in Hibernat - postgresql

I am getting an error that Id column is not able to generate.
which will have the Getters and Setters.
Note: In my case, Primary Key was bookingId.
"Id" has to be a sequence number.
Below is the save method.
At the time of save is was not able to generate value for the column.
Below is My Entity.
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Id
#Column(name = "booking_id")
private String bookingId;
#Column(name = "booked_by")
private String bookedBy;
#Column(name = "booking_status")
private int bookingStatus;
#Column(name = "booking_rcv")
private Date bookingRcv;
#Column(name = "chargeable_kgs")
private BigDecimal chargeableKgs;
}
Here we will have all the getters and setters, Constructors, hashcode, and equals methods.
#Transactional
#Override
public Booking saveBooking(Booking booking) {
Booking savedBooking = bookingRepository.save(booking);
if (savedBooking.getId() != null) {
booking.setId(savedBooking.getId());
}
booking.setVersion(savedBooking.getVersion());
bookingRepository.flush();
// bookingRepository.refresh(booking);
LOGGER.debug("savedbooking id::" + savedBooking.getId());
return savedBooking;
}
I am using postgre DB and Hibernate.

Related

Unable to create unique key constraint - Make sure that you use the correct column name which depends on the naming strategy in use

The full error message is:
Unable to create unique key constraint (aircraft_series_id, service_enum) on table aircraft_service: database column 'service_enum' not found. Make sure that you use the correct column name which depends on the naming strategy in use (it may not be the same as the property name in the entity, especially for relational types)
My entity is specified as:
#Entity
#Table(uniqueConstraints = { #UniqueConstraint(columnNames = { "aircraft_series_id", "service_enum" }) })
#Getter
#Setter
#NoArgsConstructor
#ToString
public class AircraftService {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#NotNull
private Integer minimumQuantity;
#NotNull
private Integer maximumQuantity;
#NotNull
private Integer defaultQuantity;
#NotNull
#ManyToOne(optional = false)
#JsonIgnore
private AircraftSeries aircraftSeries;
#NotNull
#Enumerated(EnumType.STRING)
private ServiceEnum serviceEnum;
}
If I comment out the #Table(uniqueConstraints = { #UniqueConstraint(columnNames = { "aircraft_series_id", "service_enum" }) }) annotation then the columns are created and I can see the field names when opening the table under the SQL client.
service_enum
aircraft_series_id
For now I'm running the application against the H2 database.
I could have the application running not throw an exception if the class is boasting the column annotations, as in:
#Column(name = "service_enum")
#ManyToOne(optional = false)
#JoinColumn(name = "service_profile_id")
I don't see why this is the case, as by default, the column names are exactly the same, when attributed by the application itself.

JPA entity sequence generating

In spring boot JPA I tried to implement sequence generator but it is not working.
the following is my entity
#Entity
#Table(name = "role_level")
public class RoleLevel implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#SequenceGenerator(name = "role_level_sequence", sequenceName = "role_level_id_seq",allocationSize = 1)
#GeneratedValue(strategy = GenerationType.SEQUENCE,generator = "role_level_sequence")
#Column(name = "id", updatable = false)
private Long id;
#Column(name = "role_level")
private String roleLevel;
#Column(name = "role_level_description")
private String roleLevelDescription;
//getters and setters
}
when I insert value in directly through the database then next sequence from the db is not getting in jpa.it shows
org.postgresql.util.PSQLException: ERROR: duplicate key value violates unique constraint "role_level_pkey"
Detail: Key (id)=(7) already exists.
But the console shows
Hibernate: select nextval ('role_level_id_seq')
I think its not working.
Is there any solution for this.?

JPA repository retrieve custom primary key value after save

I have an entity class pointing to postgresql table. Below is table structure. The paymentreferencenumber is the PK which is populated by a trigger. id field is the sequence generated field. When i try to save in this table using JPARepository save method it inserts the first record. But after that it fails due to the primary key constraint. Since PK is a string type and generated using trigger I am specifying generator strategy as 'select'. Can anyone help me with this blocker and point me in the right direction. Thanks
Table structure --
custId serial not null,
paymentreferencenumber varchar(32) not null
constraint customers1_pkey
primary key,
firstname varchar(255),
lastname varchar(255)
Entity class --
#Entity
#Table(name = "customersnew")
public class Customer implements Serializable {
private static final long serialVersionUID = -1L;
#GeneratedValue(generator = "seq")
#GenericGenerator(name="seq", strategy="sequence", parameters = { #Parameter(name="key", value = "customersnew_custid_seq")})
#Column(name = "custid")
private long id;
#Id
#GeneratedValue(generator = "trigger_generated")
#GenericGenerator(name="trigger_generated", strategy="select", parameters = { #Parameter(name="key", value = "id")})
#Column(name = "paymentreferencenumber")
private String refNum;
#Column(name = "firstname")
private String firstName;
#Column(name = "lastname")
private String lastName;
}
--- Controller using JPA save
#RestController
public class CustomerController {
#Autowired
CustomerRepository repository;
EntityManagerFactory emf;
public CustomerController(CustomerRepository repository, EntityManagerFactory emf) {
this.repository = repository;
this.emf = emf;
}
#PostMapping("/create")
public String create(#RequestBody CustomerUI customer){
// save a single Customer
Customer returnObj = repository.saveAndFlush(new Customer(customer.getFirstName(), customer.getLastName()));
PersistenceUnitUtil util = emf.getPersistenceUnitUtil();
Object retObj = util.getIdentifier(returnObj);
return "Customer is created";
}
If you don't specify an id generation strategy, Hibernate will use GenerationType.AUTO. This will result in any of
AUTO - either identity column, sequence or table depending on the
underlying DB.
If you look here, you'll notice all of those generate ids of type long, short or int, not of type String.
Say you wanted a String UUID as an id, you could use
#Id
#GeneratedValue(generator = "uuid")
#GenericGenerator(name = "uuid", strategy = "uuid2")
#Column(name = "paymentreferencenumber")
private String refNum;

Spring Data JPA does findAll retrieve data from associated table in a onetoone mapping?

I am using Spring Data JPA. I have 2 tables as follows:
Investment and Investment_Type. There is a one to one relationship between Investment and Investment_Type.
My Investment class is as follows:
#Entity
public class Investment {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int investmentId;
#NotNull(message = "Cannot be empty")
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "investment_type_id")
private InvestmentType investmentType;
#NotNull(message = "Cannot be empty")
private String investmentNumber;
//getter and setter methods
}
My InvestmentType class is as follows:
#Entity
public class InvestmentType {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private Integer investmentTypeId;
private String investmentTypeName;
//getter and setter methods
}
My InvestmentRepository is as follows:
public interface InvestmentRepository extends JpaRepository <Investment, Integer>{
}
My controller has the following code:
List<Investment> investments = investmentRepo.findAll();
for(Investment investment:investments){
logger.info(" Got investment with id "+investment.getInvestmentId());
if(investment.getInvestmentType() != null){
logger.info("Investment Type is "+investment.getInvestmentType().getInvestmentTypeName());
}
else{
logger.info("null investment type ");
}
}
However, the for loop always outputs "null investment type"
So it appears that the findAll method does not retrieve the data from the InvestmentType table to which there is a OneToOne mapping.
Am I doing something wrong? Do I need to do something explicit in order to also retrieve data from the associated table with the mapping?
one-to-one association is the only one that can not be proxied.Add fetch type lazy and use mappedby on related table colum.
Parent table
#NotNull(message = "Cannot be empty")
#OneToOne(fetch = FetchType.LAZY, optional = false)
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "investment_type_id")
private InvestmentType investmentType;
Related table
#Id #GeneratedValue(strategy=GenerationType.AUTO)
#OneToOne(mappedBy = "investment")
private Integer investmentTypeId;

Exception while persisting JPA object in DB having one to many relation

hi have two tables in picture table a and table b as follows :
#Entity
#Table(name = "A")
public class A implements Serializable {
#Id
#SequenceGenerator(name = "JOURNAL_CATEGORY_ID_GENERATOR", allocationSize = 1, sequenceName = "clm_jounal_category_config_seq")
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "JOURNAL_CATEGORY_ID_GENERATOR")
#Column(name = "CLAIM_ID")
private String claimId;
#Column(name = "name")
private String name;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "country")
private List<ClaimDTLS> claimDetails;
}
B Primary Key:
#Embeddable
public class BPK implements Serializable {
#Column(name = "code")
private String code;
#Column(name = "CLAIM_ID")
private String claimId;
}
B Entity:
#Entity
#Table(name = "B")
public class B implements Serializable {
#EmbeddedId
protected BPK bpk;
#Column(name = "name")
private String name;
#MapsId("country_code")
#JoinColumn(name = "claimId", referencedColumnName = "claimId", insertable = false, updatable = false)
#ManyToOne
private A a;
}
when i try to persist object of A type in Db the value of table b claim id is not set and is intialized with zero.
Also primary key of table A is generated with a oracle sequence.
any help will be welcomed.
thanks in advance
Sequence values are numbers and when JPA use them as a generator it call the setter method of the entity PK. Now, you defined your PK as a string while you use a sequence and so no matching setter can be found. Change the type of you PK to be Long and things shall work