Spring Data JPA is part of Spring Data family. Spring Data makes it easier to create Spring driven applications that use new ways to access data, such as non-relational databases, map-reduction frameworks, cloud services, as well as well-advanced relational database support. Unfortunately, (at least for Hibernate) changing the @Version field manually is not going to make it another 'version'. Optimistic concurrency checking is done against the version value retrieved when entity is read, not the version field of entity when it. I am working on getting back up to speed on Spring, Spring Data and JPA. I was interested in implementing the Specifications piece to enable a more dynamic query. Say I have the following methods.
- Spring Jpa Print Sql
- Spring Data Jpa Sql Injection
- Spring Data Jpa Show Sql
- Spring Data Jpa Sql Injection Query
I have the following code snippet from my GenericDAOImpl
// createQuery() is a private method which builds the where clause and order by clause from the Map/List
This is one sample query this code snippet created : “SELECT o from temptable o where type = 'x'”
I am just trying to know whether my code is SQL injection prone. Some of the articles say when inlining user input the code is injection prone. I tried to create some of the injection scenarios and my test user inputs created following queries to test the SQL injection.
In both these cases below exceptions were thrown respectively, so no table drop happened.


I am using the JPA implementation of Hibernate.
In that case, is this code still injection prone? Am I missing some other test cases? Or do you think any other JPA implementation will fail to throw the exception in such case?
Thanks in advance.
It is still subject to SQL injection; for example (*):
could be switched to
(*) Yes, storing plain text passwords is also wrong to begin with, it is just an example of sensitive information.
Since you already have all the values stored in lists, changing your code to use setParameter
is pretty trivial (hint, just name then :param0
, :param1
, ... and set them in order), so I do not understand why you would not use it to begin with.
PHP: While loop not working after adjusting SELECT for SQL injection prevention
php,mysql,select,sql-injection,associative-array
You cannot bind column and table names, only data. You need to specify the table and then bind for your '%calendar weekday%'. $stmt = $conn->prepare('SELECT ' . $selectLang . ' FROM `TranslationsMain` WHERE `location` LIKE ? ORDER BY `sortOrder`, ' . $selectedLang); $stmt->bind_param('s', $calendar_weekday); ...
Use JSF, JPA, JTA, JAAS, CDI, Bean Validation with Tomcat? [closed]
jsf,tomcat,jpa,cdi,jta
Yes. Except of JAAS. ...
Transaction error in Spring
Spring Jpa Print Sql
java,spring,jpa
In the stacktrace, there are no Spring AOP class listed between these two lines: at com.vizaco.onlinecontrol.service.impl.UserServiceImpl.saveUser(UserServiceImpl.java:51) at com.vizaco.onlinecontrol.controller.UserController.createUser(UserController.java:112) Your Dependency Injection is not setup right.. the Controller should be getting a Spring Bean of UserService ...
performance of executing openjpa query
java,performance,jpa,openjpa
The problem is that you are measuring two different things.164 ms is the time that the database spent executing the query. I suspect the 824 ms that you measured is query execution + instantiation of your Entity objects.
@Resource datasource breaking DB connection
java,jpa,jdbc,jboss,wildfly
There are a few possibilities what could go wrong. First, you are opening the connection in initParser(), but closing it in finalizeParser(), without using finally. If an exception is thrown, the connection is not closed. It would still be better to use try-with-resources. Another potential problem is that the class...
Sqlite JPA Primary Key error
java,sqlite,jpa
I don't think your second insert is colliding with the two values (secID = 1 and 2) already in the table; I think it's colliding with the value you just inserted (secID = 0). You aren't explicitly setting secID anywhere, which means it's 0. So it's inserting 0, over and...
JPA AccessType.Property failing to retrieve value from nested classes
java,jpa,persistence
Your @Transient annotation may be causing problem here. @Transient private String href; @Transient used to indicate that perticular field should not be persisted in underlying persistance system i.e. database. you may follow this link as well ...
Configure HikariCP + Hibernate + GuicePersist(JPA) at Runtime
java,hibernate,jpa,hikaricp,guice-persist
Try removing the persistence-unit name from the JPA properties, so instead of: Map<String, String> properties = new HashMap<>(); properties.put('myJPAunit.hibernate.hikari.dataSource.url', 'jdbc:postgresql://192.168.100.75:5432/mpDb'); properties.put( + 'myJPAunit.hibernate.hikari.dataSource.user', 'cowboy'); properties.put( + 'myJPAunit.hibernate.hikari.dataSource.password', 'bebop'); you should have this: Map<String, String> properties = new HashMap<>(); properties.put('hibernate.hikari.dataSource.url',...
JPA and Apache Aries: persistence unit unresolved dependency
java,jpa,osgi,blueprint-osgi,aries
The problem was due to a fistful of missing bundles in my runtime. To solve the problem it was enough to look at the blog sample project within the Apache Aries Samples and replicate that runtime in my bnd file. The bundles I added are the following: org.apache.aries.transaction.wrappers org.apache.aries.jpa.container org.apache.aries.jpa.container.context...
Cache inconsistency - Entity not always persisted in cached Collection
java,hibernate,jpa,caching,ehcache
The Hibernate Collection Cache always invalidates existing entries and both the Entity and the Collection caches are sharing the same AbstractReadWriteEhcacheAccessStrategy, so a soft-lock is acquired when updating data. Because you are using a unidirectional one-to-many association, you will end up with a Validation table and a Step_validation link table...
OpenJPA OneToMany and composite key in parent and child table
java,jpa,jpa-2.0,openjpa
The easiest way to do this is to create an association from ChildObj to ParentObj similar to the following: @ManyToOne(fetch = FetchType.LAZY, optional = true) @JoinColumns({ @JoinColumn(name = 'serverId', referencedColumnName = 'serverId'), @JoinColumn(name = 'code', referencedColumnName = 'code')}) private ParentObj parentObj; and then define the @OneToMany association in ParentObj like...
JPA NamedNativeQuery syntax error with Hibernate, PostgreSQL 9
java,hibernate,postgresql,jpa
So the problem was that em.createNativeQuery(...) was not the correct invocation of a NamedNativeQuery in order to do that I should've invoked em.createNamedQuery(...). However, seeing that em.createNativeQuery(...) does not accept @SqlResultSetMapping it is very difficult to map the result to a custom class. The end solution was to use return...
Java JPA EM.createNativeQuery(sql, someClass).getResultList()
java,jpa
An SQL query of the form 'SELECT * FROM tbl' will return each row as Object[]. Hence you should do List<Object[]> results = ... To map to a specific result class (whatever your foobar is), follow this link. You can of course just use JPQL if wanting to map to...
javax.validation.ConstraintViolationException: Bean Validation constraint(s) violated while executing Automatic Bean Validation on event:'prePersist'
hibernate,jpa,eclipselink,bean-validation,jsr303

It looks like the version isn't actually set until the entity is modified, therefore rowVersion is null when the entity is first created. That fails your 'not null' check. Try this instead and see if it works: @Version @Basic(optional = false) @NotNull @Column(name = 'row_version', nullable = false) private Long...
Hibernate/JPA: Check generated sql before updating DB Schema (like .NET EF migrations)
java,hibernate,jpa
Yes, there is a schema generator class. org.hibernate.tool.hbm2ddl.SchemaExport Here's a sample code on how I use it (note that this was very highly inspired from a post here) package com.mypackage.jpa.util; import java.io.File; import java.net.URL; import java.util.ArrayList; import java.util.List; import org.hibernate.cfg.Configuration; import org.hibernate.tool.hbm2ddl.SchemaExport; public class SchemaGenerator { private Configuration cfg; public...
Spring 4 + JPA (Hibernate 4) + JTA transaction manager doesn't flush automatically
java,spring,hibernate,jpa,transactions
The problem is due to this property: <prop key='hibernate.transaction.jta.platform'>ch.vd.dsas.rdu.ref.transaction.jencks.JencksTransactionManagerLookup</prop> The hibernate.transaction.jta.platform property is not the same with hibernate.transaction.manager_lookup_class and it should point to an AbstractJtaPlatform implementation: <property name='hibernate.transaction.jta.platform' value='org.hibernate.service.jta.platform.internal.SunOneJtaPlatform'/> ...
Use alternative producers of EntityManager / EMF in integration tests
java,maven,jpa,integration-testing,cdi
After some research i found that DeltaSpike already has module called 'Test-Control', which enable use CDI in tests. So i decided to extend current EMF producer to read name of persistence unit from property file which contains configuration. Different property files in src/main/resources and src/test/resources lets me use different persistence...
Checking for multiple child constraint violations in Hibernate/JPA
spring,hibernate,jpa
I found a way to accomplish my end result, although it was through means I did not expect. In order to accomplish my goal, I would need to use nested transactions and SavePoints. At the end of the day, that implementation would still produce invalid data in my database, because...
Can I make this request more efficient using index?
java,mysql,sql,jpa
Change the query to: SELECT ui FROM Userinfo ui WHERE twitchChannel IS NOT NULL This will benefit from an index on Userinfo(twitchChannel) (assuming there really are very few values that are filled in). At the very least, this reduces the amount of data passed from the database to the application,...
@TransactionAttribute(TransactionAttributeType.REQUIRES_NEW) doesn't work
java,jpa,glassfish,ejb-3.0
deleteEmployee method is not wrapped into a new transaction because you are referencing method on this. What you can do is to inject reference to the facade itself and then call deleteEmployee method on it (it should be public). More or less something like this: @Stateless public class MyFacade {...
very high float value changing to infinity while retrieving from database
java,mysql,sql-server,hibernate,jpa
You should use double instead of float: // Float.MAX_VALUE = 3.4028234663852886E38f float f = Float.parseFloat('1.11111111111111E+49'); System.out.println('f=' + f); // -> f=Infinity // Double.MAX_VALUE = 1.7976931348623157E308 double d = Double.parseDouble('1.11111111111111E+49'); System.out.println('d=' + d); // -> d=1.11111111111111E49 ...
How to avoid SQL Injection with Update command in Npgsql?
database,postgresql,sql-injection,npgsql
As @tadman says, you should never use string concatenation to compose your query - that is the source of SQL injection. However, there's no need to prepare your statement. Use parameter placeholders in your query, something like the following should work: string UpdateCmd = 'update dx set chronic = @p1...
Why JPA entities are treated like this outside a session?
jpa,entity
It can't do anything else. The only alternative would be to return an empty collection of employees, which would be much much worse: you would incorrectly assume that the enterprise has 0 employee, which is a valid, but completely incorrect result. To realize how much worse it would be to...
Spring Data JPA user posts
java,spring,jpa,data
Create a second entity (java class) e.g. UserPost: @Entity @Table(...) public class UserPost { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private long id; private long userId; ... } Then add @OneToMany relationship field to User. Cascading, lazy-loading, etc. depends on how you'd use it. It'd look like this inside User: @OneToMany(cascade={...}) @JoinColumn(name='userId')...
PHP / MySQLi: How to prevent SQL injection on INSERT (code partially working)
php,mysql,mysqli,sql-injection,sql-insert
In the New PHP code snippet, you are still vulnerable to injections. You are using a prepared statement in the insert part, but you are not actually using the preparations strengths correctly. When creating a prepared statement, you create a query in which you add placeholders instead of the raw...
All I want is to access a H2 mem database in Websphere V8 using JPA 2.0
java,jpa,jdbc,websphere,persistence.xml
Found it! These full JNDI names doesn't seem to work in Websphere. I used a plain 'jdbc/sgodb' instead and it could find the context. <jta-data-source>jdbc/sgodb</jta-data-source> instead of <jta-data-source>java:comp/env/jdbc/sgodb</jta-data-source> ...
What are Relational Objects?
database,jpa,persistence
A Query indeed returns instances of entities, but it can also simply return arrays (i.e. rows), or lists of objects that are not entities.
Prevent SQL Injection when the table name and where clause are variables
asp.net,ado.net,sql-injection
Without knowing further details, there are several options you have in order to avoid SQL injections attacks or at least to minimize the damage that can be done: Whitelisting is more secure than blacklisting: Think about whether you really need access to all the tables except the blacklisted ones. If...
JPQL In clause error - Statement too complex
jpa,derby,jpql
Ok here is my solution that worked for me. I could not change the part generating the customerList since it is not possible for me, so the solution has to be from within this method. Bryan your explination was the best one, i am still confuse how 'in' clause worked...
How do I prevent MySQL Database Injection Attacks using vb.net?
mysql,.net,database,vb.net,sql-injection
MySQLCon.Open() Dim SQLADD As String = 'INSERT INTO members(member,gamertag,role) VALUES(@memberToAdd, @memberGamingTag, @memberRole)' COMMAND = New MySqlCommand(SQLADD, MySQLCon) COMMAND.Parameters.AddWithValue('@memberToAdd', memberToAdd.Text) COMMAND.Parameters.AddWithValue('@memberGamingTag', membersGamertag.Text) COMMAND.Parameters.AddWithValue('@memberRole', membersRole.Text) COMMAND.ExecuteNonQuery() memberToAdd.Text = ' membersGamertag.Text = ' membersRole.Text = ' MySQLCon.Close() MySQLCon.Dispose() You don't need to use...
Hibernate Query cache invalidation
java,hibernate,jpa,caching,concurrency
The query cache is not useful for write-mostly applications, as you probably figured out yourself. There is no write-through query caching option, so you need to question why you are using this feature in the first place. The entity caching is useful when you plan on changing those entities you’re...
org.hibernate.ejb.event.EJB3MergeEventListener missing after upgrading from Hibernate 3 to 4.3.9
java,hibernate,jpa,ejb
So it looks like this class (and a lot of the other EJB stuff) has been renamed and moved around. I was able to replace instances of org.hibernate.ejb.event.EJB3MergeEventListener (which was located in the hibernate-entitymanager jar in version 3.6.10) with org.hibernate.event.internal.DefaultMergeEventListener (which is actually located in the hibernate-core jar in version...
Envers Pre/PostCollection Listener
java,hibernate,jpa,hibernate-envers
That's when you have persistent collections, e.g. fields of type List<String>, or Set<EmbeddedComponent>.
Making an efficient query with 7 joins, JPA or SQL? What type of collection?
java,mysql,jpa,join
You say that the native SQL query runs in less than a millisecond. So stick with that. But that doesn't mean you have to wrestle with the List that comes from query.getResultList(). You can execute a native query (either from EntityManager.createNativeQuery() or from EntityManager.createNamedQuery() referring to a @NamedNativeQuery) and still...
Optimistic locking not throwing exception when manually setting version field
hibernate,jpa,spring-data-jpa
Unfortunately, (at least for Hibernate) changing the @Version field manually is not going to make it another 'version'. i.e. Optimistic concurrency checking is done against the version value retrieved when entity is read, not the version field of entity when it is updated. e.g. This will work Foo foo =...
Is it possible to connect a JPA implementation to a Neo4j specific version?
jpa,neo4j,datanucleus,kundera,hibernate-ogm
I have a sample app I've been playing with for a while, and was using DataNucleus v4.1 with the Neo4j it pulls in by default (2.1.3 IIRC). I just tried it with v2.0.0 and all runs fine for me. Just put the version of neo4j you want in the CLASSPATH...
JPA persit creates new existing entity in many to one relation
java,hibernate,jpa,insert
With merge you should be using: Entity entity=entityManager.merge(newEntity); int lastId=entity.getId(); to get the reference to the object and get its id where has persist does not need to because the entity is already managed after persist....
Retrieve the id of an Entity object as soon as the entity was instantiated?
jsf,jpa
There is no way to retrieve the ID before persisting - simply because it has no ID until you persist your entity. This has nothing to do with your strategy. It has something to do with concurrence. But you can add your own temporary key for your use case: @Entity...
How to know an object has changed compared to database
java,hibernate,jpa,playframework,playframework-1.x
To force Hibernate to start a new transaction in the playframework and thus give you a new entity manager that will return the object as it is in the database and not a reference to it, you need to specifically ask the play framework to start a new transaction through...
JPA annotation for MS SQL Server 2008 R2 IDENTITY column
hibernate,sql-server-2008,jpa,spring-data-jpa
I just found I missed setting up hibernate dialect on LocalContainerEntityManagerFactoryBean. After setting up org.hibernate.dialect.SQLServer2008Dialect as hibernate dialect, the GenerationType.IDENTITY works fine as Neil mentioned. Below is my spring data configuration and application.properties. FYI I have multiple datasource, one is H2 embedded datasource for internal use and the other is...
jsf - foreign key in datatable
jpa,datatable
I'm happy to say I found the solution! (kudos for @Mauricio Gracia to enlight my finding-a-solution path) First, I removed the 'fetch = FetchType.LAZY' from the customer relationship in Order class @ManyToOne(cascade={CascadeType.PERSIST}) @JoinColumn(name = 'customer_id') private Customer customer; Then, I serialized the Customer class @Entity public class Customer implements Serializable...
Unidirectional one-to-many mapping in Hibernate generates redundant updates
java,hibernate,jpa
Have you tried: @JoinColumn(name = 'parent_id', referencedColumnName = 'id', nullable = false, insertable=false, updatable=false) ...
How to Fetch Data using Spring Data
spring,jpa,spring-boot,spring-data
You want to find all books for a specific author so, given an Author, retrieve all Books whose set of Authors contains the specified Author. The relevant JPQL operator is: http://www.objectdb.com/java/jpa/query/jpql/collection#NOT_MEMBER_OF_ [NOT] MEMBER [OF] The [NOT] MEMBER OF operator checks if a specified element is contained in a specified persistent...
Why is my EntityManager not properly injected?
jpa,ejb,wildfly,entitymanager
thanks all for help; If anyone getting the same error than me, maybe this helps: I used managed beans in JSF which are EJB, but I need to use CDI-Beans. As I deleted the Beans from the faces-config.xml everything works fine. Sorry for asking this question....
Segregating the read-only and read-write in Spring/J2EE Apps
mysql,jpa,design-patterns,architecture,spring-data
When using MySQL, it is common for Java developers to use Connector/J as the JDBC driver (since this is the official JDBC driver from MySQL). Developers typically use the com.mysql.jdbc.Driver class as the driver, with a URL such as jdbc:mysql://host[:port]/database. Connector/J offers another driver called the ReplicationDriver that allows an...
Blocking Updating or Inserting an Entity when using Cascade in Hibernate
java,hibernate,jpa,orm,hibernate-mapping
If you never want to modify the EntCariHareketler, you could simply annotate it with @Immutable. If you the entity is mutable but you want to disable updates from the other side, you need to set to false the insertable and updatable @JoinColumn attribute: @OneToOne(fetch= FetchType.LAZY) @JoinColumn(name='carihareketid', insertable = false,...
Not persisted entity with Hibernate
java,spring,hibernate,jpa
Spring Data Jpa Sql Injection
upd Answer, corresponding to the first version of a question was entirely removed - in short, it suggested to flush changes again after entity was updated. Current problem is in mixing two kinds of annotation - first is @ManyToOne annotation that belongs to JPA specification and second is @Cascade that...
Get id column name from POJO, using reflection
java,jpa,reflection,annotations
This is the all-by-yourself solution: public static String getPKColumnName(Class<?> pojo) { if (pojo null) return null; String name = null; for (Field f : pojo.getDeclaredFields()) { Id id = null; Column column = null; Annotation[] as = f.getAnnotations(); for (Annotation a : as) { if (a.annotationType() Id.class) id...
Is it possible to have “connection preparation” with Spring / JPA persistency
java,spring,jpa,spring-data
Using AOP would seem to be one approach: an example of using AOP to enrich Spring Data repositories can be found at the below: https://github.com/spring-projects/spring-data-jpa-examples If you can get a reference to the injected EntityManager within the advice then you should be able to get the underlying connection from that...
multiple update with jpa
Spring Data Jpa Show Sql
java,jpa
Spring Data Jpa Sql Injection Query
Try the following: @Override public String estadoPedido(List<DetallePedido> lista) { EntityManager em = emf.createEntityManager(); //em.getTransaction().begin(); //Consider using Container managed transactions , // if you do remove this line and the line above, and have //entity manager injected ! String mensage = null; try { for (DetallePedido ped : lista) { detPed.setPedEstado('EN...

Comments are closed.