Error attempting to apply AttributeConverter - java

I was using JPA AttributeConverter with spring boot 1.2.1 RELEASE and it worked fine. But I get the following error after upgrading to spring boot 1.3.0.RELEASE
Caused by: javax.persistence.PersistenceException: Error attempting to apply AttributeConverter
at org.hibernate.type.descriptor.converter.AttributeConverterSqlTypeDescriptorAdapter$1.bind(AttributeConverterSqlTypeDescriptorAdapter.java:103)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:286)
at org.hibernate.type.AbstractStandardBasicType.nullSafeSet(AbstractStandardBasicType.java:281)
at org.hibernate.type.AbstractSingleColumnStandardBasicType.nullSafeSet(AbstractSingleColumnStandardBasicType.java:56)
at org.hibernate.persister.entity.AbstractEntityPersister.dehydrate(AbstractEntityPersister.java:2843)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3248)
at org.hibernate.persister.entity.AbstractEntityPersister.updateOrInsert(AbstractEntityPersister.java:3183)
at org.hibernate.persister.entity.AbstractEntityPersister.update(AbstractEntityPersister.java:3525)
at org.hibernate.action.internal.EntityUpdateAction.execute(EntityUpdateAction.java:159)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:465)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:351)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:350)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:56)
at org.hibernate.internal.SessionImpl.flush(SessionImpl.java:1258)
at org.hibernate.internal.SessionImpl.managedFlush(SessionImpl.java:425)
at org.hibernate.engine.transaction.internal.jdbc.JdbcTransaction.beforeTransactionCommit(JdbcTransaction.java:101)
at org.hibernate.engine.transaction.spi.AbstractTransactionImpl.commit(AbstractTransactionImpl.java:177)
at org.hibernate.jpa.internal.TransactionImpl.commit(TransactionImpl.java:77)
at org.springframework.orm.jpa.JpaTransactionManager.doCommit(JpaTransactionManager.java:517)
... 81 more
Caused by: java.lang.NullPointerException
at rafito.spring.boot.domain.TimestampPersistenceConverter.convertToDatabaseColumn(TimestampPersistenceConverter.java:16)
at rafito.spring.boot.domain.TimestampPersistenceConverter.convertToDatabaseColumn(TimestampPersistenceConverter.java:10)
at org.hibernate.type.descriptor.converter.AttributeConverterSqlTypeDescriptorAdapter$1.bind(AttributeConverterSqlTypeDescriptorAdapter.java:97)
I am not setting serviceBeginTime and serviceEndTime in my POST JSON currently. But this wasn't giving me a null pointer before I upgraded spring boot version.
Converter class
#Converter
public class TimestampPersistenceConverter implements AttributeConverter<Long, Timestamp> {
#Override
public Timestamp convertToDatabaseColumn(Long aLong) {
return new Timestamp(aLong);
}
#Override
public Long convertToEntityAttribute(Timestamp timestamp) {
return timestamp.getTime();
}
}
Entity
#Column(name = "service_begin_time")
#Convert(converter = TimestampPersistenceConverter.class)
Long serviceBeginTime;
#Column(name = "service_end_time")
#Convert(converter = TimestampPersistenceConverter.class)
Long serviceEndTime;
Database fields
service_begin_time timestamp without time zone,
service_end_time timestamp without time zone,

Added a null check as that was the easiest.
#Override
public Timestamp convertToDatabaseColumn(Long aLong) {
if (aLong == null)
return null;
return new Timestamp(aLong);
}

Related

Data truncation: Data too long for column 'xxx' at row x (boolean)

I am using hibernate mapping one to many to complete my task. But when I ran the project, it ran into a problem: "Data truncation: Data too long for column 'tinhTrang' at row 1".
I can't get the point why I got this. I searched but I couldn't find any problem with boolean like me. Please help me. Thank everyone
.package com.javapoint;
import javax.persistence.*;
#Entity
#Table(name="DH")
public class DonHang {
#Id
#GeneratedValue(strategy=GenerationType.TABLE)
private int soDH;
private int maKH;
private double triGia;
#Column(nullable = false, columnDefinition = "TINYINT(4)")
private boolean tinhTrang;
public int getsoDH()
{
return soDH;
}
public void setsoDH(int soDH)
{
this.soDH = soDH;
}
public int getmaKH()
{
return maKH;
}
public void setmaKH(int maKH)
{
this.maKH = maKH;
}
public double gettriGia()
{
return triGia;
}
public void settriGia(double triGia)
{
this.triGia = triGia;
}
public boolean gettinhTrang()
{
return tinhTrang;
}
public void settinhTrang(boolean tinhTrang)
{
this.tinhTrang = tinhTrang;
}
}
Here is the error message:
Caused by: org.hibernate.exception.DataException: could not execute statement
at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:52)
at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:113)
at org.hibernate.engine.jdbc.spi.SqlExceptionHelper.convert(SqlExceptionHelper.java:99)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:178)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3171)
at org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:3686)
at org.hibernate.action.internal.EntityInsertAction.execute(EntityInsertAction.java:90)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:604)
at org.hibernate.engine.spi.ActionQueue.executeActions(ActionQueue.java:478)
at org.hibernate.event.internal.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:356)
at org.hibernate.event.internal.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:39)
at org.hibernate.internal.SessionImpl.doFlush(SessionImpl.java:1454)
... 9 more
Caused by: com.mysql.cj.jdbc.exceptions.MysqlDataTruncation: Data truncation: Data too long for column 'tinhTrang' at row 1
at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:104)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:974)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1113)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdateInternal(ClientPreparedStatement.java:1061)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeLargeUpdate(ClientPreparedStatement.java:1381)
at com.mysql.cj.jdbc.ClientPreparedStatement.executeUpdate(ClientPreparedStatement.java:1046)
at org.hibernate.engine.jdbc.internal.ResultSetReturnImpl.executeUpdate(ResultSetReturnImpl.java:175)
... 17 more
The error originates from the MySQL server. You are trying to put a too big value into one of the columns.
You should check what value you are trying to add to the column and change the type for the column to something bigger.
For a better answer you need to supply more information on what data you are trying to add to each column.

Error when retrieving values from MS SQL using Hibernate

I've done a program where I have to retrieve the data from a table in MS SQL. I'm using Hibernate where AbtDebtbyCAN is an Entity class. The connection so far is fine but the only problem I'm facing is printing out data from MS SQL using Annotation Mapping. Debt is the name of the table(the name of the table is in lower case) which is to be mapped with. Below here is the result I want to print it out using Hibernate. Can anybody help me on how to achieve the fetching of data?
debt
id can bdrl_debt excess_ta_debt posting_ref debt_settlement_id debt_settlement_at debt_business_date
11425 1099112400000003 0 200 501728 137 2020-10-13 10:51:50.000 2020-10-13
AbtDebtbyCAN
#Data
#Entity
#Table(name = "debt")
public class AbtDebtbbyCAN implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id")
private int debt_id;
#Column(name = "can")
private int debt_can;
#Column(name = "bdrl_debt")
private int bdrl_debt;
#Column(name = "excess_ta_debt")
private int excess_ta_debt;
#Column(name = "posting_ref")
private int posting_ref;
#Column(name = "debt_settlement_id")
private int debt_settlement_id;
#Column(name = "debt_settlement_at")
private DateTime debt_settlement_at;
#Column(name = "debt_business_date")
private Date debt_business_date;
}
AbtCANMapperTest
public class AbtCANMapperTest {
public static void main(String args[]) {
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hibernate.cfg.xml").build();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
SessionFactory factory = meta.getSessionFactoryBuilder().build();
Session session = factory.openSession();
Transaction tx = null;
try {
tx = session.beginTransaction();
List abtdebt = session.createQuery("FROM AbtDebtbbyCAN WHERE debt_can=1099112400000003").getResultList();
for (Iterator iterator = abtdebt.iterator(); iterator.hasNext(); ) {
AbtDebtbbyCAN abtcan = (AbtDebtbbyCAN) iterator.next();
System.out.print("debt id: " + abtcan.getDebt_id());
System.out.print("debt can: " + abtcan.getDebt_can());
System.out.print("bdrl debt: " + abtcan.getBdrl_debt());
System.out.print("excess debt: " + abtcan.getExcess_ta_debt());
System.out.print("posting ref: " + abtcan.getPosting_ref());
System.out.print("debt settlement id: " + abtcan.getDebt_settlement_id());
System.out.print("debt settlement at: " + abtcan.getDebt_settlement_at());
System.out.println("debt business date: " + abtcan.getDebt_business_date());
}
tx.commit();
} catch (HibernateException e) {
if (tx != null) tx.rollback();
e.printStackTrace();
} finally {
session.close();
}
}
}
Error StackTrace
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.type.SerializationException: could not deserialize
at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:154)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1542)
at org.hibernate.query.Query.getResultList(Query.java:165)
at AbtMainTestControl.AbtTestObj.AbtCANMapperTest.main(AbtCANMapperTest.java:36)
Caused by: org.hibernate.type.SerializationException: could not deserialize
at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:243)
at org.hibernate.internal.util.SerializationHelper.deserialize(SerializationHelper.java:287)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.fromBytes(SerializableTypeDescriptor.java:138)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:113)
at org.hibernate.type.descriptor.java.SerializableTypeDescriptor.wrap(SerializableTypeDescriptor.java:29)
at org.hibernate.type.descriptor.sql.VarbinaryTypeDescriptor$2.doExtract(VarbinaryTypeDescriptor.java:60)
at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:257)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:253)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:243)
at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:329)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:3088)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1907)
at org.hibernate.loader.Loader.hydrateEntityState(Loader.java:1835)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1808)
at org.hibernate.loader.Loader.getRow(Loader.java:1660)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:745)
at org.hibernate.loader.Loader.getRowsFromResultSet(Loader.java:1044)
at org.hibernate.loader.Loader.processResultSet(Loader.java:995)
at org.hibernate.loader.Loader.doQuery(Loader.java:964)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:350)
at org.hibernate.loader.Loader.doList(Loader.java:2887)
at org.hibernate.loader.Loader.doList(Loader.java:2869)
at org.hibernate.loader.Loader.listIgnoreQueryCache(Loader.java:2701)
at org.hibernate.loader.Loader.list(Loader.java:2696)
at org.hibernate.loader.hql.QueryLoader.list(QueryLoader.java:506)
at org.hibernate.hql.internal.ast.QueryTranslatorImpl.list(QueryTranslatorImpl.java:400)
at org.hibernate.engine.query.spi.HQLQueryPlan.performList(HQLQueryPlan.java:219)
at org.hibernate.internal.SessionImpl.list(SessionImpl.java:1415)
at org.hibernate.query.internal.AbstractProducedQuery.doList(AbstractProducedQuery.java:1565)
at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1533)
... 2 more
Caused by: java.io.StreamCorruptedException: invalid stream header: 0000AC53
at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:899)
at java.io.ObjectInputStream.<init>(ObjectInputStream.java:357)
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:309)
at org.hibernate.internal.util.SerializationHelper$CustomObjectInputStream.<init>(SerializationHelper.java:299)
at org.hibernate.internal.util.SerializationHelper.doDeserialize(SerializationHelper.java:218)
... 32 more
Caused by: org.hibernate.type.SerializationException: could not deserialize
> Task :AbtCANMapperTest.main() FAILED
Caused by: java.io.StreamCorruptedException: invalid stream header: 0000AC53
Execution failed for task ':AbtCANMapperTest.main()'.
> Process 'command 'C:/Program Files/Java/jdk1.8.0_241/bin/java.exe'' finished with non-zero exit value 1
* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
Not sure what types you are exactly using here, but at least DateTime is not a standard type that is supported by Hibernate. If Hibernate does not know about a type, it tries to flush the value in its serialized form as blob/byte[]. If you would use java.sql.Timestamp, java.util.Calendar or any other type that is supported by Hibernate out of the box, this should work properly.

Entity not managed after getting it from database

I am using Play Framework and currently doing a CRUD of users. I have created a repository for doing operations on the database using the Play Framework JPAApi. The relevant ones are this
<U> U jpaWrapper(Function<EntityManager, U> function) {
return jpaApi.withTransaction(function);
}
public CompletionStage<T> update(T entity) {
return supplyAsync(() -> jpaWrapper(em -> update(em, entity)), executionContext);
}
private T update(EntityManager em, T entity) {
em.refresh(entity);
return entity;
}
public CompletionStage<Usuario> findById(int id) {
return supplyAsync(
() -> jpaWrapper(em -> findById(id, em)),
executionContext);
}
private Usuario findById(int id, EntityManager em) {
return (Usuario) JpaResultHelper.getSingleResultOrNull(
em.createNamedQuery("Usuario.findById", Usuario.class)
.setParameter("id", id)
);
}
In my controller I am editing the user by first finding it on the repository and after that setting the correct parameters. This is the controller action.
public CompletionStage<Result> editUser() {
Usuario editedUser = formFactory.form(Usuario.class).bindFromRequest("id", "nombre", "email", "rol").get();
return usuarioRepository.findById(editedUser.getId()).thenCompose( dbUser -> {
dbUser.setNombre(editedUser.getNombre());
dbUser.setRol(editedUser.getRol());
dbUser.setEmail(editedUser.getEmail());
return usuarioRepository.update(dbUser).thenApplyAsync( u ->
redirect(routes.UserController.listUsers())
);
});
}
The problem is that when I call the method the entity appears to be not managed with the following stack trace.
play.api.http.HttpErrorHandlerExceptions$$anon$1: Execution exception[[CompletionException: java.lang.IllegalArgumentException: Entity not managed]]
at play.api.http.HttpErrorHandlerExceptions$.throwableToUsefulException(HttpErrorHandler.scala:251)
at play.api.http.DefaultHttpErrorHandler.onServerError(HttpErrorHandler.scala:178)
at play.core.server.AkkaHttpServer$$anonfun$1.applyOrElse(AkkaHttpServer.scala:382)
at play.core.server.AkkaHttpServer$$anonfun$1.applyOrElse(AkkaHttpServer.scala:380)
at scala.concurrent.Future.$anonfun$recoverWith$1(Future.scala:413)
at scala.concurrent.impl.Promise.$anonfun$transformWith$1(Promise.scala:37)
at scala.concurrent.impl.CallbackRunnable.run(Promise.scala:60)
at akka.dispatch.BatchingExecutor$AbstractBatch.processBatch(BatchingExecutor.scala:55)
at akka.dispatch.BatchingExecutor$BlockableBatch.$anonfun$run$1(BatchingExecutor.scala:91)
at scala.runtime.java8.JFunction0$mcV$sp.apply(JFunction0$mcV$sp.java:12)
Caused by: java.util.concurrent.CompletionException: java.lang.IllegalArgumentException: Entity not managed
at java.util.concurrent.CompletableFuture.encodeThrowable(CompletableFuture.java:273)
at java.util.concurrent.CompletableFuture.completeThrowable(CompletableFuture.java:280)
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1592)
at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:40)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
at java.lang.Thread.run(Thread.java:748)
Caused by: java.lang.IllegalArgumentException: Entity not managed
at org.hibernate.internal.SessionImpl.fireRefresh(SessionImpl.java:1320)
at org.hibernate.internal.SessionImpl.refresh(SessionImpl.java:1277)
at models.management.AbstractRepository.update(AbstractRepository.java:54)
at models.management.AbstractRepository.lambda$null$4(AbstractRepository.java:31)
at play.db.jpa.DefaultJPAApi.withTransaction(DefaultJPAApi.java:142)
at play.db.jpa.DefaultJPAApi.withTransaction(DefaultJPAApi.java:100)
at models.management.AbstractRepository.jpaWrapper(AbstractRepository.java:40)
at models.management.AbstractRepository.lambda$update$5(AbstractRepository.java:31)
at java.util.concurrent.CompletableFuture$AsyncSupply.run(CompletableFuture.java:1590)
at akka.dispatch.TaskInvocation.run(AbstractDispatcher.scala:40)

Jackson blob exception

I am trying to save image to database, but I get error:
org.codehaus.jackson.map.JsonMappingException: Can not construct instance of java.sql.Blob, problem: abstract types can only be instantiated with additional type information
at [Source: java.io.StringReader#e95dbd; line: 1, column: 27] (through reference chain: com.soul.seeker.models.Post["postImage"])
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
at org.codehaus.jackson.map.deser.StdDeserializationContext.instantiationException(StdDeserializationContext.java:233)
at org.codehaus.jackson.map.deser.AbstractDeserializer.deserialize(AbstractDeserializer.java:60)
at org.codehaus.jackson.map.deser.SettableBeanProperty.deserialize(SettableBeanProperty.java:299)
at org.codehaus.jackson.map.deser.SettableBeanProperty$MethodProperty.deserializeAndSet(SettableBeanProperty.java:414)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromObject(BeanDeserializer.java:697)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:580)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2732)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1863)
at com.soul.seeker.serviceImpl.PostServiceImpl.createPostImage(PostServiceImpl.java:121)
at com.soul.seeker.Application.lambda$main$8(Application.java:142)
at spark.ResponseTransformerRouteImpl$1.handle(ResponseTransformerRouteImpl.java:47)
at spark.http.matching.Routes.execute(Routes.java:61)
at spark.http.matching.MatcherFilter.doFilter(MatcherFilter.java:130)
at spark.embeddedserver.jetty.JettyHandler.doHandle(JettyHandler.java:50)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:189)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:119)
at org.eclipse.jetty.server.Server.handle(Server.java:517)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:308)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:242)
at org.eclipse.jetty.io.AbstractConnection$ReadCallback.succeeded(AbstractConnection.java:261)
at org.eclipse.jetty.io.FillInterest.fillable(FillInterest.java:95)
at org.eclipse.jetty.io.SelectChannelEndPoint$2.run(SelectChannelEndPoint.java:75)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.produceAndRun(ExecuteProduceConsume.java:213)
at org.eclipse.jetty.util.thread.strategy.ExecuteProduceConsume.run(ExecuteProduceConsume.java:147)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:654)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:572)
at java.lang.Thread.run(Thread.java:745)
Pojo class:
public class Post{
private String post_id;
private String title;
private String details;
private String username;
private String userImage;
private String url;
private List categories;
private String created_at;
private Blob postImage; //BLOB TYPE
private String postImageName;
//getters setters
}
Implementation class:
#Override
public void createPostImage(Request request) {
try {
ObjectMapper mapper = new ObjectMapper();
Post createPostImage = mapper.readValue(request.body(), Post.class);
System.out.println("CREATE POST IMAGE" + createPostImage);
} catch (IOException ex) {
Logger.getLogger(PostServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
}
}
Looked online for similar posts but couldn't find any leads. How do I fix this? It says abstract types can only be instantiated with additional type information. What is the additional info I have to passed here?
I'm not sure about the method you're trying to upload a file, but I'm sure that's not the "recommended" method when working with Spark.
According to the documentation, you should read the file as a stream and use the request.raw() for that purpose, instead of the request.body().
Read about the recommended way here, and there's also a github example for that.

Hibernate + Oracle, strange null constraint violation with primitive type

I just add a new column on an entity and a strange thing is happening.
The entity was previously:
int publishedDayNb;
public int getPublishedDayNb() {
return publishedDayNb;
}
public void setPublishedDayNb(int publishedDayNb) {
this.publishedDayNb = publishedDayNb;
}
And the entity is now:
int publishedDayNb;
int publishedDayNbSinceLastPublication;
public int getPublishedDayNb() {
return publishedDayNb;
}
public void setPublishedDayNb(int publishedDayNb) {
this.publishedDayNb = publishedDayNb;
}
#Column(name="published_days_since_last_pub")
public int getPublishedDayNbSinceLastPublication() {
return publishedDayNbSinceLastPublication;
}
public void setPublishedDayNbSinceLastPublication(int publishedDayNbSinceLastPublication) {
this.publishedDayNbSinceLastPublication = publishedDayNbSinceLastPublication;
}
As you can see i've just added a column.
The sql script to do that in database was:
alter table mytable add published_days_since_last_pub number(10,0);
update mytable set published_days_since_last_pub=0;
alter table mytable modify published_days_since_last_pub number(10,0) not null;
I'm doing a java batch processing, reading a file, inserting new entity entries, and updating existing ones.
It works fine in local and in dev server, but in validation server, i've got this error during a new entity processing (insert)
BATCH 03/05/2011 06:41:11 WARN
[JDBCExceptionReporter.java:77] - SQL
Error: 1400, SQLState: 23000 BATCH
03/05/2011 06:41:11 ERROR
[JDBCExceptionReporter.java:78] -
ORA-01400: cannot insert NULL into
("mydb"."mytable"."PUBLISHED_DAYS_SINCE_LAST_PUB")
BATCH 03/05/2011 06:41:11 ERROR
[AbstractFlushingEventListener.java:301]
- Could not synchronize database state with session
org.hibernate.exception.ConstraintViolationException:
could not insert:
[com.xxx.myentity]
at
org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:71)
at
org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2262)
at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2655)
at
org.hibernate.action.EntityInsertAction.execute(EntityInsertAction.java:60)
at
org.hibernate.engine.ActionQueue.execute(ActionQueue.java:279)
at
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:263)
at
org.hibernate.engine.ActionQueue.executeActions(ActionQueue.java:167)
at
org.hibernate.event.def.AbstractFlushingEventListener.performExecutions(AbstractFlushingEventListener.java:298)
at
org.hibernate.event.def.DefaultFlushEventListener.onFlush(DefaultFlushEventListener.java:27)
at
org.hibernate.impl.SessionImpl.flush(SessionImpl.java:1001)
at
org.hibernate.impl.SessionImpl.managedFlush(SessionImpl.java:339)
at
org.hibernate.transaction.JDBCTransaction.commit(JDBCTransaction.java:106)
at
org.springframework.orm.hibernate3.HibernateTransactionManager.doCommit(HibernateTransactionManager.java:655)
at
org.springframework.transaction.support.AbstractPlatformTransactionManager.processCommit(AbstractPlatformTransactionManager.java:732)
at
org.springframework.transaction.support.AbstractPlatformTransactionManager.commit(AbstractPlatformTransactionManager.java:701)
at
org.springframework.transaction.interceptor.TransactionAspectSupport.commitTransactionAfterReturning(TransactionAspectSupport.java:321)
at
org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:116)
at
org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
at
org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:635)
at
com.xxx.eplatform.websites.webstore.batch.processor.DistrinetDataProcessor$$EnhancerByCGLIB$$42d43018.processDistrinetLine() at
com.xxx.eplatform.websites.webstore.batch.services.impl.WebstoreImporterServiceImpl.importDistrinetFile(WebstoreImporterServiceImpl.java:71)
at
com.xxx.eplatform.websites.webstore.batch.WebstoreImportBatch.execute(WebstoreImportBatch.java:142)
at
com.xxx.eplatform.websites.webstore.batch.WebstoreImportBatch.main(WebstoreImportBatch.java:104)
Caused by: java.sql.SQLException:
ORA-01400: cannot insert NULL into
("mydb"."mytable"."PUBLISHED_DAYS_SINCE_LAST_PUB")
at
oracle.jdbc.driver.DatabaseError.throwSqlException(DatabaseError.java:112)
at
oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:331)
at
oracle.jdbc.driver.T4CTTIoer.processError(T4CTTIoer.java:288)
at
oracle.jdbc.driver.T4C8Oall.receive(T4C8Oall.java:745)
at
oracle.jdbc.driver.T4CPreparedStatement.doOall8(T4CPreparedStatement.java:216)
at
oracle.jdbc.driver.T4CPreparedStatement.executeForRows(T4CPreparedStatement.java:966)
at
oracle.jdbc.driver.OracleStatement.doExecuteWithTimeout(OracleStatement.java:1170)
at
oracle.jdbc.driver.OraclePreparedStatement.executeInternal(OraclePreparedStatement.java:3339)
at
oracle.jdbc.driver.OraclePreparedStatement.executeUpdate(OraclePreparedStatement.java:3423)
at
org.hibernate.jdbc.NonBatchingBatcher.addToBatch(NonBatchingBatcher.java:23)
at
org.hibernate.persister.entity.AbstractEntityPersister.insert(AbstractEntityPersister.java:2242)
... 21 more
I don't understand what is wrong since the primitive type i added to the entity is always initialized at 0 so it shouldn't be null.
I've also looked my entity class with javap and it seems it's the right version of the entity: my new attribute is there.
Anyone? Thanks
Just Change int to Integer and see if it help

Categories