Many to many relation in spring framework - java

Currently I'm working on a Spring Framwork application to try out how it works.
I'm having trouble with a many to many relationship and inserting data into it.
As example I'm making something to store orders containing one or multiple items through a link table.
I would like to store one order at a time, including all products related to it (products are already existing). The problem is that when I try to store data, the orderId isn't stored in the product_order table and gives me the following error:
""Column 'ORDER_ID' cannot be null"".
Has anyone a clue about what i'm doing wrong? Or if it's just not possible this way.
SQL structure & Java code is at the end.
The way I try to store the data is:
curl -i -X POST -H "Content-Type:application/json" -d '{
"code" : "Test",
"statusId" : 2,
"userId" : 1,
"productOrders" : [ {
"price" : 1.0,
"amount" : 2,
"product" : {
"productId" : 1
}
}, {
"price" : 2.0,
"amount" : 3,
"product" : {
"productId" : 2
}
} ]
}' http://localhost:8080/order
This is the SQL structure i'm using:
CREATE TABLE `user` (
`USER_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`USER_NAME` VARCHAR(20) NOT NULL,
`USER_BALANCE` DOUBLE UNSIGNED NOT NULL DEFAULT '0',
PRIMARY KEY (`USER_ID`)
);
CREATE TABLE `product` (
`PRODUCT_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`PRODUCT_NAME` VARCHAR(20) NOT NULL,
`PRODUCT_PRICE` DOUBLE UNSIGNED NOT NULL,
`PRODUCT_DESCRIPTION` VARCHAR(45),
PRIMARY KEY (`PRODUCT_ID`)
);
CREATE TABLE `order` (
`ORDER_ID` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT,
`ORDER_USER_ID` INT(10) UNSIGNED NOT NULL,
PRIMARY KEY (`ORDER_ID`),
CONSTRAINT `FK_ORDER_USER_ID` FOREIGN KEY (`ORDER_USER_ID`)
REFERENCES `user` (`USER_ID`)
);
CREATE TABLE `product_order` (
`ORDER_ID` INT(10) UNSIGNED NOT NULL,
`PRODUCT_ID` INT(10) UNSIGNED NOT NULL,
`AMOUNT` INT(10) UNSIGNED NOT NULL,
`PRICE` DOUBLE NOT NULL,
PRIMARY KEY (`ORDER_ID`,`PRODUCT_ID`),
CONSTRAINT `FK_PRODUCT_ORDER_ORDER_ID` FOREIGN KEY (`ORDER_ID`)
REFERENCES `order` (`ORDER_ID`),
CONSTRAINT `FK_PRODUCT_ORDER_PRODUCT_ID` FOREIGN KEY (`PRODUCT_ID`)
REFERENCES `product` (`PRODUCT_ID`)
);
And this are my classes (removed the getters/setters, left the annotations)
#Entity
#Table(name = "product")
public class Product implements java.io.Serializable {
private Integer productId;
private String name;
private String description;
private Double price;
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "PRODUCT_ID", unique = true, nullable = false)
#Column(name = "PRODUCT_NAME", nullable = false)
#Column(name = "PRODUCT_PRICE", nullable = false)
#Column(name = "PRODUCT_DESCRIPTION", nullable = false)
}
#Entity
#Table(name = "`order`")
public class Order implements java.io.Serializable {
private Integer orderId;
private Integer userId;
private Set<ProductOrder> productOrders = new HashSet<>(0);
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "ORDER_ID", unique = true, nullable = false)
#Column(name = "ORDER_USER_ID")
#OneToMany(fetch = FetchType.LAZY, mappedBy = "pk.order", cascade = CascadeType.ALL)
}
#Entity
#Table(name = "product_order")
#AssociationOverrides({
#AssociationOverride(name = "pk.order",
joinColumns = #JoinColumn(name = "ORDER_ID")),
#AssociationOverride(name = "pk.product",
joinColumns = #JoinColumn(name = "PRODUCT_ID")) })
public class ProductOrder implements java.io.Serializable {
private ProductOrderId pk = new ProductOrderId();
private Double price;
private Integer amount;
#EmbeddedId
//Getter/setter for primaryKey (pk)
#Transient
//Link to product
#Column(name = "PRICE")
#Column(name = "AMOUNT")
}
#Embeddable
public class ProductOrderId implements java.io.Serializable {
private Product product;
private Order order;
#ManyToOne
//link to Product
#ManyToOne
//Link to Order
}

Related

sql constraint violation exception

I have an entity Mathematics referenced by MathematicsAnswer. If a perform a post request on Mathematics, I get the exception that field on MathsAnswer cannot be null. But I actually did cascade on the field. Please I need solution this.
java.sql.SQLIntegrityConstraintViolationException: Column 'question_id' cannot be null
sql schema:
CREATE TABLE MATHEMATICS(
id integer not null auto_increment,
year date not null,
question_no int not null,
question varchar(128) default null,
primary key(id)
) engine=InnoDb;
CREATE TABLE MATHS_ANSWER(
id integer not null auto_increment,
date date default null,
question_no int not null,
question_id int not null,
solution varchar(128) default null,
solution_url varchar(128) default null,
primary key(id),
foreign key(question_id) references MATHEMATICS(id) ON DELETE NO ACTION ON UPDATE NO ACTION
) engine = InnoDb;
entity class:
#Entity
#Table(name = "Mathematics")
public class Mathematics {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer id;
#Column(name = "year")
private Date year;
#Column(name = "question_no")
private Integer questionNo;
#Column(name = "question")
private String question;
#OneToOne(mappedBy = "maths", fetch = FetchType.EAGER,cascade = CascadeType.ALL
)
private MathsAnswers answers = new MathsAnswers();//getters & setters
MathsAnswers.java:
#Entity
#Table(name = "Mathematics")
public class Mathematics {
#Id
#Column(name = "id")
#GeneratedValue(strategy = GenerationType.SEQUENCE)
private Integer id;
#Column(name = "year")
private Date year;
#Column(name = "question_no")
private Integer questionNo;
#Column(name = "question")
private String question;
#OneToOne(mappedBy = "maths", fetch = FetchType.EAGER,cascade = CascadeType.ALL
)
private MathsAnswers answers = new MathsAnswers();//getters & setters
jpaRepo:
#RepositoryRestResource(collectionResourceRel = "mathematics", path = "maths")
public interface MathsRepo extends JpaRepository<Mathematics, Integer> {
}
post request:
{
"year":"2004-01-03",
"questionNo":"4",
"question":"How many weeks makes a year?"
}
The table name specified for my MathsAnswer entity was wrong; should've been Mathsanswer instead of Mathematics.

How to fix automatic bigint generation in spring boot for table column

I have a spring boot application with two entities in a relationship. MeetingSetting and MeetingTime meetingSetting can have unlimited meetingTimes. So far the databases are generating without problem and I can halfway save the values as well. But there is one problem. meetingName is a string and used as a foreign key in meetingTime but when the database are generated for some reason it is added as a bigint and I could not find the reason for that, because everywhere it is used as string. Could someone look at my code and tell me my mistake?
MeetingSettings:
#Entity
#Table(name = "meeting_settings")
#Data
public class MeetingsSetting {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "meeting_name", unique = true)
private String meetingName;
#Column(name = "meeting_url")
private String meetingUrl;
#Column(name = "meeting_pw")
private String meetingPw;
#OneToMany(mappedBy = "meeting_Name", cascade = CascadeType.ALL)
private Set<MeetingTime> meetingTime = new HashSet<>();
}
MeetingTime:
#Entity
#Table(name = "meeting_times")
#Data
public class MeetingTime {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(name = "meeting_date")
private String date;
#Column(name = "start_time")
private String startTime;
#Column(name = "end_time")
private String endTime;
#ManyToOne
#JoinColumn(name = "meeting_name" ,insertable = false, updatable = false)
private MeetingsSetting meeting_Name;
}
This is my application property:
spring.datasource.url=jdbc:mysql://localhost:3306/coorporate_blinddate?createDatabaseIfNotExist=true&useSSL=true&serverTimezone=UTC
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL8Dialect
spring.jpa.properties.javax.persistence.schema-generation.scripts.create-target=../generate.sql
spring.jpa.show-sql= true
spring.jpa.generate-ddl=true
spring.jpa.hibernate.ddl-auto = update
spring.datasource.driver-class-name= com.mysql.jdbc.Driver
spring.datasource.username=root
spring.datasource.password=Test1234##1
server.port=8081
and the script used for db generation:
-- auto-generated definition
create table meeting_settings
(
id bigint auto_increment
primary key,
meeting_name varchar(255) null,
meeting_pw varchar(255) null,
meeting_url varchar(255) null
);
-- auto-generated definition
create table meeting_times
(
id bigint auto_increment
primary key,
meeting_date varchar(255) null,
start_time varchar(255) null,
end_time varchar(255) null,
meeting_name varchar(255) null,
constraint fk_meeting_times_meeting_name
foreign key (meeting_name) references meeting_settings (meeting_name)
);
I fixed this with the big int by adding referencedColumnName = "meeting_name" to this in meetingTime:
#ManyToOne
#JoinColumn(name = "meeting_name" ,insertable = false, updatable = false)
private MeetingsSetting meeting_Name;
changed to:
#ManyToOne
#JoinColumn(name = "meeting_name" ,insertable = false, updatable = false, referencedColumnName = "meeting_name")
private MeetingsSetting meeting_Name;

Add auto_increment in JPA entity

I use this entity definition for JPA:
#Entity
#Table(name = "payment_transactions")
public class PaymentTransactions implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", unique = true, updatable = false, nullable = false)
private int id;
#Column
private Date date;
#Column
private Integer year;
.....
}
Table is successfully created:
CREATE TABLE `payment_transactions` (
`id` int(11) NOT NULL,
....
PRIMARY KEY (`id`),
}
Table is successfully created.
But I would like MariaDB to auto-generate unique table key value. Like this:
CREATE TABLE `payment_transactions` (
`id` int(11) NOT NULL auto_increment,
....
PRIMARY KEY (`id`),
}
What is the proper way to configure this with JPA?

Saving Record in Relation Spring Boot

I am creating a project in spring boot which creates record by api call.
so I have two table ( name and phone ) below is my domain:
#Entity
#Table(name = "name")
public class Name {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
private Long id;
#Column(name = "name", nullable = false)
private String name;
#Column(name = "active", nullable = false)
private boolean active = true;
#LazyCollection(LazyCollectionOption.FALSE)
#OneToMany(mappedBy = "name")
#JsonIgnoreProperties("name")
private List<Phone> phones;
}
And
#Entity
#Table(name = "phone")
public class Phone {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false)
private Long id;
#Column(name = "number", nullable = false)
private String number;
#Column(name = "active", nullable = false)
private boolean active = true;
#ManyToOne(targetEntity= Name.class)
#JoinColumn(name="name_id"))
private Name name;
}
The Code to create the name is as follows:
public Name createNewName(Name createName) {
Name newName = new Name();
newName = NameRepo.save(createName);
return newName;
}
And Repository is:
#Repository
public interface NameRepository extends PagingAndSortingRepository<Name, Long> {}
So My problem is when i send a request using api to call this, Name does not store Phone values and also does not link if exist.
My request is as follows:
{
"name": "testrretf",
"active": true,
"phones":[{
"id":1
}]
}
This request should link the new Name to existing Phone id=1
And
{
"name": "testrretf",
"active": true,
"phones":[{
"number":"Test Phone",
"active":true,
}]
}
This request should create a Phone and link to the created Name.
Please help me..
Thanks,
UPDATE# Below is the Create Table Query:
CREATE TABLE `name` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`active` bit(1) NOT NULL,
`name` varchar(255) DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `IDX_NAME` (`name `),
KEY `IDX_NAME_ACTIVE` (`active`)
) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=latin1
CREATE TABLE `phone` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`active` bit(1) NOT NULL,
`name` varchar(255) DEFAULT NULL,
`name_id` bigint(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `IDX_PHONE_ACTIVE` (`active`),
KEY `fk_name_phone` (`name_id`),
CONSTRAINT `fk_name_phone` FOREIGN KEY (`name_id`) REFERENCES `name` (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=latin1

HIbernate Foreign key must have same number of columns as the referenced primary key Error

I have these two tables in my database:
CREATE TABLE classroom_trainee (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
trainee_id BIGINT(20) NOT NULL,
classroom_id BIGINT(20) NOT NULL,
completed BOOLEAN,
notes VARCHAR(255),
result INT(3),
feedback BOOLEAN DEFAULT 0,
PRIMARY KEY (id),
FOREIGN KEY (trainee_id)
REFERENCES user (id),
FOREIGN KEY (classroom_id)
REFERENCES classroom (id)
);
CREATE TABLE trainee_presence (
id BIGINT(20) NOT NULL AUTO_INCREMENT,
classroom_trainee_id BIGINT(20) NOT NULL,
day INT(2) NOT NULL,
presence BOOLEAN,
notes VARCHAR(255),
PRIMARY KEY (id),
FOREIGN KEY (classroom_trainee_id)
REFERENCES classroom_trainee (id)
);
and this is the Entities that I have:
UserEntity.java:
....
public class UserEntity implements Serializable {
...
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "manager_id")
private UserEntity manager;
#Column(name = "email", nullable = false, unique = true)
private String email;
#Column(name = "forename")
private String forename;
#Column(name = "surname")
private String surname;
...
ClassroomTraineeEntity.java
....
public class ClassroomTraineeEntity {
.....
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne
#JoinColumn(name="trainee_id")
private UserEntity trainee;
#ManyToOne
#JoinColumn(name="classroom_id")
private ClassroomEntity classroom;
....
TraineePresenceEntity.java
....
public class TraineePresenceEntity {
.......
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#ManyToOne
#JoinColumn(name="classroom_trainee_id")
private ClassroomTraineeEntity classroomTrainee;
#Column(name = "day")
private Integer day;
#Column(name = "presence")
private Boolean presence;
...
When in TraineePresenceEntity I use
#Column(name="classroom_trainee_id")
private Integer classroomTraineeId;
It all works fine and dandy, but with a ClassroomTraineeEntity object I get this exception:
Caused by: org.hibernate.MappingException: Foreign key (FKn85t08ggb5n6ail459koe0sm8:trainee_presence [classroom_trainee_id])) must have same number of columns as the referenced primary key (classroom_trainee [classroom_id,trainee_id])
Anyone knows how I can solve this problem?

Categories