Hibernate #Index error on long string columns - java

I have a data model where I need a String column to be indexed by the backing database:
#Entity
public class A {
// ...
#Column(length=2048)
#Index(name="strFieldIndex")
private String strField;
}
When adding the length attribute of #Column(length=2048) (for which hibernate doesn't generate varchar anymore) the following error message appears on MySQL:
ERROR org.hibernate.tool.hbm2ddl.SchemaExport -
BLOB/TEXT column 'strField' used in key specification without a key length
I've scanned the API docs for hibernate and I can't find an approach to setting the key length.

I think you have to declare this index manually as required for MySQL, since Hibernate can't handle all DBMS-specific requirements. For example, using <database-object> syntax.

Related

flyway migration on existing database results in "wrong column type encountered in column"

i have spring boot application that uses my database schema. Lets say i have non-empty schema with table APPLICATION_USERS defined as follows:
create table AREA
(
name NVARCHAR2(36) not null,
id NUMBER not null
)
now i wanted to add FlyWay to my application. I have defined in my application properties flyway.baselineOnMigrate=true to start initial Flyway deployment and spring.jpa.hibernate.ddl-auto=validate to validate my Enities agains schema, however upon starting application i get following error:
wrong column type encountered in column [name] in table [APPLICATION_USERS]; found [nvarchar2 (Types#OTHER)], but expecting [varchar2(255 char) (Types#VARCHAR)]
as far as i understand it, it complains about NVARCHAR2, as it expect varchar how can i force hibernate to accept nvarchar2 as varchar?
i know i can use columnDefinition on my entity attributes, however this is not my dream solution, is there any other way?
I assume that you are using Oracle database.
You have to annotate your the attribute name in your Entity with Nationalized
#Nationalized
private String name;
You also could register your own dialect:
public class CustomOracleDialect extends Oracle10gDialect {
public CustomOracleDialect() {
super();
registerColumnType(Types.NVARCHAR, "nvarchar2($l)");
registerHibernateType(Types.NVARCHAR, StandardBasicTypes.STRING.getName());
}
}

saving Oracle XMLType type column using JPA

I have a column type defined in Oracle as XMLTYPE and I am trying to save xml content using JPA. I have used something like in my entity class.
#CLOB
#Column(name = "COLOUM_NAME")
private String coloumName;
But i am getting the following exception.
ORA-01461: can bind a LONG value only for insert into a LONG column
Any solution for above issue?
You don't need #CLOB annotation here. Just use String type.

How to generate column with length property using JPA tools?

I was generating Entity class for tables using JPA Tools in Eclipse Mars.It generate this
#Column(name="someColumn")
private String someColumn;
type of data member in Entity class which is of varying(130) type in databse. I have to manually edit every data member like this
#Column(name="someColumn",length=130)
private String someColumn;
by adding length in Column annotation. How to configure JPA Tools for generating data member with length automatically?

Manually update the counter used for generation of primary key in Hibernate?

In my spring project, the tables in database are created automatically by Hibernate using my entity classes as base, but I insert some default values in the table manually (using pgAdmin3).
Because that, I am facing now this problem: when I try insert a value via Java code in one of the tables which already have values, I receive a error message, saying the primary key already exists in the database.
Anyone knows how to solve this problem?
UPDATE
That's how I declare my primary key in my class:
#Id
#Column(name = "id")
#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
Call this SQL query once per table to set the sequence to the next free number:
SELECT setval('tblname_id_seq', max(id)) FROM tblname;
tblname being the actual name of the table.
Hibernate may use a different naming convention, or the sequence may have been renamed. If you can't find the sequence behind the serial column, check with (per documentation):
SELECT pg_get_serial_sequence(tblname, column_name)
More details:
Modify Django AutoField start value
How to import a CSV to postgresql that already has ID's assigned?
The problem here might be that you declare the id as a primitive instead of a wrapper.
So instead of:
private int id;
You should have:
private Integer id;
When you create the entity with the id is initialized as 0, instead of NULL.
That's why you get duplicate id constraint violation exceptions.
Only when the id is NULL the AUTO generation strategy will delegate the id assignment to the database.

Hibernate null constraint violation on #Id with #GeneratedValue

I am using Hibernate 4.1.3 (JPA) on the Play! framework. The database is PostgreSQL 8.4.2. The schema was generated using hibernate.hbm2ddl.auto="update".
Short version: I have a class that has an #Id field that is a #GeneratedValue. Sometimes, when persisting it, I get a null-column violation, why?
More details:
I have a really simple class that I want to save to the database, that looks like this:
#Entity
class MyObject {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
public Long id;
#NotNull
public String email;
public Integer total;
}
I usually create an instance of MyObject, I assign a value to email and total fields while id is null and I save it via EntityManager.persist(). Hibernate gets an id for the new object and saves it to the DB.
However sometimes, I get the following stacktrace:
2012-05-19 00:45:16,335 - [ERROR] - from org.hibernate.engine.jdbc.spi.SqlExceptionHelper [SqlExceptionHelper.java:144] in play-akka.actor.actions-dispatcher-6
ERROR: null value in column "id" violates not-null constraint
2012-05-19 00:45:16,350 - [ERROR] - from application in play-akka.actor.actions-dispatcher-6
! #6ad7j3p8p - Internal server error, for request [POST /method] ->
play.core.ActionInvoker$$anonfun$receive$1$$anon$1: Execution exception [[PersistenceException: org.hibernate.exception.ConstraintViolationException: ERROR: null value in column "id" violates not-null constraint]]
How is this possible? How can I track down the problem?
Here's the relevant DDL generated by Hibernate:
CREATE TABLE myobject (
id bigint NOT NULL,
email character varying(255) NOT NULL,
physical integer
);
CREATE SEQUENCE hibernate_sequence
START WITH 1
INCREMENT BY 1
NO MAXVALUE
NO MINVALUE
CACHE 1;
ALTER TABLE ONLY dailydetailedscore
ADD CONSTRAINT dailydetailedscore_pkey PRIMARY KEY (id);
Try the annotation #org.hibernate.annotations.GenericGenerator(name = “test-hilo-strategy”, strategy = “hilo”):
#Id
#org.hibernate.annotations.GenericGenerator(name=“hilo-strategy”, strategy = “hilo”)
#GeneratedValue(generator = ”hilo-strategy”)
As someone noted above, AUTO does not do what you think. It uses the underlying DB to determine how to generate values. It may pick sequences (for oracle), identity column (for mssql), or something else that is db specific.
The approach here uses an internal strategy that Hibernate supplies called "hilo".
See chapter 5 of the Hibernate reference manual dealing with "Generator" for a full description of what each of the supplied ones does.
Neither the OP solution nor Matt's solution worked with my PostgreSQL 9.3.
But this one works:
#SequenceGenerator(name="identifier", sequenceName="mytable_id_seq", allocationSize=1)
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="identifier")
Replace mytable_id_seq with the name of the sequence that generates your id.
Use Hibernate method:- save(String entityName, Object object)
Persist the given transient instance, first assigning a generated identifier.
Do not use :- #GeneratedValue(strategy=GenerationType.IDENTITY) for primary key if you want to persist user define Id.
For detail:-
http://docs.jboss.org/hibernate/core/3.6/javadocs/org/hibernate/Session.html#save(java.lang.String
In mycase i was using Identity generation strategy and i have set the wrong data type in Postgres. Following steps i performed to debug the problem.
set
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=true in application.properties and Drop the tables.
By this hibernate will automatically create the schema for you on the basis of your data-type.I noticed change in the datatype of id field.
Now when i tried any post requests, everything worked fine.

Categories

Resources