#Data
#Entity
#Table(name = "test_jpa")
public class TestEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id",length = 19)
private Long id;
#Column(name = "length",precision = 10)
private Long length;
#Column(name = "test", length = 19)
private String test;
}
Log print:
Hibernate: create table test_jpa (id bigint not null, length bigint, test varchar(19), primary key (id)) engine=InnoDB
The length of Long value ,do not work.Also I tried #Size and #Length, same problem.
JPA version:2.6.7
Mysql
Thank you M. Deinum.
I get it, Numeric types no need to set length,They have fixed range.
Related
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.
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 created the table in the H2 database as follows:
CREATE OR REPLACE SEQUENCE IF NOT EXISTS SCMSA_HIST.KEY_GEN_SEQ
START WITH 0
INCREMENT BY 1
NOCYCLE
NOCACHE;
CREATE TABLE IF NOT EXISTS SCMSA_HIST.SCMSA_POS_TRANS_ROLLUP
(
POS_TRANS_ID INTEGER DEFAULT
(NEXT VALUE FOR SCMSA_HIST.KEY_GEN_SEQ)
NOT NULL IDENTITY ,
JOB_LOG_ID INTEGER,
DEALER_CODE VARCHAR(255),
STORE_ID VARCHAR(255),
TRANSACTION_DT TIMESTAMP,
QUANTITY INTEGER,
ROLLUP_TYPE VARCHAR(255),
CREATE_DT TIMESTAMP,
MAX_TRANSACTION_DT TIMESTAMP,
PROCESSED_FLAG VARCHAR(255),
CREATE_MONTH INTEGER,
CREATE_YEAR INTEGER
);
The Model class for the above table is as follows:
#Entity
#Table(schema = "SCMSA_HIST", name = "SCMSA_POS_TRANS_ROLLUP")
public class ScmsaPosTransRollup {
#Id
#GeneratedValue(strategy = GenerationType.AUTO, generator = "SEQ")
#SequenceGenerator(name = "SEQ", sequenceName = "SCMSA_HIST.KEY_GEN_SEQ")
#Column(name = "POS_TRANS_ID")
private Long posTransId;
#Column(name = "JOB_LOG_ID")
private Long jobLogId;
#Column(name = "DEALER_CODE")
private String dealerCode;
#Column(name = "STORE_ID")
private String storeId;
#Column(name = "TRANSACTION_DT")
private Timestamp transactionDate;
#Column(name = "ROLLUP_TYPE")
private String rollupType;
#Column(name = "QUANTITY")
private Integer quantity;
#Column(name = "CREATE_DT")
private Timestamp createDate;
#Column(name = "MAX_TRANSACTION_DT")
private Timestamp maxTransactionDate;
#Column(name = "PROCESSED_FLAG")
private String processedFlag;
#Column(name = "CREATE_MONTH", insertable = false, updatable = false)
private Integer createMonth;
#Column(name = "CREATE_YEAR", insertable = false, updatable = false)
private Integer createYear;
public ScmsaPosTransRollup() {
}
//getter and setter
}
But, when I am trying to insert , the value for the "POS_TRANS_ID" is inserted as null. Can anyone please suggest me what am doing wrong here.
I tried to reproduce your problem. What helps to me:
1. Scripts
CREATE OR REPLACE SEQUENCE IF NOT EXISTS KEY_GEN_SEQ
MINVALUE 1
MAXVALUE 999999999999999999
START WITH 1
INCREMENT BY 500
NOCYCLE
NOCACHE;
In create table DDL I replaced ID creation
POS_TRANS_ID INTEGER DEFAULT KEY_GEN_SEQ.NEXTVAL
NOT NULL IDENTITY ,
In Java class added initialValue and allocationSize to #SequenceGenerator, and changed strategy to SEQUENCE
#GeneratedValue(strategy=SEQUENCE, generator="SEQ")
#SequenceGenerator(name = "SEQ", sequenceName = "KEY_GEN_SEQ",initialValue = 1,allocationSize = 500)
And don't forget to define dialect in Hibernate props
hibernate.dialect=org.hibernate.dialect.H2Dialect
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));