How To Update multi rows once in spring JPA? - java

I use ICsvBeanReader to read CSV files.
So what is the best workaround to update rows read from CSV file in the database without creating a new record if its id is new?
I can't use
saveAll(Iterable)
because it will create a new record if it's id not found.
Example
private Long id;
private int quantity;
private String name;
CSV File
id,quantity,name
1,30,name1
2,30,name2
20,30,name3
...
Note that:- row 20 is not found in the table so ignore it in an update.

JPA doesn't have an API to update an entity only if it exists, you can do a merge() which will update if the entity exists but it will also create a new row if it doesn't already exist.
Hibernate has an update() method which will update a row if it exists, but fail if the row doesn't exist.

I overcame this problem with a simple workaround.
Fetch all table ids and check if CSV row id found in the table ids list so add this row to the new list else ignore this row.
In final send the new list to saveall(iterable) method.

Related

Inserting id column in new table

I have situation like this.
I need to read data from a table. Let's say this table is called Person_Old and has three columns
I need to read the data from Person_Old and to save in another table called Person_New. In the Person_New table, I need to insert an extra column called ID. So in the Person_New table, I have a total of 4 columns.
The new table should be like this:
I have a Java class Called Person. where i have three fields firstname, lastname and dateOfBirth. Now if i insert another field called id like below
#ID
#GeneratedValue
private Long id;
then I get an error
Invalid column name ID
So now my question is how to insert this id column in my java class and in the SQL script for creating Person_new table so that when I run the program it'll read the data from old table and while persisting data in new table it'll generate Ids for each entry.
I would be grateful for your suggestions. Thank you.
You should define the column name and Primary key annotation need to be corrected.
#Id
#GeneratedValue
#Column("ID")
private Long id;

How to Delete Entity from Database and Store a Clone in a Different Database Table in Java/Spring/Hibernate

My goal is
Delete entity in current table
Clone the deleted entity to another table to store for future reference
Thanks
My suggestion is to not delete first, but rather copy the entity into the table you wish, make sure it is successfull by checking the result code, then delete the entity from the table.
INSERT INTO copy_table
SELECT * FROM original_table
WHERE condition;
DELETE FROM original_table
WHERE condition;
In JPA
https://docs.spring.io/spring-data/jpa/docs/1.5.0.RELEASE/reference/html/jpa.repositories.html
Entity x = jpaRepository.findById(id);
cloneTableJpaRepo.save(x);
jpaRepository.delete(x);

Android ROOM INSERT in pre-populated database

So, in my app I have a pre-populated database (I used SQLiteStudio to add the data and set the primary key on auto-increment for each table).
I want to add more rows in the one table of the database (that has already some data).
The problem is that the primary key is not auto-incremented and I think this happens because there is already some data in the table.
Does anyone know how to make the autogenerate work for pre-populated databases? Or the only solution is to manually add the ID, by selecting max(ID) from the table and adding 1 to it ?
Thank you in advance for taking some time to read this!
One of these tables is Users and I put the autogenerated pk:
#Entity(tableName = "users")
public class Users_table {
#PrimaryKey(autoGenerate = true)
private int userID;
// the rest of the code
}
I also checked and the #Insert method is called but I saw in logs that all userIDs are 0.

How to insert a row into a table with a column is List from a select query in PostgreSQL?

I am learning PostgreSQL, and need help to solve one problem.
I have two java entity classes, say
User
{
Long id;
String name;
Set<Long> bookIds;
}
Book
{
Long id;
String name;
}
When it translated into PostgreSQL DB scheme, it created a user table, user_bookids table and book table.
I want to insert a new row into user table and user_bookids table with bookids selected ids from book table.
I knew how to do it in Java land, I can create a user object and populate the bookIds list and persist, data will be populated to two tables.
but how can I do this in PostgreSQL.
Thanks in advance for all helps.

Get generated key value while inserting in partitioned table

Hi I have a table in Postgres, say email_messages. It is partitioned so whatever the inserts i do it using my java application will not effect the master table, as the data is actually getting inserted in the child tables. Here is the problem, I want to get an auto generated column value (say email_message_id which is of big serial type). Postgres is returning it as null since there is no insert being done on master table. For oracle I used GeneratedKeyHolder to get that value. But I'm unable to do the same for partitioned table in postgres. Please help me out.
Here is the code snippet we used for oracle
public void createAndFetchPKImpl(final Entity pEntity,
final String pStatementId, final String pPKColumnName) {
final SqlParameterSource parameterSource =
new BeanPropertySqlParameterSource(pEntity);
final String[] columnNames = new String[]{"email_message_id"};
final KeyHolder keyHolder = new GeneratedKeyHolder();
final int numberOfRowsEffected = mNamedParameterJdbcTemplate.update(
getStatement(pStatementId), parameterSource, keyHolder, columnNames);
pEntity.setId(ConversionUtil.getLongValue(keyHolder.getKey()));
}
When you use trigger-based partitioning in PostgreSQL it is normal for the JDBC driver to report that zero rows were affected/inserted. This is because the original SQL UPDATE, INSERT or DELETE didn't actually take effect, no rows were changed on the main table. Instead operations were performed on one or more sub-tables.
Basically, partitioning in PostgreSQL is a bit of a hack and this is one of the more visible limitations of it.
The workarounds are:
INSERT/UPDATE/DELETE directly against the sub-table(s), rather than the top-level table;
Ignore the result rowcount; or
Use RULEs and INSERT ... RETURNING instead (but they have their own problems) (Won't work for partitions)

Categories

Resources