Unable to convert between java.lang.Integer and BINARY.- Spring - java

I have the following DTO that I use to persist new records to my database
#Entity(name = "User")
public class User {
#Id
#Column(name = "User_Id")
private long userId;
#Column(name = "User_Name")
private String userNm;
#Column(name = "years_active")
private long years;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "Manager_Id", insertable = false, updatable = false)
private Manager manager;
#Column(name = "Projects",insertable = false, updatable = false)
private LinkedHashMap<Long, String> projects;
#Column(name = "Projects")
private long projectId;
#Column(name = "address")
private Address address;
//getters & setters
}
DDL:
CREATE TABLE [dbo].[User] (
[User_Id] int NOT NULL,
[User_Name] varchar(255) NOT NULL,
[years_active] int NOT NULL,
[Manager_id] int NOT NULL, //FK to Manager table
[Projects] int NOT NULL, //FK to Project table
[Address] int NULL, //FK to Address Table
[ModifiedBy] varchar(255) NOT NULL,
[ModifiedTS] datetime NULL)
I have no problem persisting data to this table via form submission, however when I try to retrieve an entity object using Spring Repository:
User user = userRepo.findOne(id); // id == Long, passed through #Controller method
I consistently get the following error : Unable to convert between java.lang.Integer and BINARY.
o.h.engine.jdbc.spi.SqlExceptionHelper : Unable to convert between java.lang.Integer and BINARY.
o.h.e.internal.DefaultLoadEventListener : HHH000327: Error performing load command :
org.hibernate.exception.DataException: Could not read entity state from ResultSet : EntityKey[com.myapp.entities.User#3]
I'm not sure where this conversion between integer and Binary is happening; any ideas?

Related

Table doesn't get created JPA

Table "books" doesn't get created somehow.
My books table:
#Entity
#Table(name = "books")
public class Book {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", nullable = false)
private Long id;
#ManyToOne(cascade = CascadeType.PERSIST)
#JoinColumn(name = "publisher_id", nullable = false)
private Publisher publisher;
#ManyToMany
#JoinTable(name = "authors_books", joinColumns = #JoinColumn(name = "book_id"),
inverseJoinColumns = #JoinColumn(name = "author_id"))
private Set<Author> authors;
#Column(name = "is_rented", nullable = false, columnDefinition = "DEFAULT FALSE")
private Boolean is_rented;
#Column(name = "isbn", nullable = false, unique = true, length = 300)
private String isbn;
Publishers table:
#Entity
#Table(name = "publishers")
public class Publisher {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", nullable = false)
private Long id;
#OneToMany(mappedBy = "publisher")
private Set<Book> books;
Authors table:
#Entity
#Table(name = "authors")
public class Author {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id", nullable = false)
private Long id;
#ManyToMany(mappedBy = "authors")
private Set<Book> books;
application.properties:
spring.jpa.hibernate.ddl-auto=create
spring.jpa.database=mysql
spring.datasource.url=jdbc:mysql://${MYSQL_HOST:localhost}:3306/<schema_name>?createDatabaseIfNotExist=true
spring.datasource.username=${MYSQL_USERNAME}
spring.datasource.password=${MYSQL_PASSWORD}
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
Omitted other fields, only reference fields left. I also ovverrid equals and hashcode methods in all entities. And I have empty constructors and full constructors, as well as getters and setters in all of them. Also added #EntityScan to SpringBootApplication file.
I get error:
Table '<schema_name>.authors_books' doesn't exist.
Table '<schema_name>.books' doesn't exist.
But all other tables do exist. Does anybody see what I am missing?
EDIT
Checked database manually. Table "authors_books" DOES exist(despite jpa telling me that it doesn't). Only "books" DOES NOT.
EDIT #2
I added to application.properties:
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
And it shows me:
org.hibernate.tool.schema.spi.CommandAcceptanceException: Error executing DDL "
create table books (
id bigint not null,
amount integer not null,
image varchar(300),
is_rented DEFAULT FALSE,
isbn varchar(300) not null,
published_on date,
title varchar(300) not null,
publisher_id bigint not null,
primary key (id)
) engine=InnoDB"
Caused by: java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DEFAULT FALSE,
isbn varchar(300) not null,
' at line 5
Looks like problem was with:
#Column(name = "is_rented", nullable = false, columnDefinition = "DEFAULT FALSE")
private Boolean is_rented;
If you configure columnDefinition, then Hibernate does not care about java-based data type you provided.
So the SQL was like:
is_rented DEFAULT FALSE,
which obviously lacks data type.
So I changed it into:
#Column(name = "is_rented", columnDefinition = "BOOLEAN DEFAULT FALSE")
private Boolean is_rented;
And it worked :)

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;

org.hibernate.exception.ConstraintViolationException: could not insert

When I try to add into TDEPOFAZLA table, I get the following error:
org.springframework.dao.DataIntegrityViolationException: could not insert: [tr.gov.tcmb.pgmtems.model.DepoFazla]; SQL [insert into PGMTEMS.TDEPOFAZLA (ID, FAZLABULUNDURMAORANI, GRUP) values (default, ?, ?)]; constraint [null]; nested exception is org.hibernate.exception.ConstraintViolationException: could not insert: [tr.gov.tcmb.pgmtems.model.DepoFazla]
Here is my JUnit test function:
#Test
public void testSaveDepoFazla() {
DepoTur depoTur = new DepoTur("my tür", 5);
depoTurService.saveDepoTur(depoTur);
List<DepoTur> list = depoTurService.getDepoTurList();
assertNotNull(list.get(0));
BigDecimal fazlaBulundurmaOrani = new BigDecimal(6000);
DepoFazla depoFazla = new DepoFazla(1, list.get(0), fazlaBulundurmaOrani);
depoFazlaService.saveDepoFazla(depoFazla);
}
Here is my DepoFazla.java:
#Entity
#Table(schema = "PGMTEMS", name = "TDEPOFAZLA")
public class DepoFazla implements Serializable {
private static final long serialVersionUID = -2800365387332643658L;
#Id
#GeneratedValue
#Column(name = "ID", nullable = false, updatable = false)
private Long id;
#Column(name = "GRUP", nullable = false, columnDefinition = "INTEGER")
private Integer grup;
#ManyToOne(fetch = FetchType.LAZY, targetEntity = DepoTur.class)
#JoinColumn(name = "ID", insertable = false, updatable = false)
#NotNull
private DepoTur depoTur;
#Column(name = "FAZLABULUNDURMAORANI", nullable = false, columnDefinition = "DECIMAL(6, 2)")
private BigDecimal fazlaBulundurmaOrani;
public DepoFazla() {
super();
}
public DepoFazla(Integer grup, DepoTur depoTur, BigDecimal fazlaBulundurmaOrani) {
super();
this.grup = grup;
this.depoTur = depoTur;
this.fazlaBulundurmaOrani = fazlaBulundurmaOrani;
}
//GETTER AND SETTER METHODS
}
Here is DepoTur.java:
#Entity
#Table(schema = "PGMTEMS", name = "TDEPOTUR")
public class DepoTur implements Serializable {
private static final long serialVersionUID = 6203672609079710060L;
#Id
#GeneratedValue
#Column(name = "ID", nullable = false, updatable = false)
#Index(name = "XUTDEPOTURP", columnNames = { "id" })
private Long id;
#Column(name = "ACIKLAMA", nullable = false)
private String aciklama;
#Column(name = "BLOKESIRASI", nullable = false)
private Integer blokeSirasi; //
#Column(name = "DEPOCINSI")
private String depoCinsi;
public DepoTur() {
super();
}
public DepoTur(String aciklama, Integer blokeSirasi, String depoCinsi) {
super();
this.aciklama = aciklama;
this.depoCinsi = depoCinsi;
this.blokeSirasi = blokeSirasi;
}
public DepoTur(String aciklama, Integer blokeSirasi) {
super();
this.aciklama = aciklama;
this.blokeSirasi = blokeSirasi;
}
//GETTER AND SETTER METHODS
When I debug the JUnit test, I get this error:
Error: DB2 SQL Error: SQLCODE=-407, SQLSTATE=23502, SQLERRMC=TBSPACEID=2, TABLEID=75, COLNO=2, DRIVER=3.50.152 SQLState: 23502 ErrorCode: -407
When I search the error, I find that I try to insert NULL but I can't figure out where I add null value.
This is how I create TDEPOFAZLA table:
CREATE TABLE TDEPOFAZLA
(
ID decimal(20,0) PRIMARY KEY NOT NULL,
GRUP int NOT NULL,
DEPOTUR decimal(20,0) NOT NULL,
FAZLABULUNDURMAORANI decimal(6,2) NOT NULL
);
CREATE UNIQUE INDEX XUTDEPOFAZLAP ON TDEPOFAZLA(ID);
This is how I create TDEPOTUR table:
CREATE TABLE TDEPOTUR
(
ID decimal(20,0) PRIMARY KEY NOT NULL,
ACIKLAMA varchar(100) NOT NULL,
DEPOCINSI char(1),
BLOKESIRASI int NOT NULL
);
CREATE UNIQUE INDEX XUTDEPOTURP ON TDEPOTUR(ID);
Any ideas on what I should do?
Your property definition with the FK is wrong, as i saw you use updatable, insertable to false, you what really want is that the FK object is not modified because could be a master table common for some other entities.
Then what you can use is this
#ManyToOne(cascade= {CascadeType.DETACH})
#JoinColumn(name = "DEPOTUR")
#NotNull
private DepoTur depoTur;
With DETACH, you will save the value only in the first table, column DEPOTUR and wont update the object in the DepoTur table
Also add the FK in your first table
CREATE TABLE TDEPOFAZLA
(
ID decimal(20,0) PRIMARY KEY NOT NULL,
GRUP int NOT NULL,
DEPOTUR decimal(20,0) NOT NULL,
FAZLABULUNDURMAORANI decimal(6,2) NOT NULL
);
CREATE UNIQUE INDEX XUTDEPOFAZLAP ON TDEPOFAZLA(ID);
CONSTRAINT fk_column FOREIGN KEY (DEPOTUR) REFERENCES TDEPOTUR(ID);
The problem was that I didn't reference the join column properly. This solved the problem:
#ManyToOne(fetch = FetchType.LAZY, optional = false)
#JoinColumn(name = "DEPOTUR", referencedColumnName = "ID", nullable = false, columnDefinition = "DECIMAL(20,0)")
#NotNull
private DepoTur depoTur;
It appears that you specified the same name for the join column Id twice in your DepoFazla model you have to change its name use for example :
#Entity
#Table(schema = "PGMTEMS", name = "TDEPOFAZLA")
public class DepoFazla implements Serializable {
private static final long serialVersionUID = -2800365387332643658L;
...
#ManyToOne(fetch = FetchType.LAZY, targetEntity = DepoTur.class)
#JoinColumn(name = "ID_depoTur", insertable = false, updatable = false)
#NotNull
private DepoTur depoTur;
...
}

Database column requires int, but doesn't throw exception when string is inputted

I have a rest service which has a database. When I add an entity to my database in an EJB using a entityfacade, one entity variable price requires an real. If I input the price as a string in xml format from a client, no exception is thrown and the database registers 0 instead. If I make the variable too large the proper exception is thrown.
Any ideas of why this is happening? Or is there a way if setting my database table to accept integer only?
#Entity
#Table(name = "BOOKS", catalog = "", schema = "DAVID")
#XmlRootElement
public class Books implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
//#NotNull
#Column(name = "BOOKID")
private Integer bookid;
#Basic(optional = false)
#NotNull
#Column(name = "ISBN")
private long isbn;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 40)
#Column(name = "PUBLISHER")
private String publisher;
#Column(name = "QUANTITY")
private int quantity;
#Basic(optional = false)
#NotNull
#Column(name = "PRICE")
private float price;
CREATE TABLE BOOKS (BOOKID INTEGER DEFAULT AUTOINCREMENT: start 1 increment 1 NOT NULL GENERATED ALWAYS AS IDENTITY, ISBN BIGINT NOT NULL, TITLE VARCHAR(100) NOT NULL, COPYRIGHT VARCHAR(4) NOT NULL, PUBLISHER VARCHAR(40) NOT NULL, QUANTITY INTEGER, PRICE REAL NOT NULL, PRIMARY KEY (BOOKID));

Categories