DataIntegrityViolationException: could not execute statement; SQL n/a; constraint fk_qjc1iwbdvgwixafwdkjn82tmt - java

I'm trying to figure Hibernate out. I thought I was doing ok with all the internet tutorials and all but I'm stuck with this exception. I'm trying to save an object that contains a couple Lists into my database.
The object is called DataPointsListResultSet and it contains a List predictDataPointsList and a actualDataPointsList
Here are the models:
(DataPointsListResultSet)
#Entity
public class DataPointsListResultSet {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer resultsetid;
#OneToMany(targetEntity= DataPoints.class,
mappedBy="dataPointsid",cascade = CascadeType.ALL,
fetch=FetchType.EAGER)
private List<DataPoints> predictDataPointsList = new ArrayList<>();
#OneToMany(targetEntity= DataPoints.class, mappedBy="dataPointsid",
cascade = CascadeType.ALL, fetch=FetchType.EAGER)
private List<DataPoints> actualDataPointsList = new ArrayList<>();
//getters and setters
(DataPoints)
#Entity
public class DataPoints {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer dataPointsid;
double x;
double y;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "resultsetid")
DataPointsListResultSet dataPointsListResultSet;
public DataPoints(){
}
//getters and setters
Here is the some of the Stacktrace:
Message Request processing failed; nested exception is
org.springframework.dao.DataIntegrityViolationException: could not
execute statement; SQL [n/a]; constraint
[fk_337ty7afmhvcde8gwkd0sd6bq]; nested exception is
org.hibernate.exception.ConstraintViolationException: could not
execute statement
Description The server encountered an unexpected condition that
prevented it from fulfilling the request.
Exception
org.springframework.web.util.NestedServletException: Request
processing failed; nested exception is
org.springframework.dao.DataIntegrityViolationException: could not
execute statement; SQL [n/a]; constraint
[fk_337ty7afmhvcde8gwkd0sd6bq]; nested exception is
org.hibernate.exception.ConstraintViolationException: could not
execute statement
Root Cause
org.springframework.dao.DataIntegrityViolationException: could not
execute statement; SQL [n/a]; constraint
[fk_337ty7afmhvcde8gwkd0sd6bq]; nested exception is
org.hibernate.exception.ConstraintViolationException: could not
execute statement
and this is the Java method that executes the logic:
public DataPointsListResultSet predictPriceOneAhead (MultiLayerNetwork net, List<Pair<INDArray, INDArray>> testData, double max, double min, int exampleLength, String nomeDoConjunto, GeneralStockDataSetIterator iterator) {
double[] predicts = new double[testData.size()];
double[] actuals = new double[testData.size()];
DataPointsListResultSet resultSet = new DataPointsListResultSet();
List<DataPoints> predictDataPointsList = new ArrayList<>();
List<DataPoints> actualDataPointsList = new ArrayList<>();
resultSet.setPredictDataPointsList(predictDataPointsList);
resultSet.setActualDataPointsList(actualDataPointsList);
resultSetDao.save(resultSet);
for (int i = 0; i < testData.size(); i++) {
predicts[i] = net.rnnTimeStep(testData.get(i).getKey()).getDouble(exampleLength - 1) * (max - min) + min;
actuals[i] = testData.get(i).getValue().getDouble(0);
DataPoints predictDataPoint = new DataPoints();
predictDataPoint.setDataPointsListResultSet(resultSet);
predictDataPoint.setY(predicts[i]);
predictDataPoint.setX(i);
dataPointsDao.save(predictDataPoint);
predictDataPointsList.add(predictDataPoint);
DataPoints actuaDataPoint = new DataPoints();
actuaDataPoint.setDataPointsListResultSet(resultSet);
actuaDataPoint.setY(actuals[i]);
actuaDataPoint.setX(i);
dataPointsDao.save(actuaDataPoint);
actualDataPointsList.add(actuaDataPoint);
}
log.info("Print out Predictions and Actual Values...");
log.info("Predict,Actual");
for (int i = 0; i < predicts.length; i++) log.info(predicts[i] + "," + actuals[i]);
return resultSet;
}
Could anyone shine some light into this issue, I'd really appreciate it!

You can try removing cascade = CascadeType.ALL from your DataPointsListResultSet entity and do save operations of both entities manually in your case.

Related

org.postgresql.util.PSQLException: ERROR: column must appear in the GROUP BY clause or be used in an aggregate function

I have 2 entities with unidirectional association.
#Entity
#Table(name = "albums")
public class Album {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private String ownerId;
private String name;
private Boolean isPublic;
#OneToMany(orphanRemoval = true)
#JoinTable(
name = "album_album_cards",
joinColumns = #JoinColumn(name = "album_id"),
inverseJoinColumns = #JoinColumn(name = "album_card_id"))
private List<AlbumCard> cards;
}
#Entity
#Table(name = "album_cards")
public class AlbumCard {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
private Integer price;
private String condition;
private String design;
private Integer count;
private Long cardId;
#UpdateTimestamp
private LocalDate updated;
}
And three tables albums, album_cards and album_album_cards (for mapping)
When i map entity to model the exception is throws.
2022-11-14 21:37:57.725 ERROR 18696 --- [nio-9999-exec-7] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
org.postgresql.util.PSQLException: ERROR: column "cards0_.album_id" must appear in the GROUP BY clause or be used in an aggregate function
at ru.berserkdeck.albums.impl.mapper.AlbumMapper.albumCardListToAlbumPositionModelList(AlbumMapper.java:57) ~[classes/:na]
at ru.berserkdeck.albums.impl.mapper.AlbumMapper.toModel(AlbumMapper.java:31) ~[classes/:na]
at java.base/java.util.Optional.map(Optional.java:260) ~[na:na]
at ru.berserkdeck.albums.impl.service.AlbumServiceImpl.getAlbum(AlbumServiceImpl.java:50) ~[classes/:na]
Last sql logs is
Hibernate: select album0_.id as id1_1_, album0_.is_public as is_publi2_1_, album0_.name as name3_1_, album0_.owner_id as owner_id4_1_ from albums album0_ where album0_.owner_id=? and album0_.id=?
Hibernate: select cards0_.album_id as album_id8_0_0_, cards0_.id as id1_0_0_, cards0_.id as id1_0_1_, cards0_.card_id as card_id2_0_1_, cards0_.condition as conditio3_0_1_, cards0_.count as count4_0_1_, cards0_.design as design5_0_1_, cards0_.price as price6_0_1_, cards0_.updated as updated7_0_1_ from album_cards cards0_ where cards0_.album_id=?
mapper code:
51 protected List<AlbumPositionModel> albumCardListToAlbumPositionModelList(List<AlbumCard> list) {
52 if (list == null) {
53 return new ArrayList<>();
54 }
55
56 List<AlbumPositionModel> list1 = new ArrayList<>();
57 list.forEach(e -> list1.add(albumCardToAlbumPositionModel(e))); <---- exception throws there. And it throws if i call any method of list (List<AlbumCard>)
58 return list1;
the service method, calling the mapper(i tried with Transactional annotation and without, result the same):
#Override
public Optional<AlbumModel> getAlbum(String ownerId, Long albumId) {
if (ownerId != null) {
return albumRepo
.findByOwnerIdAndId(ownerId, albumId)
.map(mapper::toModel);
} else {
return albumRepo
.findByIdAndIsPublic(albumId, true)
.map(mapper::toModel);
}
}
Anyone could help me? What I'm dooing wrong?
Try renaming the count column from
private Integer count;
to
#Column(name = "CARD_COUNT")
private Integer count;

Use entity's value in query with Hibernates #Formula annotation

Given the following db structure:
And having the following mapping for this structure:
#Entity
#Table(name = "a")
class A {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", updatable = false, nullable = false)
private int aId;
#Column(name = "title")
private String title;
#Formula("(SELECT COUNT(*) FROM b WHERE b.a_id = aId)")
private Integer count;
}
My aim is to get the count of all references to A from B (where aId in the query is the value of the current entity).
But I get following Error:
Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet] with root cause
java.sql.SQLException: Unknown column 'a0_.aId' in 'where clause'
As Simon mentioned you need to use the name of the column, not the attribute name. In your example above this would be:
#Formula("(SELECT COUNT(*) FROM b WHERE b.a_id = id)")
You have to use the name of the column not the attribute name:
#Formula("(SELECT COUNT(*) FROM b WHERE b.a_id = a_id)")

Join non-unique column in spring jpa

I was hopping to find an answer to my probleme on this here forum. My problem is as follows, I have two classes :
#Entity
#Table(name = "a")
public class A implements Serializable{
#Id
private String id = UUID.randomUUID().toString();
#Column(name = "REFERENCE_ID")
private String referenceId;
#Column(name = "VERSION")
private String version;
}
And
#Entity
#Table(name = "b")
public class B{
#Id
private String id = UUID.randomUUID().toString();
#Column(name = "REFERENCE")
private String reference;
#ManyToMany(fetch = FetchType.LAZY)
#NotFound(action = NotFoundAction.IGNORE)
#JoinColumnsOrFormulas({
#JoinColumnOrFormula(formula = #JoinFormula(value =
"(select r from A r where r.reference_id = reference_id order by r.version desc limit 1)",
referencedColumnName = "reference_id")),
#JoinColumnOrFormula(column = #JoinColumn(name = "reference_id",
referencedColumnName = "reference_id", insertable = false))
})
private A referenceId;
}
The thing is reference_id is not a unique key in the b table and was just an indicative value in table A so in order to fetch the entire correspondent row I had to do some filtering with the formula in my join annotation.
When I try to fetch my data I get the following error
[Request processing failed; nested exception is
org.springframework.dao.InvalidDataAccessResourceUsageException:
could not extract ResultSet; SQL [n/a]; nested exception is
org.hibernate.exception.SQLGrammarException: could not extract
ResultSet] with root cause org.postgresql.util.PSQLException:
ERROR: relation "a" does not exist Position : 309
EDIT
ACtually t works as intended when changing my join formula to
#JoinFormula(value =
"(select r from schema_A r where r.reference_id = reference_id order by r.version desc limit 1)",
referencedColumnName = "reference_id"))
the problem now is that the code is intended to work on multipple envirnments
as for my application.yml it looks a bit like this;
jpa:
database: POSTGRESQL
show-sql: true
hibernate:
ddl-auto: update
properties:
hibernate:
format_sql: true
default_schema: schema
jdbc:
lob:
non_contextual_creation: true
time_zone: UTC
Thanks for your responses :)
I agree with Simon's comment. For Postgres (and relational databases in general), the word "table" and "relation" are the same and where the term "relational" comes from. So, when it says "Can't find relation B" it literally means "Can't find a table called B".
You should check your connection settings for the schema to see if those tables have/haven't been defined. If it's not obvious, maybe add/edit the question accordingly with your connection settings & appropriate debugging showing you DO see the relations (tables) there.

Exception Description: A NullPointerException

I'm working on a project in java with a postgresql database and I'm having a problem when I try to insert data or rather when I commit.
It looks like it comes from a problem with ID (game_id) but I do not know what.
Here is the code of my entity :
#Entity
#Cacheable(true)
#Table(name = "game")
#Multitenant(MultitenantType.TABLE_PER_TENANT)
#TenantTableDiscriminator(type = TenantTableDiscriminatorType.SCHEMA, contextProperty = PersistenceUnitProperties.MULTITENANT_PROPERTY_DEFAULT)
public class Game implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#Column(name = "game_id", unique = true, nullable = false)
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Integer gameId;
#Column(name = "game_title", length = 256)
private String gameTitle;
#Temporal(TemporalType.DATE)
#Column(name = "game_released")
private Date gameReleased;
#Column(name = "game_img")
private Byte[] gameImg;
#Column(name = "game_desc", length = 3072)
private String gameDesc;
And here's how I try to insert my data :
EntityManagerFactory emf = Persistence.createEntityManagerFactory("projet_nintendo");
EntityManager em = emf.createEntityManager();
EntityTransaction transac = em.getTransaction();
transac.begin();
for(int ii = 0; ii < array.length(); ii++) {
Game g = new Game();
g.setGameId(Conversion.stringEnInt(array.getJSONObject(ii).getString("fs_id")));
g.setGameTitle(array.getJSONObject(ii).getString("title"));
JSONArray test = array.getJSONObject(ii).getJSONArray("dates_released_dts");
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
Date parsedDate = dateFormat.parse(test.getString(0));
g.setGameReleased(parsedDate);
} catch(Exception e) {
}
em.persist(g);
System.err.println(array.getJSONObject(ii).getString("pretty_date_s"));
}
transac.commit();
em.close();
emf.close();
I have this error :
Exception in thread "main" javax.persistence.RollbackException: Exception [EclipseLink-69] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd): org.eclipse.persistence.exceptions.DescriptorException
Exception Description: A NullPointerException was thrown while extracting a value from the instance variable [gameId] in the object [database.orm.Game].
Internal Exception: java.lang.NullPointerException
Mapping: org.eclipse.persistence.mappings.DirectToFieldMapping[gameId-->game.game_id]
Descriptor: RelationalDescriptor(database.orm.Game --> [DatabaseTable(game)])
at org.eclipse.persistence.internal.jpa.transaction.EntityTransactionImpl.commit(EntityTransactionImpl.java:157)
at test.main(test.java:79)
Caused by: Exception [EclipseLink-69] (Eclipse Persistence Services - 2.5.2.v20140319-9ad6abd)
Could you tell me what I'm doing wrong?
try(EntityManager em = emf.createEntityManager();
EntityTransaction transac = em.getTransaction()){
...
}
// don't need to close here em.. emf..
Try to remove your #GeneratedValue. Currently you are using
GenerationType.IDENTITY
This GenerationType indicates that the persistence provider must assign primary keys for the entity using a database identity column. IDENTITY column is typically used in SQL Server. This special type column is populated internally by the table itself without using a separate sequence. If underlying database doesn't support IDENTITY column or some similar variant then the persistence provider can choose an alternative appropriate strategy. In this examples we are using H2 database which doesn't support IDENTITY column.
This results in the database assigns a new value automatically for your id field and then EclipseLink have to retrieve it.

Hibernate autogeneration of Id doesn't seem to be working

I have my entity called Post which has Id as a primary key.
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "Id", unique = true, nullable = false)
public Integer getId() {
return Id;
}
public void setId(Integer id) {
Id = id;
}
In above code you may see GenerationType.IDENTITY which I would assume is responsible for generating a new ID in case of creation of a new Post.
However, when I make a HTTP POST with this JSON:
{"id":0,"title":"test","viewCount":0,"body":"test","tags":"","answerCount":0,"commentCount":0,"postTypeId":1,"favoriteCount":0,"creationDate":"Nov 25, 2015 11:43:22 AM","acceptedAnswerId":0,"lastEditorUserId":0,"score":0}
I am getting this error:
SEVERE: Servlet.service() for servlet [rest] in context with path [/StackExchange] threw exception [Request processing failed; nested exception is org.springframework.orm.jpa.JpaSystemException: could not execute statement; nested exception is org.hibernate.exception.GenericJDBCException: could not execute statement] with root cause
java.sql.SQLException: Field 'Id' doesn't have a default value
I haven't set AI though, maybe that is the cause. But I am unable to alter the table. The data in the table are from SQL dumps and I can't alter it to set Id as AutoIncrement

Categories