I can't save result of select into database using JPA in Spring Boot application. The code that I use is below:
#Override
#Transactional
public void fetchAndSave() {
List<TestData> all = testDataRepository.findAllRecords();
testDataRepository.saveAll(all);
// let suppose I will save another data here that's why I need #Transactional for roll-back in case of exception
}
#Repository
public interface TestDataRepository extends JpaRepository<TestData, Long> {
#Query(value = "select raw_values.identificator AS id, raw_values.name as value from test.raw_values", nativeQuery = true)
List<TestData> findAllRecords();
}
When I call fetchAndSave with a property spring.jpa.show-sql=true I see in logs only select:
Hibernate: select raw_values.identificator AS id, raw_values.name as value from test.raw_values
In a case I don't use #Transactional I can see more requests to database in logs and values are saved:
Hibernate: select raw_values.identificator AS id, raw_values.name as value from test.raw_values
Hibernate: select testdata0_.id as id1_0_0_, testdata0_.value as value2_0_0_ from test.test_data testdata0_ where testdata0_.id=?
Hibernate: select testdata0_.id as id1_0_0_, testdata0_.value as value2_0_0_ from test.test_data testdata0_ where testdata0_.id=?
Hibernate: select testdata0_.id as id1_0_0_, testdata0_.value as value2_0_0_ from test.test_data testdata0_ where testdata0_.id=?
Hibernate: insert into test.test_data (value, id) values (?, ?)
Hibernate: insert into test.test_data (value, id) values (?, ?)
Hibernate: insert into test.test_data (value, id) values (?, ?)
I have a pretty simple table in database, DDL looks like:
create table test_data
(
id serial not null
constraint test_data_pk
primary key,
value varchar(256)
);
-- There are 3 records in table raw_values
create table table_name
(
identificator integer not null
constraint table_name_pk
primary key,
name varchar(256)
);
Can you help me to identify the reason of such behavior? I expect records to be saved into database when I use #Transactional.
The short answer for "why it does not save" is: because they are already saved.
The longer answer is Hibernate sees that these IDs has already present in DB, and it does not save them.
If you want to inset another three entities to DB, just create duplicates for these objects, with id=null and save them:
List<TestData> all = testDataRepository.findAllRecords();
List<TestData> copies = all.stream()
.map(testData -> new TestData(...)) //copy all the fields EXCEPT ID
.collect(toList());
testDataRepository.saveAll(copies);
Related
I have a spring boot project using JPA hibernate.
I'm trying to make a custom query that inserts the results of a select into a table. How would I do that?
This is my SQL query:
INSERT INTO aggregateTable
(
SELECT
avgSalesA,
avgSalesB,
salesMade,
tableA.employeeid
FROM
(
SELECT
avg(sales) as avgSalesA,
count(salesMadeDaily) as SalesMadeTotal,
employeeid
FROM companyA
GROUP BY employeeid
) tableA
INNER JOIN
(
SELECT
avg(sales) as avgSalesB,
employeeid
FROM companyB
GROUP BY employeeid
) tableB
ON tableA.employeeid = tableB.employeeid
)
You could simply use JPA:
entityManager.executeUpdate("INSERT INTO aggregateTable (Select avgSalesA, avgSalesB,
salesMade, tableA.employeeid FROM
(SELECT avg(sales) as avgSalesA, count(salesMadeDaily) as
SalesMadeTotal, employeeid FROM companyA GROUP BY
employeeid) tableA INNER JOIN (SELECT
avg(sales) as avgSalesB, employeeid FROM companyB group
by employeeid)
tableB ON tableA.employeeid = tableB.employeeid)");
Or if you use Spring Data repositories
#Modifying
#Query("<your insert query", nativeQuery=true)
public int insert();
I`m using Spring Data JPA with embedded H2 database. I have two sql files:
schema.sql
CREATE TABLE SINGER (
ID INT NOT NULL AUTO_INCREMENT,
FIRST_NAME VARCHAR(60) NOT NULL,
LAST_NAME VARCHAR(60) NOT NULL,
BIRTH_DATE DATE,
CONSTRAINT UQ_SINGER UNIQUE (FIRST_NAME, LAST_NAME),
PRIMARY KEY (ID)
);
CREATE TABLE ALBUM(
ID INT NOT NULL AUTO_INCREMENT,
SINGER_ID INT,
TITLE VARCHAR(100) NOT NULL,
RELEASE_DATE DATE,
CONSTRAINT UQ_ALBUM UNIQUE (TITLE),
CONSTRAINT FK_ALBUM FOREIGN KEY (SINGER_ID) REFERENCES SINGER (ID),
PRIMARY KEY (ID)
);
data.sql
INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('John', 'Mayer', '1977-10-16');
INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('Eric', 'Clapton', '1945-03-30');
INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('Jorn', 'Butler', '1975-04-01');
INSERT INTO ALBUM (SINGER_ID, TITLE, RELEASE_DATE) VALUES (1, 'The Search For Everything', '2017-01-20');
INSERT INTO ALBUM (SINGER_ID, TITLE, RELEASE_DATE) VALUES (1, 'Battle Studies', '2009-11-17');
INSERT INTO ALBUM (SINGER_ID, TITLE, RELEASE_DATE) VALUES (2, 'From The Cradle', '1994-09-13');
Database configuration:
#Bean
public DataSource dataSource() {
try {
EmbeddedDatabaseBuilder builder = new EmbeddedDatabaseBuilder();
return builder.setType(EmbeddedDatabaseType.H2)
.addScripts("db/schema.sql", "db/data.sql")
.build();
} catch (Exception ex) {
log.error("Cannot create DataSource", ex);
return null;
}
}
The problem is: schema.sql is executed while data.sql not. All test (find all data, find by id, insert, update, delete) passes successfully
Logs
INFO [main] org.springframework.jdbc.datasource.init.ScriptUtils:510 - Executed SQL script from class path resource [db/schema.sql] in 47 ms.
INFO [main] org.springframework.jdbc.datasource.init.ScriptUtils:444 - Executing SQL script from class path resource [db/data.sql]
DEBUG [main] org.springframework.jdbc.datasource.init.ScriptUtils:476 - 1 returned as update count for SQL: INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('John', 'Mayer', '1977-10-16')
DEBUG [main] org.springframework.jdbc.datasource.init.ScriptUtils:476 - 1 returned as update count for SQL: INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('Eric', 'Clapton', '1945-03-30')
DEBUG [main] org.springframework.jdbc.datasource.init.ScriptUtils:476 - 1 returned as update count for SQL: INSERT INTO SINGER (FIRST_NAME, LAST_NAME, BIRTH_DATE) VALUES ('Jorn', 'Butler', '1975-04-01')
DEBUG [main] org.springframework.jdbc.datasource.init.ScriptUtils:476 - 1 returned as update count for SQL: INSERT INTO ALBUM (SINGER_ID, TITLE, RELEASE_DATE) VALUES (1, 'The Search For Everything', '2017-01-20')
DEBUG [main] org.springframework.jdbc.datasource.init.ScriptUtils:476 - 1 returned as update count for SQL: INSERT INTO ALBUM (SINGER_ID, TITLE, RELEASE_DATE) VALUES (1, 'Battle Studies', '2009-11-17')
DEBUG [main] org.springframework.jdbc.datasource.init.ScriptUtils:476 - 1 returned as update count for SQL: INSERT INTO ALBUM (SINGER_ID, TITLE, RELEASE_DATE) VALUES (2, 'From The Cradle', '1994-09-13')
INFO [main] org.springframework.jdbc.datasource.init.ScriptUtils:510 - Executed SQL script from class path resource [db/data.sql] in 16 ms.
DEBUG [main] org.springframework.jdbc.datasource.DataSourceUtils:340 - Returning JDBC Connection to DataSource
It seems like data.sql is executed successfully, but I doesn`t see the data (in test methods) as long as I insert some.
UPDATE: I have following test methods (all they pass successfully, but in testFindAll() I don`t see any data):
#Test
void testFindAll() {
List<Singer> singers = singerRepository.findAll();
assertNotNull(singers);
displayAllSingers(singers);
}
#Test
void testInsert() {
Singer singer = createSinger();
singerRepository.insert(singer);
assertNotNull(singer.getId());
displayAllSingers(singerRepository.findAll());
}
You don`t need to worry about SingerRepository implementation, it works properly (in testInsert() you can see singerRepository.findAll() and it works, I see inserted singer).
It happens when I insert entity from UI and it stores in db for the first time as I have entered. After I refresh page, it updates db and returns me some invalid chars. Something like this:
'8', NULL, NULL, '?e??_??e?', '?e??_o??a??', '2', NULL, '?e??_o?'
Here it is the part of sql log:
Hibernate:
/* insert test.model.Smer
*/ insert
into
test.smer
(naziv, smer, oblast, obrazovni_profil, odsek_id, stari_naziv, studijska_grupa_id)
values
(?, ?, ?, ?, ?, ?, ?)
Hibernate:
/* select
generatedAlias0
from
Smer as generatedAlias0 */ select
smer0_.smer_id as smer_id1_19_,
smer0_.naziv as naziv2_19_,
smer0_.smer as smer3_19_,
smer0_.oblast as oblast4_19_,
smer0_.obrazovni_profil as obrazovn5_19_,
smer0_.odsek_id as odsek_id8_19_,
smer0_.stari_naziv as stari_na6_19_,
smer0_.studijska_grupa_id as studijsk7_19_
from
test.smer smer0_
Hibernate:
select
odsek0_.odsek_id as odsek_id1_13_0_,
odsek0_.odsek as odsek2_13_0_
from
test.odsek odsek0_
where
odsek0_.odsek_id=?
Hibernate:
select
odsek0_.odsek_id as odsek_id1_13_0_,
odsek0_.odsek as odsek2_13_0_
from
test.odsek odsek0_
where
odsek0_.odsek_id=?
Hibernate:
select
odsek0_.odsek_id as odsek_id1_13_0_,
odsek0_.odsek as odsek2_13_0_
from
test.odsek odsek0_
where
odsek0_.odsek_id=?
Hibernate:
/* select
generatedAlias0
from
Odsek as generatedAlias0 */ select
odsek0_.odsek_id as odsek_id1_13_,
odsek0_.odsek as odsek2_13_
from
test.odsek odsek0_
Hibernate:
/* update
test.model.Smer */ update
test.smer
set
naziv=?,
smer=?,
oblast=?,
obrazovni_profil=?,
odsek_id=?,
stari_naziv=?,
studijska_grupa_id=?
where
smer_id=?
What language are you working with?
Double check to see if the page is utf-8 (or whatever suitable) and the database field must be the same char-set then check the received values before sending them to DB to check where that happens exactly.
I have a table, populated with an import file.
Now I need to declare the related entity AUDIT and We have try to create a procedure for insert the revinfo in the Audit Table, by this way:
Extract from the DB the max REV and max RevTS
#Query(value="select max(rev) from revinfo",nativeQuery=true)
int findMaxRev();
#Query(value="select max(revtstmp) from revinfo",nativeQuery=true)
Long findMaxrevtstmp();
At this data we add a +1 value, and try to set it in this query:
#Query(value="insert into revinfo (`rev`, `revtstmp`) values (:rev, :revtstmp)", nativeQuery=true)
void addRevInfo(#Param("rev") int rev, #Param("revtstmp")Long revtstmp);
#Query(value="insert into entity_h (id, audit_revision, action_type, audit_revision_end, audit_revision_end_ts ) "
+ "values (:id, :rev, 0, null, '2017-08-31 10:45:37')", nativeQuery=true)
void addEnvers(#Param("id")long id, #Param("rev")int rev);
But when we run the addRevInfo query, We obtain this error:
`ERROR: org.hibernate.engine.jdbc.spi.SqlExceptionHelper - Can not issue data manipulation statements with executeQuery()`.
If we run this same query directly in MySQLWorkbench, the insert run without problem.
What's wrong?
Try to add this to you insert query:
#Modifying(clearAutomatically = true)
#Query("....")
With that the EntityManager flush your changes otherwise not, and it permit to use the executeUpdate() instead of exectueQuery() works for
the SQL statement, which returns a single ResultSet object
The executeUpdate instead is
for SQL statement, which may be an INSERT, UPDATE, or DELETE statement
or an SQL statement that returns nothing, such as an SQL DDL
statement.
In my application, which uses Spring and Hibernate, I parse a CSV file and populate the db by calling handleRow() every time a record is read from the CSV file.
My domain model:
'Family' has many 'SubFamily'
'SubFamily' has many 'Locus'
a 'Locus' belongs to a 'Species'
Family <-> SubFamily <-> Locus are all bi-directional mappings.
Code:
public void handleRow(Family dummyFamily, SubFamily dummySubFamily, Locus dummyLocus) {
//Service method which access DAO layers
CommonService serv = ctx.getCommonService();
boolean newFamily=false;
Family family=serv.getFamilyByFamilyId(dummyFamily.getFamilyId());
if(family==null){
newFamily=true;
family=new Family();
family.setFamilyId(dummyFamily.getFamilyId());
family.setFamilyIPRId(dummyFamily.getFamilyIPRId());
family.setFamilyName(dummyFamily.getFamilyName());
family.setFamilyPattern(dummyFamily.getFamilyPattern());
family.setRifID(dummyFamily.getRifID());
}
SubFamily subFamily = family.getSubFamilyBySubFamilyId( dummySubFamily.getSubFamilyId() );
if(subFamily==null){
subFamily=new SubFamily();
subFamily.setRifID(dummySubFamily.getRifID());
subFamily.setSubFamilyId(dummySubFamily.getSubFamilyId());
subFamily.setSubFamilyIPRId(dummySubFamily.getSubFamilyIPRId());
subFamily.setSubFamilyName(dummySubFamily.getSubFamilyName());
subFamily.setSubFamilyPattern(dummySubFamily.getSubFamilyPattern());
family.addSubFamily(subFamily);
}
//use the save reference, to update from GFF handler
Locus locus = dummyLocus;
subFamily.addLocus(locus);
assignSpecies(serv,locus);
//Persist object
if(newFamily){
serv.createFamily(family);
} else {
serv.updateFamily(family);
}
}
a Species is assigned to a Locus using following method, which simply accesses the DAO layer:
private void assignSpecies (CommonService serv, Locus locus) {
String locusId = locus.getLocusId();
String speciesId = CommonUtils.getLocusSpecies(locusId, ctx.getSpeciesList()).getSpeciesId();
//Simply get Species object from DAO
Species sp = serv.getSpeciesBySpeciesId(speciesId);
locus.setSpecies(sp);
}
Hibernate gives following error:
[INFO] Starting scheduled refresh cache with period [5000ms]
Hibernate: insert into species (species_id, name) values (?, ?)
Hibernate: insert into species (species_id, name) values (?, ?)
Hibernate: insert into species (species_id, name) values (?, ?)
############################ROW#####################1
SubFamiyID#######RIF0005913
Hibernate: select this_.id as id1_0_, this_.family_id as family2_1_0_, this_.rif_iD as rif3_1_0_, this_.family_name as family4_1_0_, this_.family_ipr_id as family5_1_0_, this_.family_pattern as family6_1_0_ from family this_ where this_.family_id=?
Creating NEW SubFamiyID#######RIF0005913
Hibernate: select this_.id as id3_0_, this_.species_id as species2_3_0_, this_.name as name3_0_ from species this_ where this_.species_id=?
Hibernate: insert into family (family_id, rif_iD, family_name, family_ipr_id, family_pattern) values (?, ?, ?, ?, ?)
Hibernate: insert into subfamily (sub_family_id, rif_iD, sub_family_name, sub_family_ipr_id, sub_family_pattern, family_id, sub_family_index) values (?, ?, ?, ?, ?, ?, ?)
Hibernate: insert into locus (locus_id, refTrans_id, function, species_id, sub_family_id, sub_family_index) values (?, ?, ?, ?, ?, ?)
Hibernate: update species set species_id=?, name=? where id=?
Hibernate: update subfamily set family_id=?, sub_family_index=? where id=?
Hibernate: update locus set sub_family_id=?, sub_family_index=? where id=?
############################ROW#####################2
SubFamiyID#######RIF0005913
Hibernate: select this_.id as id1_0_, this_.family_id as family2_1_0_, this_.rif_iD as rif3_1_0_, this_.family_name as family4_1_0_, this_.family_ipr_id as family5_1_0_, this_.family_pattern as family6_1_0_ from family this_ where this_.family_id=?
Hibernate: select subfamilie0_.family_id as family7_1_, subfamilie0_.id as id1_, subfamilie0_.sub_family_index as sub8_1_, subfamilie0_.id as id0_0_, subfamilie0_.sub_family_id as sub2_0_0_, subfamilie0_.rif_iD as rif3_0_0_, subfamilie0_.sub_family_name as sub4_0_0_, subfamilie0_.sub_family_ipr_id as sub5_0_0_, subfamilie0_.sub_family_pattern as sub6_0_0_, subfamilie0_.family_id as family7_0_0_ from subfamily subfamilie0_ where subfamilie0_.family_id=?
Hibernate: select locuslist0_.sub_family_id as sub5_1_, locuslist0_.id as id1_, locuslist0_.sub_family_index as sub7_1_, locuslist0_.id as id2_0_, locuslist0_.locus_id as locus2_2_0_, locuslist0_.refTrans_id as refTrans3_2_0_, locuslist0_.function as function2_0_, locuslist0_.sub_family_id as sub5_2_0_, locuslist0_.species_id as species6_2_0_ from locus locuslist0_ where locuslist0_.sub_family_id=?
Hibernate: select species0_.id as id3_0_, species0_.species_id as species2_3_0_, species0_.name as name3_0_ from species species0_ where species0_.id=?
Hibernate: select this_.id as id1_0_, this_.family_id as family2_1_0_, this_.rif_iD as rif3_1_0_, this_.family_name as family4_1_0_, this_.family_ipr_id as family5_1_0_, this_.family_pattern as family6_1_0_ from family this_ where this_.family_id=?
Hibernate: select this_.id as id3_0_, this_.species_id as species2_3_0_, this_.name as name3_0_ from species this_ where this_.species_id=?
Exception in thread "main" [INFO] Closing Compass [compass]
org.springframework.orm.hibernate3.HibernateSystemException: a different object with the same identifier value was already associated with the session: [com.bigg.nihonbare.common.domain.Species#1]; nested exception is org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.bigg.nihonbare.common.domain.Species#1]
Caused by: org.hibernate.NonUniqueObjectException: a different object with the same identifier value was already associated with the session: [com.bigg.nihonbare.common.domain.Species#1]
at org.hibernate.engine.StatefulPersistenceContext.checkUniqueness(StatefulPersistenceContext.java:590)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performUpdate(DefaultSaveOrUpdateEventListener.java:284)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.entityIsDetached(DefaultSaveOrUpdateEventListener.java:223)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.performSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:89)
at org.hibernate.event.def.DefaultSaveOrUpdateEventListener.onSaveOrUpdate(DefaultSaveOrUpdateEventListener.java:70)
at org.hibernate.impl.SessionImpl.fireSaveOrUpdate(SessionImpl.java:507)
at org.hibernate.impl.SessionImpl.saveOrUpdate(SessionImpl.java:499)
at org.hibernate.engine.CascadingAction$5.cascade(CascadingAction.java:218)
at org.hibernate.engine.Cascade.cascadeToOne(Cascade.java:268)
Any tips?
Use merge(). The exception means that the current session is already aware of the entity you are passing. If not, check how you have overridden hashCode() and equals() - it should return different values for different entities.
You can also encounter this problem if you are doing a delete() or update(). The problem is likely to occur if you build the hibernate-mapped pojo yourself, perhaps from a DTO. This pojo now has the same identifier as one that is already in the Session, and that causes the problem.
You now have two options. Either do what #Bozho said and first merge() the object. That takes care of updating. For deleting, take the object returned by merge() and delete it.
The other option is to first query the Session using the id of the object and then delete or update it.
I have seen this when an Entity does not have a GeneratedValue annotation for its ID column:
#GeneratedValue(strategy = GenerationType.AUTO)
I resolved so:
On delete method:
this.getHibernateTemplate().clear();
this.getHibernateTemplate().delete(obj);
// Esta línea realiza el "commit" del comando
this.getHibernateTemplate().flush();
On update method:
this.getHibernateTemplate().merge(obj);
// Esta línea realiza el "commit" del comando
this.getHibernateTemplate().flush();
If you are updating an object evict() it from session after the saveOrUpdate() call, also check your hashCode implementation of the object.
You may have created two instances of Session
Session session = factory.openSession();
If you have opened one session in one function and executing another function with creating another session, then this problem occurs.
This happened to me because part of my compound key was null. Ex:
#Id
#Column(name = "id")
private String id;
#JoinColumn(name = "id")
private Username username;
Username happened to be null which led to "duplicate" null primary keys, even though the id was different.