Spring POST error whit third entity relationship - java

I'm new on Spring, i would like to store relationship between Exam and Question whith this structure:
#Entity
#Data
#EqualsAndHashCode(callSuper = true)
public class Exam extends UriEntity<Integer> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotBlank
#Length(min = 1, max = 256)
private String name;
#OneToMany(mappedBy="exam")
private List<ExamQuestion> exams_questions;
#Entity
#Data
#EqualsAndHashCode(callSuper = true)
public class Question extends UriEntity<Integer> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#NotBlank
#Column(unique = true)
private String statement;
#NotBlank
private String answer;
#OneToMany(mappedBy="question")
private List<ExamQuestion> exams_questions;
#Entity
#Data
#EqualsAndHashCode(callSuper = true)
public class ExamQuestion extends UriEntity<Integer> {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne
#JoinColumn(name = "question_id")
private Question question;
#ManyToOne
#JoinColumn(name = "exam_id")
private Exam exam;
When i want to store a new ExamQuestion object with POSTMAN
{
"exam": "http://localhost:8080/exams/28",
"question": "http://localhost:8080/questions/17"
}
I get an error 409, and the message:
NULL not allowed for column \"ID\";
Any could help me ?
Thanks in advance.

This might happen because of the #GeneratedValue(strategy = GenerationType.IDENTITY).
Make sure that in your database schema ID column is set to be auto incremented, since GenerationType.IDENTITY uses databases identity column to generate values. Thus if your column is not set to be auto incremented you get this error.

Related

JPA null value in column "header_id" of relation "invoice" violates not-null constraint with PostgresSQL

Getting below Error while saving data
Caused by: org.postgresql.util.PSQLException: ERROR: null value in column "header_id" of relation "invoice" violates not-null constraint
Detail: Failing row contains (...null).
Header
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "header")
public class Header implements Serializable {
private static final long serialVersionUID = 3363186434410305269L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "header_id")
private Long headerId;
#Column(name = "submitted_by", length = 17)
private String submittedBy;
#OneToMany(mappedBy = "header", cascade = CascadeType.ALL)
#Builder.Default
private List<Invoice> invoices = new ArrayList<>();
}
Invoice
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "invoice")
public class Invoice implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "invoice_id")
private Long invoiceId;
#Column(name = "serial_no")
private Integer serialNo;
#JsonIgnore
#ManyToOne
#JoinColumn(name = "header_id", nullable = false)
private Header header;
}
Please help me to solve the error.
I think this is because your headerId can be null because you use "Long" as type, wich is a good practice, but you should remove nullable = false inside Invoice.java.
Put nullable = false inside your database rules
If this problem does not come from there, check that the headerId of your Header class is not null when you create the object that you want to save in the database

#ManyToOne #OneToMany Mapping , foreign key is null

#Entity
#Data
#NoArgsConstructor
public class Offer {
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;
}
#Data
#EqualsAndHashCode
#Entity
#NoArgsConstructor
public class User {
#OneToMany(mappedBy = "user",cascade = CascadeType.ALL,fetch=FetchType.LAZY)
private Set<Offer> offers = new HashSet<Offer>();
}
Please help if the mapping is correct in table User and Offer .user_id column have null values ....:(
I'm not sure if these are only parts of the entities but in order for the entity to have an id, you need to provide it with one and annotate the relevant field as #Id.
I also use #GeneratedValue(strategy = GenerationType.IDENTITY) so each table will get it's own id (generated by Hibernate, you don't provide the id when you save a new entity and not a global id, otherwise let's say you add an Offer, you get id with value x, then add new User you get id with value x+1 and so on...
#Entity
#Data
#NoArgsConstructor
public class Offer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name = "user_id", referencedColumnName = "id")
private User user;
}
#Data
#EqualsAndHashCode
#Entity
#NoArgsConstructor
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#OneToMany(mappedBy = "user",cascade = CascadeType.ALL,fetch=FetchType.LAZY)
private Set<Offer> offers = new HashSet<Offer>();
}`

How to use #OnetoMany with Embeddedid

I am working on hibernate and tying to associate mapping with #OneToMany relationship with composite key.
Following are the entities that currently my using .
#Embeddable
#Getter
#Setter
public class AddressKey implements Serializable {
private static final long serialVersionUID = -307823488229761699L;
#Column(name = "id")
private Long id;
#Column(name = "city")
private Long city;
#Column(name = "locale")
private String locale;
#Column(name = "type")
private String type;
#ManyToOne
#JoinColumn(name="id")
private Person person;
}
#Entity
#Table(name = "address", schema = "test")
#Setter
#Getter
public class AddressHistory {
#EmbeddedId
private AddressKey key;
#Column(name = "active")
private boolean active;
#Column(name = "current")
private boolean current;
}
#Entity
#Table(name = "person", schema="test")
#ToString
public class Person {
#Id
#Column(name = "id")
private Long id;
#OneToMany(mappedBy="key.person", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
private Set<AddressHistory> addressHistory;
}
But when I am trying to run this program it gives me following error.
repeated column in mapping for entity AddressHistory.
Someone help me to fix this what's wrong in this mapping.
Thanks in advance
You repeated columns. Remove #JoinColumn(name="id") in AddressKey since you already have one column with the same name or rename it to something else and more maintainable like person_id.

Join two tables with hibernate

I am looking to create a DAO which represents a join of two tables with Java Hibernate. Here is the SQL I'd like to represent (Postgres 9.6 incase that matters):
SELECT tableOneValue, tableTwoValue
FROM table_one, table_two
WHERE table_one_filter = 2 AND table_one_id = table_two_id;
These tables have a OneToOne relationship.
Table1.java
#Entity
#Data
#Table(name="table_one")
public class TableOneDao implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "table_one_id")
private int tableOneId;
#Column(name = "table_one_value")
private String tableOneValue;
#Column(name = "table_one_filter")
private int tableOneFilter;
}
Table2.java
#Entity
#Data
#Table(name="table_two")
public class TableTwoDao implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "table_twp_id")
private int tableTwpId;
#Column(name = "table_two_value")
private String tableTwoValue;
}
I'm very new to hibernate so maybe this isn't the right way to think with it. What I would love to do is define a SomeDao class where I can do: daoManager.findAll(SomeDao.class, Pair.of("tableOneFilter", 2));
This would return a List<SomeDao> where we get all the rows that satisfy tableOneFilter == 2.
You need to use the #OneToOne and #JoinColumn annotation.
Pay special attention to the userDetail attribute mapping.
For example, the user class:
#Entity
#Table(name = "USERS")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "USR_ID")
private long id;
#Column(name = "USERNAME", nullable = false, unique = true)
private String username;
#Column(name = "PASSWORD")
private String password;
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name="USR_DET_ID")
private UserDetail userDetail;
// Add Constructor, Setter and Getter methods
}
And this user details class:
#Entity
#Table(name = "USER_DETAILS")
public class UserDetail {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "USR_DET_ID")
private long id;
#Column(name = "FIRST_NAME")
private String firstName;
#Column(name = "LAST_NAME")
private String lastName;
#Column(name = "EMAIL")
private String email;
#Column(name = "DBO")
private LocalDate dob;
// Add Constructor, Setter and Getter methods
}
Check the full code here.
Here is a JPA query which will work with your existing entity structure with the latest version of hibernate.
SELECT t1.tableOneValue, t2.tableTwoValue
FROM TableOneDao AS t1 JOIN TableTwoDao AS t2 ON t1.table_one_id = t2.table_two_id
WHERE t1.table_one_filter = ?
You can write a JPQL statement which is much better. Here is the sample solution:
SELECT NEW com.test.package.dao(t1.valueOne, t2.valueTwo)
FROM table_one t1 JOIN table_two t2
WHERE t1.filter = 2 AND t1.id = t2.id;
Please refer to this link and jump to the section where it mentions Result Classes (Constructor Expressions). Hope it helps. Thanks.

How can I do the multiply relations in Hibernate?

everyone! Sorry but I need some help. My db is looking this way, I try to do same throught the Hibernate in Java.
But I don`t understand how I need to annoted this relations with so many different tables.
It`s a part of my Abiturient table.
#Entity
#Table (name = "abiturient",
uniqueConstraints = {#UniqueConstraint(columnNames = {"id"})})
public class Abiturient {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, unique = true, length = 11)
#ManyToOne
private Long id;
#Column
private Date data_narodjennya;
#Column
private Integer city_village;
It`s a part of my nomer_telefonu table
#Entity
#Table(name = "nomer_telefonu")
public class NomerTelefonu {
#Id
#Column(name = "nomer_tel_id", nullable = false, unique = true, length = 11)
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long nomer_tel_id;
#Column(name = "nomer")
private String nomer;
#Column(name = "id")
#OneToMany(fetch = FetchType.LAZY)
private Set<Abiturient> id;
I don`t think that all there is right, `cos every time I try to solve problem I get an error and need other type.
Use #OneToMany bidirectional relation.
#Entity
public class Abiturient {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#OneToMany(mappedBy = "abiturent")
private List<NomerTelefonu> phones = Lists.newArrayList();
}
#Entity
public class NomerTelefonu{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "nomer_tel_id")
private Long id;
#ManyToOne(fetch = FetchType.LAZY)
private Abiturient abiturent;
}
Lists.newArrayList() from guava. This is working mapping. Always use the simplest version to experiment.
what is #JoinColumn and how it is used in Hibernate
You can use this project to play with mappings in the unit tests:
https://github.com/v-ladynev/hibernate-experimental

Categories

Resources