I have a table, which has a column "description" of type TEXT. If I do:
SELECT id, description FROM table_name;
I see in "description" column instead of text value a number. Is there any way to see the text value?
Edit: After some testing I found out why I see numbers, but others like Craig see real text. It's because the data are inserted using Hibernate.
Entity:
#Entity
public class Settings {
#Id
#GeneratedValue
private Integer id;
#Column(nullable = false, unique = true)
private String key;
#Lob
#Column(nullable = false, length = Integer.MAX_VALUE)
private String value;
// getters and setters
}
Log result:
Hibernate: create table Settings (id int4 not null, key varchar(255) not null, value text not null, primary key (id));
Hibernate: select nextval ('hibernate_sequence')
Hibernate: insert into Settings (key, value, id) values (?, ?, ?)
16:05:32,718 TRACE BasicBinder:81 - binding parameter [1] as [VARCHAR] - [GoogleSiteVerification]
16:05:32,718 TRACE BasicBinder:81 - binding parameter [2] as [CLOB] - []
16:05:32,726 TRACE BasicBinder:81 - binding parameter [3] as [INTEGER] - [4]
If I do in pgAdmin3 this select:
select * from settings;
I see this result:
1;"GoogleSiteVerification";"112351"
Added #Type(type = "org.hibernate.type.TextType") to attribute annotated with #Lob. Now it works as desired.
Also it solved the issue with encoding, which was the reason I opened pgAdmin in the first place (to see what's inside).
Technical detail: PostgreSQL stored LOB in separate place and referenced it by a numerical identifier (which was what the number which confused me).
Setup:
CREATE TABLE table_name (id integer, description text);
INSERT INTO table_name(id, description) values (1, '12');
Demo:
testdb=> SELECT id, description FROM table_name;
id | description
----+-------------
1 | 12
(1 row)
Yup, I'd say you have a number in your description column because there's a number in your description column.
Related
I get this error when I try to run start my application:
org.springframework.dao.DataIntegrityViolationException: could not execute query; SQL [SELECT * FROM testquestions ORDER by id DESC LIMIT 1]; nested exception is org.hibernate.exception.DataException: could not execute query
As seen in previous problems on StackOverflow, I tried to adjust the length of my data input in my sql file and I've set the length of my #Column to the same amount of characters. this didn't help.
this is my #Table class:
#Entity
#Getter
#Setter
#Table(name = "testquestions")
public class TestQuestion {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "questiontitle", length = 2000)
private String questionTitle;
#Column(name = "info", length = 4096)
private String Info;
#Column(name = "solvetime")
private int solveTime;
#Column(name = "difficultylevel")
private DifficultyLevel difficultyLevel;
#Column(name = "questionimage")
private Image questionImage;
public TestQuestion(){
}
public TestQuestion(int id, String questionTitle, String info, DifficultyLevel difficultyLevel) {
this.id = id;
this.questionTitle = questionTitle;
Info = info;
this.difficultyLevel = difficultyLevel;
}
public String getInfo() {
return Info;
}
}
This is my # Query in my QuestionRepository:
#Query(value = "SELECT * FROM testquestions ORDER by id DESC LIMIT 1", nativeQuery = true)
TestQuestion fetchLastQuestion();
This is my database.sql file, it writes to a PostgreSQL data base:
TRUNCATE TABLE users CASCADE;
TRUNCATE TABLE testquestions CASCADE;
DROP TABLE users;
DROP TABLE testquestions;
CREATE TABLE users(
id int,
username varchar(255),
password varchar(255),
role varchar(255)
);
CREATE TABLE testquestions(
id int primary key ,
questiontitle varchar(2000),
info varchar(4096),
solvetime int,
difficultylevel varchar(255),
questionimage bytea
);
INSERT INTO users(id, username, password, role)
VALUES (0, 'user', 'u', 'user'),
(1, 'user','u','user');
INSERT INTO testquestions(id,questiontitle, info, solvetime, difficultylevel, questionimage)
VALUES (0, 'Multiple Databases', 'A company wants to use Spring Boot in a web application which should use JPA as a database abstraction. The unit tests should be run on an H2 database while the production should run on a MySQL database.
Select all the things that need to be done or that will be done automatically by Spring Boot.', 3, 'Easy',
''),
(1, 'Screen Orientation', 'Which of these methods are called when the screen changes orientation from portrait to landscape in Android?',
3, 'Easy',''),
(2, 'Merge Names', 'Implement the uniqueNames method. When passed two arrays of names, it will return an array containing the names that appear in either or both arrays. The returned array should have no duplicates.
For example, calling MergeNames.uniqueNames(new String[]{''Ava'', ''Emma'', ''Olivia''}, new String[]{''Olivia'', ''Sophia'', ''Emma''}) should return an array containing Ava, Emma, Olivia, and Sophia in any order.',
10, 'Easy',''),
(3, 'Date', 'Write a function that converts user entered date formatted as M/D/YYYY to a format required by an API (YYYYMMDD). The parameter "userDate" and the return value are strings.
For example, it should convert user entered date "12/31/2014" to "20141231" suitable for the API.', 10, 'Easy', ''),
(4, 'Inspector', 'Fix the bugs in the following HTML code.', 10, 'Easy',''),
(5, 'Train Composition', 'A TrainComposition is built by attaching and detaching wagons from the left and the right sides, efficiently with respect to time used.
For example, if we start by attaching wagon 7 from the left followed by attaching wagon 13, again from the left, we get a composition of two wagons (13 and 7 from left to right). Now the first wagon that can be detached from the right is 7 and the first that can be detached from the left is 13.
Implement a TrainComposition that models this problem.', 20, 'Hard', '');
Has anyone got an idea how to fix this error?
Thanks!
Tom
I'am trying to do an unidirectional #OneTaMany relationship like in the Hibernate User Guide (2.7.2) but when I try to save the following object in a MariaDB Database:
Filter filter = new Filter("TLS_A320");
filter.addConstraint(new Constraint(ConstraintType.DEPARTURE, "TLS"));
filter.addConstraint(new Constraint(ConstraintType.AIRCRAFT, "A320"));
session.save(filter);
I got this exception :
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'Filter_idFilter' in 'field list'
Here are the 2 classes:
Filter.java
public class Filter {
#Id
#Column(name = "idFilter")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "name")
private String name;
#OneToMany(cascade = CascadeType.ALL, orphanRemoval = true)
private List<Constraint> constraintList;
//more code
};
Constraint.java
public class Constraint {
#Id
#Column(name = "idConstraint")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Column(name = "type")
#Enumerated(EnumType.ORDINAL)
private ConstraintType constraintType;
#Column(name = "value")
private String value;
//more code
}
And here is the tables definition :
CREATE TABLE `Constraint` (
idConstraint INT NOT NULL AUTO_INCREMENT,
type INT NOT NULL,
value VARCHAR(10) NOT NULL,
PRIMARY KEY (idConstraint)
);
CREATE TABLE Filter (
idFilter INT NOT NULL AUTO_INCREMENT,
name VARCHAR(50) UNIQUE NOT NULL,
PRIMARY KEY (idFilter)
);
CREATE TABLE Filter_Constraint (
idFilter INT UNIQUE NOT NULL,
idConstraint INT NOT NULL,
CONSTRAINT fk_Filter_Constraint_Filter FOREIGN KEY (idFilter) REFERENCES Filter(idFilter),
CONSTRAINT fk_Filter_Constraint_Constraint FOREIGN KEY (idConstraint) REFERENCES `Constraint`(idConstraint)
);
It seems to me that that Filter and Constraint insertions are fine and the exception happens when inserting in the Filter_Constraint table :
DEBUG org.hibernate.SQL - insert into Filter (name) values (?)
DEBUG org.hibernate.id.IdentifierGeneratorHelper - Natively generated identity: 4
DEBUG org.hibernate.SQL - insert into `Constraint` (type, value) values (?, ?)
DEBUG org.hibernate.id.IdentifierGeneratorHelper - Natively generated identity: 5
DEBUG org.hibernate.SQL - insert into `Constraint` (type, value) values (?, ?)
DEBUG org.hibernate.id.IdentifierGeneratorHelper - Natively generated identity: 6
DEBUG org.hibernate.SQL - insert into `Filter_Constraint` (Filter_idFilter, `constraintList_idConstraint`) values (?, ?)
DEBUG org.hibernate.engine.jdbc.spi.SqlExceptionHelper - could not execute statement [n/a]
DEBUG com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: Unknown column 'Filter_idFilter' in 'field list'
I'am pretty new to Hibernate and I just can't figure out what I did wrong.
You didn't define any join column or inverse join column on constraintList, hence Hibernate will autogenerate column names which most probably results in the name Filter_idFilter.
The entity name will be part of the name since Constraints could have an id field with the same name, i.e. idFilter. Of course you know that isn't the case but Hibernate doesn't (or at least the column name generation code isn't that complex) and hence it has to assume that could be the case.
The same is true for join table names so you'll probably want to use #JoinTable along with the definition of join columns and inverse join columns on constraintList. However, since the relation is OneToMany anyways, why don't you add a back reference to Constraint, add the filter's id to table Constraint and get rid of the join table entirely?
I have the following entity TitleScreenFormat and when i do entitymanager.commit
I getting the following error
Internal Exception: java.sql.SQLIntegrityConstraintViolationException:
The statement was aborted because it would have caused a duplicate key
value in a unique or primary key constraint or unique index identified
by 'SQL130418144233630' defined on 'S1_TITLESCREENFORMAT'. Error Code:
20000 Call: INSERT INTO s1_TitleScreenFormat
(titlescreenformat_titleid, titlescreenformat_format,
titlescreenformat_deliveryformat, TITLE_title_id) VALUES (?, ?, ?, ?)
bind => [TitleId1, Format1, DeliveryFormat1, null]
This is the entity with the keys
#Entity
#Table(name = "s1_TitleScreenFormat")
public class TitleScreenFormat
{
#Id
#Column(name = "titlescreenformat_titleid", length = 128)
private String TitleId;
#Id
#Column(name = "titlescreenformat_deliveryformat", length = 128)
private String DeliveryFormat;
#Id
#Column(name = "titlescreenformat_format", length = 128)
private String Format;
private Title Title;
And this is the instance of the object which i have want to persist
[0] TitleScreenFormat (id=81)
DeliveryFormat "DeliveryFormat1" (id=87)
Format "Format1" (id=88)
Title null
TitleId "TitleId1" (id=89)
[1] TitleScreenFormat (id=83)
DeliveryFormat "DeliveryFormat2" (id=90)
Format "Format2" (id=91)
Title null
TitleId "TitleId2" (id=92)
[2] TitleScreenFormat (id=84)
DeliveryFormat "DeliveryFormat3" (id=93)
Format "Format3" (id=94)
Title null
TitleId "TitleId3" (id=95)
[3] TitleScreenFormat (id=85)
DeliveryFormat "DeliveryFormat4" (id=96)
Format "Format4" (id=97)
Title null
TitleId "TitleId4" (id=98)
[4] TitleScreenFormat (id=86)
DeliveryFormat "DeliveryFormat5" (id=99)
Format "Format5" (id=100)
Title null
TitleId "TitleId5" (id=101)
in the persistence.xml file i use the following configuration
<property name="eclipselink.ddl-generation" value="drop-and-create-tables" />
And Im using Derby DB.
What could be the reason for this error?
I think you are inserting same values again in the DB.
Just check once in your DB before persisting these values, if they are already existing there.
Alternatively you can change these values and try committing again.
I need to use the GenerationType.sequence strategy for a table
I write the follow annotation in the class:
#Id
#SequenceGenerator(name="SEQ_PERFIL", sequenceName="SEQ_PERFIL",allocationSize=1)
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="SEQ_PERFIL")
#Column(name="PER_CODPERFIL", nullable = false)
private long perCodperfil;
To insert I use this code:
entityManager.getTransaction().begin();
entityManager.persist(entity);
entityManager.flush();
entityManager.refresh(entity);
entityManager.getTransaction().commit();
When I insert the sequence is incremented (I show that in the database), but the insertion fail, because the primary key is null
It said :
Error Code: 1400
Call: INSERT INTO PERFIL (PER_CODPERFIL) VALUES (?) bind => [1 parameters bound]
Query: InsertObjectQuery(24)
and it said that PER_CODPERFIL is null
I use Eclipse-link and a Oracle DB
The sentence loggued by eclipse link is :
15:05:36,651 INFO [EclipseLog] SELECT SEQ_SIAC_PERFIL.NEXTVAL FROM DUAL
15:05:36,761 INFO [EclipseLog] INSERT INTO PERFIL (PER_CODPERFIL) VALUES (?) bind => [null]
15:05:36,773 INFO [EclipseLog] SELECT 1 FROM DUAL
I've mapped my class as follow (omitted other fields as only ID matters):
#Entity
#Table(name = "MODEL_GROUP")
#Cache(usage = CacheConcurrencyStrategy.TRANSACTIONAL)
public class SettlementModelGroup implements Serializable
{
#Id
#GeneratedValue(generator = "MODEL_GROUP_SEQ", strategy = GenerationType.SEQUENCE)
#GenericGenerator(name = "MODEL_GROUP_SEQ",
strategy = "sequence",
parameters = #Parameter(name = "sequence", value = "SEQ_MODEL_GROUP_MODEL_GROUP_ID"))
#Column(name = "MODEL_GROUP_ID", nullable = false)
private Integer modelId;
}
when I'm saving new object:
Integer modelGroupId = sessionFactory.getCurrentSession().save( modelGroup );
System.out.println( modelGroupId );
ID is set as for example 23, but when I look at the database it is actually 24. This is leading to many problems, as I'm using this ID later on. Any idea why it is making this gap?
SQL logs show that everything is fine (I thinks so):
Hibernate:
select
SEQ_MODEL_GROUP_MODEL_GROUP_ID.nextval
from
dual
Hibernate:
insert
into
MODEL_GROUP
(DOMAIN_ID, DESCRIPTION, NAME, PERIOD_TYPE_ID, MODEL_GROUP_TYPE_ID, STATUS_ID, OWNER_ID, MODEL_GROUP_ID)
values
(?, ?, ?, ?, ?, ?, ?, ?)
Trigger and Sequence:
CREATE SEQUENCE "SEQ_MODEL_GROUP_MODEL_GROUP_ID"
INCREMENT BY 1
START WITH 1
NOMAXVALUE
MINVALUE 1
NOCYCLE
NOCACHE
NOORDER
;
CREATE OR REPLACE TRIGGER "TRG_MODEL_GROUP_MODEL_GROUP_ID"
BEFORE INSERT
ON "MODEL_GROUP"
FOR EACH ROW
WHEN (NEW."MODEL_GROUP_ID" is NULL)
BEGIN
SELECT "SEQ_MODEL_GROUP_MODEL_GROUP_ID".NEXTVAL
INTO :NEW."MODEL_GROUP_ID"
FROM DUAL;
END;
Apparently, when Hibernate ask your database for nextValue of ID, it fires also Trigger. So when I ask for ID, I've got number 23 but when actually saving to database by commiting transaction, it is increased again so I've got 24. Solution is described here:
HIbernate issue with Oracle Trigger for generating id from a sequence
To make it work correctly, I changed Trigger:
CREATE OR REPLACE TRIGGER "TRG_MODEL_GROUP_MODEL_GROUP_ID"
BEFORE INSERT
ON "MODEL_GROUP"
FOR EACH ROW
WHEN (NEW."MODEL_GROUP_ID" is NULL)
BEGIN
SELECT "SEQ_MODEL_GROUP_MODEL_GROUP_ID".NEXTVAL
INTO :NEW."MODEL_GROUP_ID"
FROM DUAL;
END;