Foreign key is null : Hibernate Spring - java

I try to save object Run to database. I defined relation between Run and City. One city could have many runs. I got problem with city_id. Is null.
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.DataIntegrityViolationException: could not execute statement; SQL [n/a]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement] with root cause
java.sql.SQLIntegrityConstraintViolationException: Column 'city_id' cannot be null
My entieties and controller:
City
#Entity
#Getter
#Setter
#Builder
#NoArgsConstructor
#AllArgsConstructor
#Table(name = "cities")
public class City {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "city_id")
private long id;
#OneToMany(mappedBy = "city", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Run> runs = new ArrayList<>();
private String name;
}
Run
#Entity
#Builder
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#Table(name = "runs")
public class Run {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name = "name_run")
private String nameRun;
#Column(name = "distance")
private double distance;
#Column(name = "date")
private Date date;
#Column(name = "my_time")
private String myTime;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "city_id", nullable = false)
#OnDelete(action = OnDeleteAction.CASCADE)
#JsonIgnore
private City city;
}
Controller
#CrossOrigin
#RestController
#RequestMapping("/api/")
public class RunController {
private RunRepository runRepository;
private RunService runService;
public RunController(RunRepository runRepository, RunService runService) {
this.runRepository = runRepository;
this.runService = runService;
}
#GetMapping("runs")
public ResponseEntity<List<Run>> getRuns() {
return runService.getRuns();
}
#PostMapping("runs")
public ResponseEntity addRun(#RequestBody Run run) {
return new ResponseEntity<>(runRepository.save(run), HttpStatus.OK);
}
}
I would like to save the run in DB.
My test request looks like :
{
"nameRun": "test",
"distance":"5.0",
"date":"2020-12-12",
"myTime":"50:40",
"city":"test1"
}
Result from evaluate expresion in Intelijj:
Why the City = null? Is here error in mapping?

Can you try with this json but you need to pass city id in json.
{
"nameRun": "test",
"distance": "5.0",
"date": "2020-12-12",
"myTime": "50:40",
"city": {
"id": 1,
"name": "test1"
}
}
Thanks

First of all, use Long for id please. It is better to add #Entity annotation too.
#Entity
public class City {
#Id
#GeneratedValue
private Long id;
#OneToMany(mappedBy = "city", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Run> runs = new ArrayList<>();
}
#Entity
public class Run {
#Id
#GeneratedValue
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
private City city;
}
You need to set city_id when you save Run.
The simplest way to do that is just create a fake transient City and set id to it.
City city = new City();
city.setId(1L);
Run run = new Run();
run.setCity(city);
repository.save(run);
Obviously you should have a city with id 1L in the database.
Other options are
Use something like session.load() Hibernate analogue with Spring repository to create City without loading it from datatbase.
Load City entity entirely by id.

if you wanna save any run class,
Run run = new Run();
City city = new City();
city.getRuns().add(run);
runRepository.save(run);
if you wanna save any run class, first you need to insert to (Arraylist) runs variable of city class like city.getRuns().add(run) after filling run then you can runRepository.save(run).
Also my samples are here. You can look at myclasses.
First class is called Patient .
#Data
#AllArgsConstructor
#NoArgsConstructor
#Entity
#ToString
#Table(name = "aapatient")
public class Patient {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AA_PATIENT_SEQ")
#SequenceGenerator(sequenceName = "AA_PATIENT_SEQ", allocationSize = 1, name = "AA_PATIENT_SEQ")
#Column(name = "patientid")
private Long patientid;
private String name;
private String lastname;
#OneToMany(mappedBy = "patient", cascade = CascadeType.ALL, fetch = FetchType.LAZY)
private List<Problem> problems;
}
Second Class called Problem is this one.
#Data
#AllArgsConstructor
#NoArgsConstructor
#ToString
#Entity
#Table(name="aaproblem")
public class Problem{
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "AA_PATIENT_SEQ")
#SequenceGenerator(sequenceName = "AA_PATIENT_SEQ", allocationSize = 1, name = "AA_PATIENT_SEQ")
#Column(name = "problemid")
private Long problemid;
private String problemName;
private String problemDetail;
#Temporal(TemporalType.TIMESTAMP)
Date creationDate;
#NotNull
#ManyToOne(optional = true, fetch = FetchType.LAZY)
#JoinColumn(name = "patient_id")
private Patient patient;
}

Related

Field 'id' doesn't have a default value because of nested object creation

I am getting field 'id' doesn't have a default value error in my Spring application.
I am trying to create an Applicant with #Post method but as I am creating the Applicant, new creditRating object needs to be created.
Here is the method
public Applicant create(ApplicantDTO applicantDTO) {
Applicant applicant = ApplicantMapper.toEntity(applicantDTO);
applicant.setCreditRating(creditRatingService.create());
return applicantRepository.save(applicant);
}
Here is my Applicant class
#Data
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "applicant")
public class Applicant {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Long identificationNumber;
private String firstName;
private String lastName;
private double monthlyIncome;
private String phoneNumber;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "credit_rating_id", referencedColumnName = "id")
private CreditRating creditRating;
#OneToOne(cascade = CascadeType.ALL)
#JoinTable(name = "applicant_credit",
joinColumns = {#JoinColumn(name = "applicant_id")},
inverseJoinColumns = {#JoinColumn(name = "credit_id")}
)
private Credit credit;
}
And this is the create method for CreditRating object.
public CreditRating create() {
CreditRating creditRating = new CreditRating();
creditRating.setCreditRating(getRandomCreditRating());
return creditRatingRepository.save(creditRating);
}
I want this object to be created while creating an Applicant but somehow I think JPA can't generate the id for it as I am doing the creation like this.
As requested here is CreditRating Entity
#Data
#Entity
#AllArgsConstructor
#NoArgsConstructor
#Table(name = "credit_rating")
public class CreditRating {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private int creditRating;
}
I figured out the problem. Problem was in database creditRating and credit somehow didn't have Auto Increment ticked. I dropped the schema then let JPA create the tables again. Then Auto Increment was both ticked on credit and creditRating tables.

I have Mapping Exception on my Spring Boot project

I have a 3 models and 1 table to Many to many relationship on my project
this:
#Embeddable
#Getter
#Setter
public class ProductWarehouseId implements Serializable {
#Column(name = "warehouse_Id")
private Long warehouseId;
#Column(name = "product_Id")
private Long productId;
#Column(name = "user_Id")
private Long userId;
public ProductWarehouseId() {
}
public ProductWarehouseId(Long warehouseId, Long productId, Long userId) {
this.warehouseId = warehouseId;
this.productId = productId;
this.userId = userId;
}
}
---------------------------------------------------
#Entity
#NoArgsConstructor
#Getter
#Setter
public class ProductWarehouse {
#EmbeddedId
ProductWarehouseId productWarehouseId;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("productId")
#JoinColumn(name = "product_id")
ProductEntity product ;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("warehouseId")
#JoinColumn(name = "warehouse_id")
WarehouseEntity warehouse ;
#ManyToOne(fetch = FetchType.LAZY)
#MapsId("userId")
#JoinColumn(name = "user_id")
UserEntity userEntity;
#Column(name = "stockAmount")
private Long stockAmount;
#Column(name = "transctionDate")
#Temporal(TemporalType.TIMESTAMP)
private Date transactionDate = new Date();
public ProductWarehouse(ProductEntity product, UserEntity user) {
this.product = product;
this.userEntity = user;
}
}
********************************************************
#Getter
#Setter
#Entity
#RequiredArgsConstructor
public class ProductEntity extends BaseEntity{
#OneToMany(mappedBy = "product",cascade = CascadeType.ALL)
private Set<ProductWarehouse> productWarehouses;
//And more veriables
}
------------------------------------
#Getter
#Setter
#Entity
public class WarehouseEntity extends BaseEntity{
#OneToMany(mappedBy = "warehouse",cascade = CascadeType.ALL)
private Set<ProductWarehouse> productWarehouses = new HashSet<>();
//and more veriables
}
When i trying to select list from product_warehouse table to make changes, i have some Exceptions.
I want to transfer the products between warehouses using fromId and toId
I using this method in service class:
#Override
#Transactional
public void transfer(Long fromId, Long toId) {
WarehouseEntity warehouseEntity = warehouseCRUDRepository.getOne(fromId);
WarehouseEntity warehouseEntity1 = warehouseCRUDRepository.getOne(toId);
if (warehouseEntity.getStatus().equals(WarehouseStatus.ACTIVE) && warehouseEntity1.getStatus().equals(WarehouseStatus.ACTIVE)){
Collection<ProductWarehouse> productWarehouses = em
.createNativeQuery("select c from product_warehouse c where c.warehouse_id =:fromId")
.setParameter("fromId",fromId)
.getResultList();
for (ProductWarehouse p : productWarehouses){
p.getProductWarehouseId().setWarehouseId(toId);
p.setWarehouse(warehouseCRUDRepository.getOne(toId));
}
}
}
And the Exception is :
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is javax.persistence.PersistenceException: org.hibernate.MappingException: No Dialect mapping for JDBC type: 2002] with root cause.
Can you hep me please.
I am sorry for my English, and thank you.
ProductWarehouse is already having Warehouse in it, I don't understand why are you again setting it up by fetching it from DB inside the for loop.
I don't see any necessity of the for loop in that method, also as you described above you haven't defined many to many relationship anywhere. while building the relationship you can use the join table as explained here
if you need more information, please share more details of your need and errors you are facing.

Not able to delete in #OneToMany relationship spring data jpa

In my spring boot project, I have one LineItem entity below is the code
#Entity
#Table(name = "scenario_lineitem")
#Data
#NoArgsConstructor
public class LineItem implements Cloneable {
private static Logger logger = LoggerFactory.getLogger(GoogleConfigConstant.class);
#Id
#GeneratedValue(strategy = IDENTITY)
private BigInteger lineItemId;
#Column
private String name;
#OneToMany(fetch = FetchType.LAZY, cascade = { CascadeType.ALL, CascadeType.PERSIST, CascadeType.MERGE })
#JoinColumn(name = "line_item_meta_id")
private List<QuickPopValue> quickPopValues;
}
Another entity is
#Entity
#Table(name = "quick_pop_value")
#Data
#NoArgsConstructor
public class QuickPopValue implements Cloneable {
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "quick_pop_value_id", columnDefinition = "bigint(20)", unique = true, nullable = false)
private BigInteger quickPopValueId;
#Column(name = "column_name")
private String columnName;
#Column(name = "value")
private String value;
#Column(name = "formula", columnDefinition = "longtext")
private String formula;
}
Now I am trying to delete QuickPopValue one by one but it's not getting deleted and not getting any exception as well.
Below is the delete code :
List<QuickPopValue> quickPopValues = sheetRepository.findByColumnName(columnName);
for (QuickPopValue qpValue : quickPopValues) {
quickPopValueRepository.delete(qpValue);
}
Such behavior occurs when deleted object persisted in the current session.
for (QuickPopValue qpValue : quickPopValues) {
// Here you delete qpValue but this object persisted in `quickPopValues` array which is
quickPopValueRepository.delete(qpValue);
}
To solve this you can try delete by id
#Modifying
#Query("delete from QuickPopValue t where t.quickPopValueId = ?1")
void deleteQuickPopValue(Long entityId);
for (QuickPopValue qpValue : quickPopValues) {
quickPopValueRepository.deleteQuickPopValue(qpValue.getQuickPopValueId());
}

Error with #ManyToOne - JPA/Hibernate Detached Entity Passed to Persist

Good Evening,
I am relatively new to using Hibernate, and I am running into the following error:
"message": "org.springframework.web.util.NestedServletException: Request processing failed;
nested exception is org.springframework.dao.InvalidDataAccessApiUsageException: detached entity passed to persist:
com.company.project.data.relational.models.ListsItems; nested exception is org.hibernate.PersistentObjectException:
detached entity passed to persist: com.company.project.data.relational.models.ListsItems",
I have a JSON object being sent from the front-end that has a nested object. I am trying to get the the nested items in a separate table in MySQL, with a relationship using the original objects ID.
Here's an example of the JSON:
{
"name":"Test",
"type":"App Id List",
"listItems":
[
{
"id":1,
"name":"Test",
"value":" 1"
},
{
"id":2,
"name":"NEW TEST",
"value":" 2"
}
]
}
Here is my Lists model:
#Entity
#Getter
#Setter
#NoArgsConstructor
#Table(name = "lists")
public class Lists implements Serializable, OperationalEntity {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(columnDefinition = "char", nullable = false)
private String guid;
private String name;
private String type;
#OneToMany(fetch = FetchType.EAGER, mappedBy = "listItems", orphanRemoval = true)
#Cascade({org.hibernate.annotations.CascadeType.ALL, })
private Set<ListsItems> listItems;
private Date created;
private Date updated;
}
And here is my ListsItems model:
#Getter
#Setter
#Entity
#Table(name = "lists_items")
#NoArgsConstructor
public class ListsItems implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name;
private String value;
#NaturalId
#ManyToOne(optional = false, fetch = FetchType.EAGER)
#JoinColumn(name = "lists_id", referencedColumnName = "id")
private Lists listItems;
}
Here is the save function:
#PostMapping(value = "/add")
#PreAuthorize("hasRole('ADMIN')")
public #ResponseBody WebResponse<W> create(#RequestBody W webModel) {
D dbModel = asDbModel(webModel);
dbModel.setGuid(UUID.randomUUID().toString());
return WebResponse.success(createWebModelFromDbModel(getDatabaseEntityRepository().save(dbModel)));
}
Any ideas on what might be causing this error? I've searched a bit but nothing I've tried from any other solutions have worked out.
Thanks in advance!
- Travis W.
The answer was to make the following changes to ListItems:
#JsonIgnore // this import will be from jackson
#NaturalId
#ManyToOne(optional = false, fetch = FetchType.LAZY)
#JoinColumn(name = "lists_id", referencedColumnName = "id")
private Lists list;
And the following to Lists:
#OneToMany(fetch = FetchType.EAGER, mappedBy = "list", orphanRemoval = true)
#Cascade({org.hibernate.annotations.CascadeType.ALL, })
private Set<ListsItems> listItems;
I also needed to iterate over the results:
#Override
protected Lists asDbModel(WebLists webModel) {
Lists dbModel = new Lists();
dbModel.setId(webModel.getId());
dbModel.setName(webModel.getName());
dbModel.setType(webModel.getType());
dbModel.setListItems(webModel.getListItems());
for(ListsItems item : webModel.getListItems()) {
item.setList(dbModel);
}
return dbModel;
}

Method threw 'org.springframework.dao.DataIntegrityViolationException' exception

I have this entity
#Entity
#Table(name = "REPORT_TASCK")
#Data
public class ReportTasck {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
public Long id;
#Column(name = "type")
public String type;
#Column(name = "status")
public Integer status;
#Column(name = "type")
#OneToMany(mappedBy = "reportTasck", fetch = FetchType.EAGER, cascade = CascadeType.ALL)
public List<Bill> bills;
}
and
#Entity
#Table(name = "BIIL")
#Data
public class Bill {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
public Long id;
#Column(name = "neme")
public String neme;
#Column(name = "status")
public Integer status;
#ManyToOne()
#JoinColumn(name = "REPORT_TASCK_ID")
public ReportTasck reportTasck;
}
then I tried fill it and save
ReportTasck reportTasck = new ReportTasck();
reportTasck.setStatus(0);
reportTasck.setType("standart");
List<Bill> bills = new ArrayList<>();
for (BillDto billDto : all) {//640 items
Bill bill = new Bill();
bill.setStatus(0);
bill.setNeme(billDto.getBill());
bill.setReportTasck(reportTasck);
bills.add(bill);
}
reportTasck.setBills(bills);
reportTasckRepository.save(reportTasck);
but when start this line reportTasck.setBills(bills); I get error in debbug mode Method threw 'java.lang.StackOverflowError' exception. Cannot evaluate entity.ReportTasck.toString()
and when I tried save I get this error Method threw 'org.springframework.dao.DataIntegrityViolationException' exception.
could not execute statement; SQL [n/a]; constraint [null]
I dont understand why I get this error and how fix

Categories