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.
Related
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;
I've been struggling with this for so long now. I have a database with two tables "product" and "categories"
CREATE TABLE `product` (
`idproduct` int NOT NULL AUTO_INCREMENT,
`idcategory` int DEFAULT NULL,
`product_name` varchar(255) DEFAULT NULL,
`product_category` varchar(255) DEFAULT NULL,
`product_description` varchar(255) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`idproduct`),
KEY `fkcat` (`idcategory`),
CONSTRAINT `fkcat` FOREIGN KEY (`idcategory`) REFERENCES `categories` (`idcategory`)
) ENGINE=InnoDB AUTO_INCREMENT=149 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
CREATE TABLE `categories` (
`idcategory` int NOT NULL AUTO_INCREMENT,
`category_name` varchar(255) NOT NULL,
`category_description` varchar(255) DEFAULT NULL,
`created_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP,
`updated_at` timestamp NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`idcategory`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci
Now I'm trying to get a hibernate join query so I can retrieve let's say
product_name and category_name
One product belongs only to one category (for example, if the product is "black t-shirt", its value for the column "idcategory" would be 2. This is enforced by the foreign key.
The table categories entries can be associated with more than one product (for example, "category_name" = 2 can be associated with many products.
How can this design be implemented in hibernate entities? I've tried this but isn't working...
#Entity
#Table(name = "product")
public class Product implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idproduct")
private int idproduct;
#Column(name = "idcategory")
private int idcategory;
#Column(name = "product_name")
private String productName;
#Column(name = "product_description")
private String productdescription;
#Column(name = "product_category")
private String productcategory;
#OneToMany(targetEntity = Categories.class, cascade = CascadeType.ALL)
#JoinColumn(name = "idcategory",referencedColumnName="idcategory")
private List<Categories> category;
#Entity
#Table(name = "categories")
public class Categories {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idcategory")
private int idcategory;
#Column(name = "category_name")
private String category_name;
#Column(name = "category_description")
private String category_description;
and the query is
SELECT p, c FROM Product p INNER JOIN p.category c
this is not correct
#OneToMany(targetEntity = Categories.class, cascade = CascadeType.ALL)
#JoinColumn(name = "idcategory",referencedColumnName="idcategory")
private List<Categories> category;
Product can't have many categories... it is actually the reverse ->
#Entity
#Table(name = "categories")
public class Categories {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idcategory")
private int idcategory;
#Column(name = "category_name")
private String category_name;
#Column(name = "category_description")
private String category_description;
#OneToMany(cascade = CascadeType.ALL, mappedBy="category")
private List<Product> products;
and Product
#Entity
#Table(name = "product")
public class Product implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idproduct")
private int idproduct;
#Column(name = "idcategory")
private int idcategory;
#Column(name = "product_name")
private String productName;
#Column(name = "product_description")
private String productdescription;
#Column(name = "product_category")
private String productcategory;
#ManyToOne
private Categories categories;
Suggestion : rename Categories to Category
First of all, apologize for the grammatical errors that you can make. My English is not very good.
I'm trying to create dinamically an Entity and relathion with other Entity.
The idea is send a json file and get some properties to create that Entity, later associate that entity with the other. However, I can't because throw Exception like:
attempted to assign id from null one-to-one property
So, here in my SchemeService I try to create both entities:
protected Scheme createScheme(final String creatorId, final String name, final String description, final InputStream inputStream) {
DeserializeJSONFile desJsonFile = new DeserializeJSONFile();
desJsonFile.init(inputStream);
TableEntity table = new TableEntity();
table.setCreator(creatorId);
table.setProperties(desJsonFile.getProperties().toString());
table.setGeometry(desJsonFile.getGeometry().toString());
createTable(table);
Scheme scheme = new Scheme();
scheme.setCreator(creatorId);
scheme.setName(name);
scheme.setDescription(description);
scheme.setTable(table);
createScheme(scheme);
return scheme;
}
private void createTable(final TableEntity table) {
tableDao.create(table);
}
protected void createScheme(final Scheme scheme) {
schemeDao.create(scheme);
}
Here is my TableEntity:
public class TableEntity extends BaseEntityActivable implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SCHEME_SEQ_GEN")
#SequenceGenerator(name = "SCHEME_SEQ_GEN", sequenceName = "test_seq_table", allocationSize = 1)
#Column(name = "table_id")
private Long tableId;
#Type(type= "jsonb")
#Column(name = "properties", columnDefinition = "json")
private String properties;
#Type(type= "jsonb")
#Column(name = "geometry", columnDefinition = "json")
private String geometry;
#OneToOne
#MapsId
private Scheme scheme;
}
Here is my SchemeEntity:
public class Scheme extends BaseEntityActivable implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SCHEME_SEQ_GEN")
#SequenceGenerator(name = "SCHEME_SEQ_GEN", sequenceName = "test_seq_scheme", allocationSize = 1)
#Column(name = "scheme_id")
private Long schemeId;
#Column(name = "name", nullable = false)
#NotEmpty(message = AxisMapsErrorConstants.NAME_CANT_BE_EMPTY)
private String name;
#Column(name = "description")
private String description;
#OneToOne(mappedBy = "scheme", cascade = CascadeType.ALL)
#JoinColumn(name = "scheme_id", referencedColumnName = "table_id", foreignKey = #ForeignKey(name = "fk_scheme_table_1"))
private TableEntity table;
}
Here is my sql:
create sequence test_seq_table start 1 increment 1;
create sequence test_seq_scheme start 1 increment 1;
create table maps_table (
table_id int8 not null,
created_at timestamp not null,
created_by varchar(255),
updated_at timestamp,
updated_by varchar(255),
is_active boolean not null,
properties jsonb not null,
geometry jsonb not null,
primary key (table_id)
);
create table maps_scheme (
scheme_id int8 not null,
created_at timestamp not null,
created_by varchar(255),
updated_at timestamp,
updated_by varchar(255),
is_active boolean not null,
description varchar(255),
name varchar(255) not null,
table_id int8 not null,
primary key (scheme_id)
);
alter table maps_scheme
add constraint fk_scheme_table_1
foreign key (scheme_id)
references maps_table;
since you are using #mapsId this means you are using the same identifier in your relation with scheme, which means first the scheme should not be nullable and it should be available as managed entity each time your object is flushed, which also means that you can do the persistence only from one side of the relation since the id of scheme should be available when persisting your entity.
I am not sure if you really need #mapsId here, since you already have a bidirectional relation which means anyway you will be able to access both sides of your entity.
I would suggest to remove #mapsId here.
Thanks everyone for helping me.
This is my solution.
Scheme:
public class Scheme extends BaseEntityActivable implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SCHEME_SEQ_GEN")
#SequenceGenerator(name = "SCHEME_SEQ_GEN", sequenceName = "aguas_seq_scheme", allocationSize = 1)
#Column(name = "scheme_id")
private Long schemeId;
#Column(name = "name", nullable = false)
#NotEmpty(message = AxisMapsErrorConstants.NAME_CANT_BE_EMPTY)
private String name;
#Column(name = "description")
private String description;
#OneToOne(cascade= { CascadeType.ALL }, fetch = FetchType.LAZY)
#JoinColumn(name="table_id")
private TableEntity table;
}
TableEntity:
public class TableEntity extends BaseEntityActivable implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "SCHEME_SEQ_GEN")
#SequenceGenerator(name = "SCHEME_SEQ_GEN", sequenceName = "aguas_seq_table", allocationSize = 1)
#Column(name = "table_id")
private Long tableId;
#Type(type= "jsonb")
#Column(name = "properties", columnDefinition = "json")
private String properties;
#Type(type= "jsonb")
#Column(name = "geometry", columnDefinition = "json")
private String geometry;
#OneToOne(mappedBy= "table")
private Scheme scheme;
}
SQL:
create sequence aguas_seq_table start 1 increment 1;
create sequence aguas_seq_scheme start 1 increment 1;
create table maps_table (
table_id int8 not null,
created_at timestamp not null,
created_by varchar(255),
updated_at timestamp,
updated_by varchar(255),
is_active boolean not null,
properties jsonb not null,
geometry jsonb not null,
primary key (table_id)
);
create table maps_scheme (
scheme_id int8 not null,
created_at timestamp not null,
created_by varchar(255),
updated_at timestamp,
updated_by varchar(255),
is_active boolean not null,
description varchar(255),
name varchar(255) not null,
table_id int8 not null,
primary key (scheme_id)
);
SchemeService to create scheme and table:
protected Scheme createScheme(final String creatorId, final String name, final String description, final InputStream inputStream) {
DeserializeJSONFile desJsonFile = new DeserializeJSONFile();
desJsonFile.init(inputStream);
TableEntity table = new TableEntity();
table.setCreator(creatorId);
table.setGeometry(desJsonFile.loadGeometries().toString());
table.setProperties(desJsonFile.loadProperties().toString());
createTable(table);
Scheme scheme = new Scheme();
scheme.setCreator(creatorId);
scheme.setName(name);
scheme.setDescription(description);
scheme.setTable(table);
createScheme(scheme);
return scheme;
}
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?
Can anyone help me with this and tell me what I'm missing. Have gone through a number of examples and seem to have everything configured correctly but I keep getting this exception:
org.hibernate.AnnotationException: A Foreign key refering com.bank.entity.Customer from com.bank.entity.Account has the wrong number of column. should be 2
I have a class called Branch that has 1:M relationship with Customer. Customer in turn has a 1:M relationship with Account.
Note: Customer also has an embeddable Address class
Here is my code:
Branch Class
#Entity
#Table(name = "Branch")
public class Branch extends AbstractPersistable<Long> implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "branch_Name")
private String branchName;
#OneToMany(mappedBy = "branch")
private Set<Customer> customers;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
Embeddable Address Class
#Embeddable
public class Address {
#Column(name = "houseNumber", nullable = false)
private String houseNumber;
#Column(name = "streetName", nullable = false)
private String streetName;
#Column(name = "city", nullable = false)
private String city;
#Column(name = "country", nullable = false)
private String country;
#Column(name = "eirCode", nullable = false)
private String eirCode;
}
Customer Class
#Entity
#Table(name = "Customer")
public class Customer extends AbstractPersistable<Long> implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "first_Name")
private String firstName;
#Column(name = "surname")
private String surName;
#Embedded
Address address;
#ManyToOne
#JoinColumn(name = "branchId", nullable = false)
private Branch branch;
#OneToMany(mappedBy = "customer")
private Set<Account> accounts;
}
Account Class
#Entity
#Table(name = "Account")
public class Account extends AbstractPersistable<Long> implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "account_type")
private String type;
#Column(name = "interest_rate")
private double rate;
#Column(name = "account_balance")
private double balance;
#ManyToOne
#JoinColumn(name = "customerId", nullable = false)
private Customer customer;
}
Here I create the tables
CREATE TABLE IF NOT EXISTS `Branch` (
`id` BIGINT(10) NOT NULL AUTO_INCREMENT,
`branch_Name` VARCHAR(25) NOT NULL,
PRIMARY KEY (`id`)
);
CREATE TABLE IF NOT EXISTS `Customer` (
`id` BIGINT(10) NOT NULL AUTO_INCREMENT,
`first_Name` VARCHAR(25) NOT NULL,
`surname` VARCHAR(25) NOT NULL,
`houseNumber` VARCHAR(25) NOT NULL,
`streetName` VARCHAR(120) NOT NULL,
`city` VARCHAR(25) NOT NULL,
`country` VARCHAR(25) NOT NULL,
`eirCode` VARCHAR(25) NOT NULL,
`branchId` BIGINT(10) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_CUST_BRANCH` (`branchId`),
CONSTRAINT `FK_CUST_BRANCH` FOREIGN KEY (`branchId`) REFERENCES `Branch` (`id`)
);
CREATE TABLE IF NOT EXISTS `Account` (
`id` BIGINT(10) NOT NULL AUTO_INCREMENT,
`account_type` VARCHAR(25) NOT NULL,
`interest_rate` DOUBLE NOT NULL,
`account_balance` DOUBLE NOT NULL,
`customerId` BIGINT(10) NOT NULL,
PRIMARY KEY (`id`),
KEY `FK_CUST_ACC` (`customerId`),
CONSTRAINT `FK_CUST_ACC` FOREIGN KEY (`customerId`) REFERENCES `Customer` (`id`)
);
In Account you are saying :
#ManyToOne
#JoinColumn(name = "customerId", nullable = false)
private Customer customer;
But there is not column with name customerId(?) so you should give name to primary key of Customer
try changing this in Customer
#Entity
#Table(name = "Customer")
public class Customer extends AbstractPersistable<Long> implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="customerId")
private Long id;
...
}