hsqldb not showing reflection of insert query while runing with JUnit test - spring

i am using hsqldb as database. i create LmexPostParamDao which has a method insertLmexPostParam(NameValuePostParamVO nameValuePostParamVO) which will insert data in databse. for testing this method i used JUnit test to insert some data in hsqldb.
my JUnit test method is as below:
#Test
public void testInsertLmexPostParam(){
String lmexPostParamId = UUID.randomUUID().toString();
NameValuePostParamVO nameValuePostParamVO = new NameValuePostParamVO();
nameValuePostParamVO.setLmexPostParamId(lmexPostParamId);
nameValuePostParamVO.setParamName("adapter_id");
nameValuePostParamVO.setParamValue("7");
lmexPostParamDao.insertLmexPostParam(nameValuePostParamVO);
}
my insert method is as below:
#Override
public void insertLmexPostParam(NameValuePostParamVO nameValuePostParamVO) {
String insertQuery = "insert into LMEX_POST_PARAM(lmex_post_param_id, param_name, param_value) values (?,?,?)";
String[] paramArr = { nameValuePostParamVO.getLmexPostParamId(), nameValuePostParamVO.getParamName(), nameValuePostParamVO.getParamValue()};
int update = adapterJdbcTemplate.update(insertQuery, paramArr);
System.out.println(update);
}
when i run my test case it's returning me 1 as output which is result of adapterJdbcTemplate. which means data inserted sucessfully. but when i see my database it is not showing me a that row which inserted. and when i debug my testcase method with same values it's give a exception : Data integrity violation exception. and after this exception when i see my database it's showing that row in my database. what will be the problem. i do not. when i see code it's look like everything is fine. help me to resolve this.
Thank you

Check your CREATE TABLE statement for LMEX_POST_PARAM. The CHAR and VARCHAR types must be defined as CHAR(N) and VARCHAR(N), with N large enough to accept the values that you insert. For example, VARCHAR(100).
If your problem is the database is not showing the successful insert, then you should create your database with WRITE_DELAY = 0 or false. See the HSQLDB documentation for the version you are using.

Related

Getting Second Order SQL Injection in Spring Hibernate

I am facing Second Order SQL Injection in the Spring-Hibernate application after scanning through the Checkmarx tool, I have gone through multiple questions in StackOverflow and in other platforms as well but did not get the right finding.
could you please look into the below code snip,
public String getOrderId(order_name){
String returnId= null;
Query query = entityManager.createNativeQuery("select order_id from order where order_name=?");
List<String> dataset = query.setParameter(1,order_name).getResultList();
if(dataset!=null){
returnId = dataset. Get(0);
}
return returnId;
}
In this above method, while calling getResultList(), getting a high vulnerability issue that, this method returns data flows through the code without being properly sanitized or validated, and eventually used in further database query in the method.
Earlier code was like this,
public String getOrderId(order_name){
String returnId= null;
String q = "select order_id from order where order_name="+order_name;
Query query = entityManager.createNativeQuery(q);
and directly it was used as a string append in query, which I have modified with set parameter,
Query query = entityManager.createNativeQuery("select order_id from order where order_name=?");
List<String> dataset = query.setParameter(1,order_name).getResultList();
but still after getting data from query.getResultSet(), it is asking for sanitizing and validating the data before use in further database query method.
and this return data is being used in further query like select * from return_Data where clause. (properly used in where clause to set parameter to avoid SQL injection).
and in the above query is used in another method where we pass return_Data as input to it.
could you please help here to know what checks and validation can be added to overcome this type of issue. Thanks in advance for prompt response.

how to update select column in Spring data?

Please check the below query I am trying to update a row by the composite key
my key combination is like:
int id
int versionId
String languageId
and query is:
#Transactional
#Modifying
#Query("update languageEntity l set l.language = :language where l.languageId = :languageId")
int UpdateProcessLanguage(#Param("language ") String processDesTranslation, #Param("languageId ") UserLanguageId languageId);
I am not getting any exception. function is returning 0, means no row effected.
please check what is worng.
It's hard to say without knowing the data. As a first step I would log the generated SQL statements (see how to log sql statements in spring-boot) and check if they look right.
Why you dont wan't to use save() method for that? Just change language property on your object and pass it to the save method. It will update the row.

Can't find tables with activeJDBC in H2 non-default schema

In my integration test, I am creating an H2 database with two schemas, A and B. A is set as the default schema, like it is in the normal setup for the application when it is running with a PostgreSQL database. During the integration test, I am starting both the H2 database and an embedded Tomcat server and execute the SQL files to initialise the database via Liquibase.
All models that are connected to tables in schema A are annotated with #Table("tablename"), whereas models for schema B are annotated with #Table("B.tablename"). When I call a REST endpoint in the embedded server, activeJDBC warns me:
WARN org.javalite.activejdbc.Registry - Failed to retrieve metadata for table: 'B.tablename'. Are you sure this table exists? For some databases table names are case sensitive.
When I then try to access a table in schema B in my Java code, activeJDBC throws the following exception (which is expected after the previous warning):
org.javalite.activejdbc.InitException: Failed to find table: B.tablename
at org.javalite.activejdbc.MetaModel.getAttributeNames(MetaModel.java:248)
at org.javalite.activejdbc.Model.hydrate(Model.java:207)
at org.javalite.activejdbc.ModelDelegate.instance(ModelDelegate.java:247)
at org.javalite.activejdbc.ModelDelegate.instance(ModelDelegate.java:241)
...
Accessing tables in schema A works as expected.
I am sure that the tables in schema B are actually created and contain data, because on top of Liquibase log entries for executing the files I can also access the database directly and get the table content as a result:
Initialisation of Database and server:
private String H2_CONNECTION_STRING = "jdbc:h2:mem:testdb;INIT=CREATE SCHEMA IF NOT EXISTS A\\;SET SCHEMA A\\;CREATE SCHEMA IF NOT EXISTS B\\;";
#Before
public void initializeDatabase() {
connection = DriverManager.getConnection(H2_CONNECTION_STRING);
Statement stat = connection.createStatement();
stat.execute("GRANT ALTER ANY SCHEMA TO PUBLIC");
LiquibaseInitialisation.initH2(H2_CONNECTION_STRING); // execute SQL scripts
EmbeddedServer.startServer();
}
Query to print content of B.tablename:
Logger Log = LoggerFactory.getLogger("test");
Statement stat = connection.createStatement();
stat.execute("SELECT * FROM B.tablename;");
connection.commit();
resultSet = stat4.getResultSet();
rsmd = resultSet.getMetaData();
columnsNumber = rsmd.getColumnCount();
while (resultSet.next()) {
builder = new StringBuilder();
for (int i = 1; i <= columnsNumber; i++) {
builder.append(resultSet.getString(i));
builder.append(" ");
}
Log.info(builder.toString());
}
This produces the desired output of the content of B.tablename.
The question is this: Why doesn't activeJDBC find the tables in schema B in the H2 database when it's clearly present, but works flawlessly in PostgreSQL? Am I missing something with regards to schemas in H2 or activeJDBC?
Please, log this as an issue: https://github.com/javalite/activejdbc/issues and provide full instructions to replicate this condition. Best if you can provide a small project.

Spring data Neo4j Affected row count

Considering a Spring Boot, neo4j environment with Spring-Data-neo4j-4 I want to make a delete and get an error message when it fails to delete.
My problem is since the Repository.delete() returns void I have no ideia if the delete modified anything or not.
First question: is there any way to get the last query affected lines? for example in plsql I could do SQL%ROWCOUNT
So anyway, I tried the following code:
public void deletesomething(Long somethingId) {
somethingRepository.delete(getExistingsomething(somethingId).getId());
}
private something getExistingsomething(Long somethingId, int depth) {
return Optional.ofNullable(somethingRepository.findOne(somethingId, depth))
.orElseThrow(() -> new somethingNotFoundException(somethingId));
}
In the code above I query the database to check if the value exist before I delete it.
Second question: do you recommend any different approach?
So now, just to add some complexity, I have a cluster database and db1 can only Create, Update and Delete, and db2 and db3 can only Read (this is ensured by the cluster sockets). db2 and db3 will receive the data from db1 from the replication process.
For what I seen so far replication can take up to 90s and that means that up to 90s the database will have a different state.
Looking again to the code above:
public void deletesomething(Long somethingId) {
somethingRepository.delete(getExistingsomething(somethingId).getId());
}
in debug that means:
getExistingsomething(somethingId).getId() // will hit db2
somethingRepository.delete(...) // will hit db1
and so if replication has not inserted the value in db2 this code wil throw the exception.
the second question is: without changing those sockets is there any way for me to delete and give the correct response?
This is not currently supported in Spring Data Neo4j, if you wish please open a feature request.
In the meantime, perhaps the easiest work around is to fall down to the OGM level of abstraction.
Create a class that is injected with org.neo4j.ogm.session.Session
Use the following method on Session
Example: (example is in Kotlin, which was on hand)
fun deleteProfilesByColor(color : String)
{
var query = """
MATCH (n:Profile {color: {color}})
DETACH DELETE n;
"""
val params = mutableMapOf(
"color" to color
)
val result = session.query(query, params)
val statistics = result.queryStatistics() //Use these!
}

Will Entity Framework and SQL Server lock a object/record while deleting it

I am deleting some objects and rows using two methods inside my asp.net MVC web application: first approach includes deleting an Entity Framework object, such as:
public void DeleteMyObject(MyObject a)
{
entities1.MyObject.Remove(a);
}
while the second approach is calling a stored procedure from my repository method to delete a database row such as:
public void Deleteuserclass(string a, int u)
{
entities1.deleteuserclass(a, u);
}
which calls the following stored procedure:
ALTER PROCEDURE dbo.deleteuserclass
#userid nvarchar(50),
#classid int
AS
Begin
Delete from Users_Classes where UserID = #userid AND ClassID = #classid
if ##rowcount = 0
Raiserror('No record deleted',1,16)
END
Using any of the above two approaches; can I be confident that if two delete requests for deleting the same object arrive at the server at the same time, then only one request will delete the record from the database and the other request will receive an exception (I mean will the Entity Framework or the SQL Server database lock the row while it is being deleted ?)?
BR
One or the other will execute first.
If your stored procedure is execured second you will get an exception due to the if statement in the stored procedure.
If the EF command is executed second there will be a OptimisticConcurrencyException, see: EF eqivalent for rows affected of SqlCommand.ExecuteNonQuery

Resources