HIbernate suddenly started to validate JPA annotations - java

I have an entity that maps a database table in my code, this entity has the following attribute:
#Column(name = "CARD_TYPE", length = 255,nullable = false)
private String cardType;
When this entity was created the column in the database had this field defined as non nullable, but due to a change in the business logic it is no longer the case. The field in the database was updated to allow this field to be null but the entity in the java code was not. Now, when testing in several environments with different instances of the same database we had no problems, but as of yesterday, after this code had been running for about a week without issues, we are getting this message over and over
error javax.persistence.PersistenceException: org.hibernate.PropertyValueException: not-null property references a null or transient value: entity.cardType | Cause: org.hibernate.PropertyValueException: not-null property references a null or transient value: entity.cardType
This exception if from Hibernate which means that it never even tries to reach the database. Is my understanding that #Column annotation is only used when creating the database schemas from code and not used for validation. We have another instance of the same code in another server running against the same database and it doesn't show the error.

Related

Hibernate Spatial: cache lookup failed for type

I have exactly the same error as in this e-mail thread:
http://hibernate-spatial.1140993.n2.nabble.com/cache-lookup-failed-for-type-1185046-tt7572634.html#a7572637 (unfortunately no solution there)
I want to persist an entity with a Geometry field using HibernateSpatial/Hibernate. On persist it throws an exception 'Caused by: org.postgresql.util.PSQLException: ERROR: cache lookup failed for type 3178753' (the type id changes with every request and is not contained in pg_type or pg_class).
Like the guy in the thread, I can:
persist an entity where the Geometry field is NULL
SQL INSERT the entity including the geometry field manually (using the generated query in the prepared statement insert into tableA (id, polygon) values (1, 'SRID=4326;POLYGON((0 0,1 1,0 1,0 0))') RETURNING *
The field definition is:
#Column(name = "polygon")
#Type(type="org.hibernate.spatial.GeometryType")
private Geometry geom;
I also tried type Polygon (always the com.vividsolutions.jts... classes)
I use
hibernate 4.3.11
hibernate-spatial 4.3
postgresql-9.4
In the DB the field is declared as geometry.
edit: it seems to be related to running the CREATE EXTENSION postgis call in one connection and the other one not picking those objects up, I don't know enough about PostgreSQL internals for that though

Hibernate boolean field mapping issue

There is a boolean field in Entity :
#Column(name = "FREEFLAG", columnDefinition = "NUMBER(0,1) default 0", nullable = false)
public boolean getFreeflag() {
return freeflag;
}
database - Oracle, field FREEFLAG - NUMBER(0,1)
I try to get object from db with Hibernate, but if the field in db is null i got a exception :
Exception in thread "main" org.hibernate.PropertyAccessException: Null value was assigned to a property of primitive type
Why default value doesn't work ?
How I can resolve this problem on server side? I have to have 0 or 1 value in db.
I got the solution - Default value not working in hibernate. But I still have to modify database. I have added DDL - alter table client modify freeflag default 0 not null
DML - update client set freeflag = 0 where freeflag is null; commit
In one of your comments you have said that your database allow null values for this column. The columnDefinition attribute is used by JPA Provider during schema generation process, so I can assume that you have not generated schema after you added columnDefinition attribute (nor nullable=false). Hints in columnDefinition which set default value were not applied to database, so it's nothing strange that you don't have this column defaulted.
Another way you can make it work is creating custom Converter for this field, which will save values in the way you need. More informations about converters implementation available here.
The columnDefinition is database dependent and hence might cause issues sometimes. What I got from searching on net is that it works sometimes but doesnt work in some cases. An alternative is to use the prePersist method technique described in below link:
http://www.coderanch.com/t/450124/ORM/databases/entity-Boolean-field-default
Hope this helps.

Hibernate handling of nullable=true in #Column

I am using Hibernate with Springs backed by a Mysql db.
Here is the entity similar to the one i use to make an entry
#Entity
#Table(name = "my_table") {
#Basic
#Column(name = "my_string", nullable = false)
private String myString;
}
The sql definition is
CREATE TABLE `my_table` (
`my_string` varchar(200) DEFAULT NULL,
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
Though the table allows null values, the column myString is non-nullable as per the JPA annotation. This is leading to unpredictable behaviour.
Q: Is the non-nullable ALWAYS enforced at the entity level while making inserts? Or is there some case in which it may be ignored
My expectation was that all of the entries should have been rejected. But with this setup, many entries (>7000) have gone into the table.
Only sometimes i get a DataIntegrityViolation exception from spring
org.springframework.dao.DataIntegrityViolationException: not-null property references a null or transient value: ...; nested exception is org.hibernate.PropertyValueException: not-null property references a null or transient value: ....
at org.springframework.orm.hibernate3.SessionFactoryUtils.convertHibernateAccessException(SessionFactoryUtils.java:652)
at org.springframework.orm.jpa.vendor.HibernateJpaDialect.translateExceptionIfPossible(HibernateJpaDialect.java:104)
at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.translateExceptionIfPossible(AbstractEntityManagerFactoryBean.java:403)
at org.springframework.dao.support.ChainedPersistenceExceptionTranslator.translateExceptionIfPossible(ChainedPersistenceExceptionTranslator.java:58)
....
....
Caused by: org.hibernate.PropertyValueException: not-null property references a null or transient value: ....
at org.hibernate.engine.internal.Nullability.checkNullability(Nullability.java:103)
....
I understand that having separate signature in the entity and the table is a bad practice, But i'm trying to identify what causes this behaviour and any other loopholes that might have been left out due to it.
Versions -
Mysql- 5.5
Hibernate - 4.0.0
Hibernate-jpa - 2.0
Spring-core- 3.1.0
Spring-jdbc- 3.1.2
People frequently confuse the #Column(nullable) and #NotNull annotations.
The #Column(nullable) is meant for the generated DDL scripts. But you don't use Hibernate to generate your DDL, so you shouldn't rely on it at all. What you want is #NotNull which is a runtime validation trigger.
If you define the Hibernate Validator Annotation (or JPA 2.0 ones) you can get the DDL for those as well:
Out of the box, Hibernate (as of version 3.5.x) will translate the
constraints you have defined for your entities into mapping metadata.
For example, if a property of your entity is annotated #NotNull, its
columns will be declared as not null in the DDL schema generated by
Hibernate.
And make sure you enable validation if you're using JPA with Hibernate.
If you are using JPA 2 and Hibernate Validator is in the classpath the
JPA2 specification requires that Bean Validation gets enabled. The
properties javax.persistence.validation.group.pre-persist,
javax.persistence.validation.group.pre-update and
javax.persistence.validation.group.pre-remove as described in Section
10.1.2, “Hibernate event-based validation” can in this case be configured in persistence.xml. persistence.xml also defines a node
validation-mode which can be set to AUTO, CALLBACK, NONE. The default
is AUTO.

How to Solve SQL Integrity Constraint Violation Exception

I created an entity class that has the same properties as project.java, and created a class where I can persist the entity object. Also, I created a database using databases in Netbeans using embedded JDBC. I have the persistence.xml, which provides the properties to connect the db, and is used the persitence class on entitymanagerfactory object. The connection seems fine but I am having Internal Exception: java.sql.SQLIntegrityConstraintViolationException: Column 'PROJECT_ID' cannot accept a NULL value. error.
Is it ok to create the db manually (executing the ddl) or should I create the table in the persistence.xml using property name="javax.persistence.jdbc.url"" value="create-tables ?
Regards
You have to set the value of the column PROJECT_ID.
You can either do this in your code, for example by using the annotations #SequenceGenerator or #GenericGenerator,
or use db features (trigger) to set the id during insert.

H2 + Hibernate with non nullable String stores empty string

I'm currently migrating some existing code from Hibernate 3.2 to Hibernate 3.6.10.Final
(and also from Spring 2.0 to Spring 3.1.2 by the way).
I have an issue with some integration tests running against H2 database, verifying that some fields are not nullable.
- I test that an attempt to insert a null String into a field marked as nullable=false ends with an Exception
- I checked that the schema is correctly created : the column is not nullable.
Using H2 (with MySQL mode), nullable constraint is ignored : an empty String is inserted in database.
I don't reproduce the case if I run my test against a MySQL database.
It worked before with Hibernate 3.2
For example, if I have a class Person :
#Entity
class Person {
#Id
#GeneratedValue
private Long id;
#Column(nullable=false)
private String name;
//getters and setters
}
And then I have a test (still using JUnit3, I'll migrate this later) :
#ExpectedException(value=DataIntegrityViolationException.class)
public void testPerson_NameCantBeNull() throws Exception {
// Given
Person person = new Person();
person.setName(null);
// When
getHibernateTemplate().persist(person);
//Flush and clear session
}
I could fix this by replacing nullable=false by #NotNull annotation but I don't want to replace it in my huge code base as I wouldn't expect the same Exception.
I had a quick look into H2Dialect class and JIRA issues in Hibernate but I didn't find anything.
Does anybody know where it comes from ?
EDIT :
Some additional informations, I added the TRACE level in Hibernate logs.
When I insert null and the field is marked with #Column(nullable=false), I have the following log :
2013-01-16 15:57:52 TRACE [BasicExtractor] found [] as column [NAME1_3_]
When I insert null and the field is not marked with #Column(nullable=false), I have the following log :
2013-01-16 15:57:52 TRACE [BasicExtractor] found [null] as column [NAME1_3_]
EDIT (22/01/13) :
I still didn't found where the problem exactly come from, but I found out that it is tied to MySQL mode with H2 : if I disable MySQL mode, Hibernate doesn't try anymore to replace my null Strings by empty Strings.
But I can't do this since some other pieces of code are tied to MySQL syntax.
Any idea ?
I didn't have enough time to digg in Hibernate and MySQL dialect, so I moved to Java Validation Framework, using #NotNull annotation.
It does the job and meets one of our other requirement : a part of our model is used in a Grails application and we want to use constraints to validate part of CRUD operations (not possible with pure javax.persistence annotations).

Categories

Resources