FAQ Database Discussion Community


Specifying whether or not to lazily load with Spring Data

java,spring,hibernate,jpa,spring-data
I have a lazy fetch type collection in an entity. And I am using Spring Data (JpaRepository) for accessing the entities. @Entity public class Parent{ @Id private Long id; @OneToMany(mappedBy = "parentId", fetch = FetchType.LAZY) private Set<Child> children; } I want two functions in service class and current implementation are...

Injecting Repository using Spring-Data-Solr

java,spring,spring-data,spring-data-solr
I am pretty new to Spring and thought I would try spring-data-solr. The problems seem to happen when I try to inject my TeamRepository which is an empty inteface which extends SolrCrudRepository. I've tried using annotatedConfiguration & XmlConfiguration and even both and seem to not be getting anywhere. The stack...

Check if User object exists in @DBRef List

spring,mongodb,spring-data,mongo-java,dbref
I'm making use of MongoDB, Spring Data and Spring MVC. I have a user model which has a list of contacts: class User { @DBRef private List<User> contacts = new ArrayList<User>(); public List<User> getContacts() { return contacts; } } I currently have 4 users inside my database. 1 user has...

Spring data repository QueryDslPredicateExecutor without pageable count

spring,spring-data,spring-data-jpa,querydsl
I'm trying to create a spring data repository with a method to list a page of entities and a QueryDSL predicate using this: public interface EntityRespository extends JpaRepository<Entity, Integer>, QueryDslPredicateExecutor<Entity> { List<Entity> findAllBy(Predicate predicate, Pageable pageable); } As mentioned here Way to disable count query from PageRequest for getting total...

Get Spring Bean from AspectJ ProceedingJoinPoint

spring,spring-boot,spring-data,aspectj
I'm looking to get the Spring Data Repository interface or the bean calling void delete(id) using AspectJ, the problem with that function is there is no argument or return type to guess the bean, is there any idea how to get the calling bean or the interface name from AspectJ...

How to Fetch Data using Spring Data

spring,jpa,spring-boot,spring-data
Hey i want to create a repository extending JpaRepository and fetch result without writing actual query, In my example i have 2 tables Book and Author mapped by many to many relationship, suppose i want to fetch list of books by a particular author_id, since in my book entity, i...

Caused by: java.sql.SQLSyntaxErrorException: [SQL0205] Column MITMAS_MMCONO not in table OOLINE in schema

spring,hibernate,jpa,left-join,spring-data
I have 3 entity classes Ooline: @Entity @IdClass(OolineId.class) @NamedQuery(name="Ooline.findAll", query="SELECT o FROM Ooline o") public class Ooline implements Serializable { private static final long serialVersionUID = 1L; @ManyToOne(fetch = FetchType.LAZY) @JoinColumns({ @JoinColumn(name="mitmas_mmcono" , referencedColumnName="mmcono"), @JoinColumn(name="mitmas_mmitno" , referencedColumnName="mmitno") }) private Mitmas mitmas ; @ManyToOne(fetch = FetchType.LAZY) @JoinColumns({ @JoinColumn(name="mitfac_m9cono",...

How to access entity manager with spring boot and spring data

spring-boot,spring-data,spring-data-jpa
How to get access to the entity manager in the repository when we use spring boot and spring data? Otherwise, i will need to put my big query in annotation, i would prefer to have something clear... then a long text....

Why do my database customizations not get applied when using Spring Data JPA with Spring Boot?

spring,hibernate,jpa,spring-boot,spring-data
I'm trying to use Spring Data JPA in a Spring Boot project in this tutorial. These are my pom.xml dependencies: <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency>...

How to query for entities with many-to-many relationships?

java,spring,spring-data,spring-data-jpa
I have 3 entities that are in relationship. The following is a simplified example of my classes: @Entity public class Action {} @Entity public class Instance { @ManyToMany private Set<Action> actions; @ManyToMany private Set<CadSystem> cadSystems; } @Entity public class CadSystem {} How can I query for all Instances that belong...

Spring DATA JPA with Java 8 Stream NonUniqueResultException

hibernate,java-8,spring-data,spring-data-jpa
I defined a repository based on PagingAndSortingRepository to have the below query implementation @Query(" SELECT me FROM CustomerModelEntity me WHERE me.planNum = :planNum AND me.customerModelStatusCode IN ('AVL','PHO')" + " AND me.modelCode IN (SELECT e.modelCode FROM ModelEntity e WHERE e.modelStatusCode IN ('AVL','PHO'))") Stream<CustomerModelEntity> findByPlanNum(@Param("planNum") String planNum); The result is expected to...

Spring MVC-showing encrypted values in jsp

mysql,spring-mvc,spring-data,jdbctemplate
I am using Spring MVC,MYSQL, JdbcTemplate in my project. When I am fetching data from db using drop down list box in JSP page Instead of showing number upto 0-9. It is showing encrypted values. The data type that I've passed here is int. My Controller class: @RequestMapping(value="/index.htm", method =...

How can I sort one column by ascending and another by descending in Spring Data?

java,spring,sorting,spring-data,spring-data-jpa
Given the following page request let's say I wanted to Sort Descending by "created" but ascending by "name", how would I do that? the api doesn't seem to allow "direction" "field" pairs. new PageRequest( 1, 15, Sort.Direction.DESC, "created", "name" ) using Spring Data JPA 1.6.5....

How to use Or condition in PagingAndSortingRepository

spring,spring-data
I need to use two or more conditions on different fields in a Repository that extends PagingAndSortingRepository. For example: public interface PersonRepository extends PagingAndSortingRepository<Person,String> { Page<Person> findByCreatedUser(String createdUserId, Pageable pageable); } This method should filter by createdUserId=Person.createdUserId or createdUserId=Person.userId. How can this be done?...

Spring Data Neo4j how to aggregate

neo4j,spring-data,spring-data-neo4j,spring-hateoas
Im trying to do what I think should be a very basic task but I'm getting steam rolled. My code is as follows: @Query("match (x:Package) where x.houseAirwayBill = {self}.houseAirwayBill return count(x)") @JsonIgnore Long pieces @JsonProperty("total_pieces") Long getPieces(){ return pieces } However, it just throws a stack strace saying that it...

why I can't use string as id

spring,spring-data,spring-data-jpa
I am trying to create a user model with a CrudRepository: @Entity public class User { @Id @GeneratedValue private String username; private String password; public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public String getUsername() { return username; } public void setUsername(String...

MongoDB & Spring Data - Searching for a user by firstname/lastname

database,mongodb,spring-data,mongodb-query,criteria-api
I have the following collection: User { firstname, lastname } I want to search for users by firstname and/or lastname (firstname/lastname/firstname+lastname). What I have: Criteria criteria = new Criteria(); criteria.orOperator(Criteria.where("firstname").regex(searchQuery),Criteria.where("lastname").regex(searchQuery)); The problem with the above is that I can either search by firstname OR lastname, but not both (e.g. ''John...

What is the purpose of Spring Data and its level of Abstraction?

spring,spring-data,spring-data-gemfire,spring-data-redis
While trying to understand the purpose of 'Spring Data' i came across this article and tried few examples with Gemfire/ Redis repositories and their corresponding Spring-Data components. Could someone help me with the following questions. Scenario: When GemFire was my datastore, i had to use methods create, get and remove...

Parameter value did not match expected type (Spring Data JPA)

spring,hibernate,jpa,spring-data,spring-data-jpa
Let's say I have class A and B public class A{ @Id String id; private B b; } public class B{ @Id String id; private List<A> a; } I'm using @Queryfor my query since my query is too long for Query creation . @Query("select a from A a where b...

Does Spring Data MongoDB support enums?

spring-data,spring-data-mongodb
For Java enum type, I learn that there are two solutions for MongoDB: serialization and using Jackson’s ObjectMapper. Can the MongoRepository work with an enum data type with either of those approaches or I have to write a customized repository?

How can I sort on the results of a case statement in Spring Data?

java,jpa-2.0,spring-data,spring-data-jpa,criteria-api
we have a UI sortable table that is backed by the following query, clicking a column does order by ascending or descending on that column. Problem is that one of the columns either renders the the users role name or their human name dependent on a conditional, and we need...

Spring-Data-Neo4j annotated Cypher Query, match paramter

java,neo4j,spring-data,spring-data-neo4j
I'm trying to parametrize the match part of a annotated Cypher query with Spring-Data-Neo4j-3.1.4 as follows. The first method is working. Passing the node type as parameter in the second method fails. public interface NodeRepository extends CrudRepository<Node, Long> { @Query("START n=node(*) MATCH (n:Organization) RETURN n") List<Node> findByNodeType(); @Query("START n=node(*) MATCH...

Use @NodeEntity on interface/abstract class

neo4j,spring-data,spring-data-neo4j
Is it possible to add @NodeEntity (or even @RelationshipEntity) annotation from SpringData Neo4j on an interface or abstact class or their fields? If not, how do you manage these situations?

Spring MVC how to modify existing _id index for mongoDB?

mongodb,indexing,spring-data
By default, it looks like Mongo adds an index named _id_ for the _id field of the document. In spring, I'm trying to make that index unique but the following code doesn't work : (it doesn't do anything) I know the syntax is correct since if I change that code...

How to maintain bi-directional relationships with Spring Data REST and JPA?

java,spring-boot,spring-data,spring-data-rest
Working with Spring Data REST. IF you have a oneToMany or ManyToOne relationship, the PUT operation returns 200 on the "non-owning" entity but does not actually persist the joined resource. Example Entities. @Entity(name = 'author') @ToString class AuthorEntity implements Author { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) Long id String fullName @ManyToMany(mappedBy...

org.hibernate.exception.SQLGrammarException: could not prepare statement; nested exception is javax.persistence.PersistenceException

java,spring,hibernate,jpa,spring-data
I have 3 entity classes Ooline: @Entity @IdClass(OolineId.class) @NamedQuery(name="Ooline.findAll", query="SELECT o FROM Ooline o") public class Ooline implements Serializable { private static final long serialVersionUID = 1L; @ManyToOne(fetch = FetchType.LAZY) @JoinColumns({ @JoinColumn(name="mitmas_mmcono" , referencedColumnName="mmcono"), @JoinColumn(name="mitmas_mmitno" , referencedColumnName="mmitno") }) private Mitmas mitmas ; @ManyToOne(fetch = FetchType.LAZY) @JoinColumns({ @JoinColumn(name="mitfac_m9cono",...

Spring Data Neo4j: Complex relationships not persisting

java,neo4j,spring-data,spring-data-neo4j-4
When adding multiple relationships between nodes simultaneously, only some of them are created. In the example below, the calls to makeUser(...) are only populating some of the relationships. Main @Transactional void clearDatabase() { session.execute("MATCH (n) OPTIONAL MATCH (n)-[r]-() DELETE n,r"); } void createPeople() { Person mark = new Person("Mark"); mark.password...

Spring Data Neo4j: How do I pull a list of nodes of which I do not know the type?

java,neo4j,spring-data,spring-data-neo4j,graph-databases
I'm using Spring Data Neo4j and I'd like to pull a list of owners. An owner can be a :Person (human) or an :Entity (company). I'm not sure what Type<T> should be. I could use in the GraphRepository<Type> interface. My Query is: MATCH ()-[r:OWNED_BY]->(o) RETURN And this is the code...

com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of org.springframework.data.domain.Sort out of START_ARRAY token

java,json,jackson,spring-data
My objectMapper is fetching the value of type Page<User> as follows: userList = objectMapper.readValue(RestAdapter.get(url), new TypeReference<PageImplBean<User>>(){}); The PageImplBean extends PageImpl class as follows: public class PageImplBean<T> extends PageImpl<T> { private static final long serialVersionUID = 1L; private int number; private int size; private int totalPages; private int numberOfElements; private long...

JPA 2.1 Attribute Converter convert enum still insert int

java,spring-data,spring-data-jpa,jpa-2.1
i'm using spring data jpa with hibernate as provider. i'm trying to persist my enums on varchar(enum.tostring) instead of (0,1,2) my enum class: public enum MagasinType { PRINCIPAL { @Override public String toString() { return "Principale".toUpperCase(); } }, SECONDARY { @Override public String toString() { return "Secondaire".toUpperCase(); } }, MOBILE...

spring data null arguments

spring,spring-data,spring-data-jpa
I am trying to implement the service for a rest controller that takes optional filter parameters like first name, last name, age, etc. I want to use a JpaRepository method like below. The problem is, if a parameter is null then no records are found. When a argument is null...

How to add/remove elements from a MongoDB list using spring data?

mongodb,spring-data
I am using spring data to talk to mongo (although I know there are few downsides to it over the mongo driver for advanced use cases). My application has a mongodb document with one of the elements being a list. Now I want to add/delete specific elements from the list...

Is there a code leve approach to triggers with JPA

java,mysql,jpa,spring-data,spring-data-jpa
We have a moderate size Spring data / JPA application with around 100 tables. We have been fairly strict about design leaving the RDBMS to do what it is good at; persistence and maintaining all program logic at the code level. We now need to extend the application so that...

Cannot Declare Beans inside ApplicationContext.xml

java,spring,spring-mvc,spring-security,spring-data
Whoever answers correct will be rewarded My Implementation is as follows: NextShipmentDaoImpl.java public class NextShipmentDaoImpl implements NextShipmentDao{ private DataSource dataSource; public DataSource getDataSource() { return dataSource; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } LoginController.java @Controller public class LoginController { @Autowired private NextShipmentDao nextShipmentDao; public void setNextShipmentDao(NextShipmentDao nextShipmentDao)...

java.lang.NoSuchMethodError: org.springframework.beans.BeanUtils.findPropertyForMethod

eclipselink,spring-data,spring-data-jpa
I am getting below error while trying to configure spring data in my applciation. I am using spring data and EclipseLink, along with spring-security and oauth2. SEVERE: Exception sending context initialized event to listener instance of class org.springframework.web.context.ContextLoaderListener java.lang.NoSuchMethodError: org.springframework.beans.BeanUtils.findPropertyForMethod(Ljava/lang/reflect/Method;Ljava/lang/Class;)Ljava/beans/PropertyDescriptor; at...

Spring MongoRepository is updating or upserting instead of inserting

java,spring,mongodb,spring-data
I'm using a : org.springframework.data.mongodb.repository.MongoRepository I start with an empty DB and create an object with _id = 1234 for example, and set some other String field to hello for example, and then do: repository.save(object); All is well, it saves the document in MondoDB. I create a NEW object, set...

Inherited properties of related entities are not visible in spring-data-neo4j-rest

spring,neo4j,spring-data,spring-data-neo4j
I have three NodeEntities A, B, and C. A is the parent of B and C. C has a property of type Set. For all three entities I have also a PagingAndSortingRepository. The Spring Boot application is set up as in the example https://spring.io/guides/gs/accessing-neo4j-data-rest/. Now there is a strange thing:...

Search MongoDB Array of Objects where property has same value for more than 1 array element

arrays,mongodb,spring-data,mongodb-query,spring-mongo
I have a Mongo Collection of Products with a Categories field that is an array of objects. { "_id" : ObjectId("XXX"), "title" : "Cool Product", "details" : "Some Details", "categories" : [ { "name" : "Cat1", "isPrimary" : true }, { "isPrimary" : true, "name" : "Cat2" }, { "name"...

Spring repository auto casts entities with different class types

java,spring,mongodb,spring-data
I'm using MongoRepository interface to extend my custom repositories for different entities. Now I faced with problem, let's assume an example: I have 2 entities: @Document(collection = "person") public class Employee { private String position; } and @Document(collection = "person") public class Manager { private String major; } repositories for...

Saving entity in repository does not work SPRING

java,spring,hibernate,repository,spring-data
I'm trying to save entity in repository but it does not work at all. Repository is Autowired and in runtime I use saveAndFlush to save entity. I'm using PostgreSQL. Above test methods I added comments with explanation what is going on. I expected that method saveAndFlush should work but it...

How to configure Auditing via Java Config in Spring Data (and Spring Data Rest)?

spring-data,spring-data-jpa,spring-data-rest
I am trying to use Spring Data's auditing capabilities (in combination with Spring Boot and Spring Data Rest), but the audit fields are not being set on save. All saves result in a constraint exception from trying to save a null "Created By." According to the spring data docs, I...

Spring-data and Spring-security integration

spring,spring-security,integration,spring-data
The document said by introducing a bean of type SecurityEvaluationContextExtension then it will make available all the commons built-in security expressions like 'principal', 'hasRole', etc. The example shows a simple integration using 'principal' in the @Query @Query("select m from Message m where m.to.id = ?#{ principal?.id }") Now what if...

spring boot switching from in-memory database to persistent database

intellij-idea,spring-boot,spring-data
I have developed my web-application using spring-boot and spring-data-jpa and and in-memory database, and I have a couple questions: how can i now switch to a persistent, let's say, MySQL database? What do I have to change in my configuration? Can spring-boot set a database up for me with a...

Usage of ClassTypeInformation.from(..) inside MappingMongoConverter introduces much thread contention

spring-data,spring-data-mongodb,spring-mongodb
I am writing an application which is storing a lot of objects into MongoDB via Spring Data's MongoTemplate. In order to avoid synchronization, I am creating a separate MongoTemplate for each thread. In fact, each thread get's it's own just about everything to avoid synchronization. The application processes events generated...

Create a Dynamic Query in Spring

spring,spring-mvc,jpa,spring-data
I have been using the standard JPA implementation for a while and had no problems creating dynamic queries resulting from algorithms to search for users in a database. However, we are moving to the Spring Framework (an older version - 3.2, unfortunately) and I simply cannot figure out how to...

JPA - how to prevent an unnecessary join while querying many to many relationships

java,hibernate,jpa,pagination,spring-data
I have entities Product and Category that are joined with a simple many to many relationship. I want to get a paginated list of products filtered by a single category. I'm trying to write a Spring Data JPA automatic method or a JPQL query method that would produce the SQL...

Using @SpringApplicationConfiguration in test throws Exception?

java,spring,spring-boot,spring-data,spring-test
I am trying to execute DAO tests, so i want Spring Boot to build the implementations, so i have this test: @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = FakeServiceRunner.class) public class ClientDAOTests { @Autowired private ClientDAO dao; @Test public void testFindAllClients() { .... Page<Client> clients = this.dao.findAll(new PageRequest(0, 30, null)); // Asserts.. } }...

Passing parameter into Cypher query node_auto_index

neo4j,cypher,spring-data
I'm trying to pass a parameter into the Cypher query node_auto_index without any luck. DecisionRepository.class: @Query("START d=node:node_auto_index(':text') MATCH (d:Decision) RETURN d") List<Decision> searchDecisions(String text); Usage: List<Decision> searchDecisions = decisionRepository.searchDecisions("name:aDbma~ OR name:mosyl~"); Is it possible and if so where I'm wrong ?...

Get embedded object from entity by entity id using Spring Data

java,hibernate,jpa,java-8,spring-data
I have an entity Applicant which contains @Embedded Name object (firstName, lastName etc.). I would like to get only the embedded object from database by applicant id using Spring Data. I'm trying like this: public interface ApplicantRepository extends Repository<Applicant, UUID> { Optional<Name> findNameById(final UUID applicantId); } but it returns the...

Segregating the read-only and read-write in Spring/J2EE Apps

mysql,jpa,design-patterns,architecture,spring-data
We using Spring, Spring-Data and JPA in our project. For production servers, we would like to setup database cluster such that all read queries are directed to one server and all write queries are directed to another server. This obviously will require some changes in the way the DAOs are...

Save LocaTime via SpringData to MongoDB

mongodb,spring-data,jodatime
I try to save a LocalTime (joda) field to the MongoDB with SpringData using spring-boot-starter-parent (org.springframework.boot 1.2.3.RELEASE) and get a StackOverflowError. The StackOverflowError is in BeanWrapper in the method public <S> S getProperty(PersistentProperty<?> property, Class<? extends S> type) Stacktrace: [email protected] daemon, prio=5, in group 'main', status: 'RUNNING' at org.springframework.data.mapping.model.BeanWrapper.getProperty(BeanWrapper.java:120) at...

Spring mongodb criteria

java,spring,mongodb,spring-data
I m using Spring Data with Mongodb and I m facing a problem. I cant execute my criteria query in my repository with this : @Query("{'name':/.*?0.*/}") public List<DirectoryEntity> findByName(String name); What is the good way of make it work ? I need simple criteria, the name contains param. What is...

Spring Data JPA Transaction - No Transaction in progress - Spring Data Neo4j

spring,spring-boot,spring-data,spring-data-jpa,spring-transactions
I think i'm missing something obvious. Iam trying to make a entity persist into a database via a JUnit Test case, however it doesnt seem to be persisting due to no active transaction. Configuration: @Configuration @EnableTransactionManagement public class TransactionConfig { @Inject private EntityManagerFactory entityMangerFactory; @Bean public JpaTransactionManager transactionManager(){ return new...

Unknown column 'categories1_.category' in 'field list'

spring,hibernate,jpa-2.0,spring-data,spring-data-jpa
I have the following model. Employee.Java @Entity public class Employee { @Id @GeneratedValue(strategy=GenerationType.AUTO) private int id; @Column(name="firstName") private String firstName; @Column(name="lastName") private String lastName; @Column(name = "category") @Enumerated(EnumType.STRING) @ElementCollection(fetch = FetchType.LAZY) @CollectionTable(name = "myobject_categories", joinColumns = @JoinColumn(name = "myobject_id")) private Set<Category> categories; } Category is an Enum as follows. public...

Self referencing @OneToMany

jpa,spring-data,datanucleus
I have the following class @Entity public class Comment extends Base { @ManyToOne(cascade = CascadeType.ALL, fetch = FetchType.EAGER) private Comment inReplyTo; @OneToMany(mappedBy = "inReplyTo", cascade = CascadeType.ALL, fetch = FetchType.EAGER) private Collection<Comment> replies; public Comment() { } public Collection<Comment> getReplies() { return replies; } public void setReplies(Collection<Comment> comments) { this.replies...

Implementation of hashCode in PrimaryKeyClass of spring-data-cassandra

java,spring,cassandra,spring-data,spring-data-cassandra
I am using spring-data-cassandra and have a table such that its primary key is ((int_col1,int_col2),bigint_col1,bigint_col2). int_col1&int_col2 are the partition keys bigint_col1 & bigint_col2 are the cluster keys. How important is it to implement hashcode & equals method for my class. What should be the hashcode implementation of my above @PrimaryKeyClass...

Spring store data in jdbcTemlate(h2 db) permanently

spring-data,spring-jdbc,jdbctemplate
I am starting to learn Spring and faced with some issues regarding spring-jdbc. First, I tried run the example from this: https://spring.io/guides/gs/relational-data-access/ and it worked. Then, I commented lines with droping and creating new tables(http://pastebin.com/zcJHsL1P), in order to not override data, but just get it from db and show it....

How do Spring Data repositories know where your database is located?

spring,mongodb,spring-data,spring-data-mongodb,spring-gs-guides
I have been looking at the Spring Framework guides (specifically the database access guide), and I am having trouble comprehending parts of them. In the MongoDB guide, it goes over creating a model, creating a MongoRepository, and interacting with the data. But nowhere does it cover how the application knows...

How is the RowMapper Method working from Spring 1.2?

java,spring,jdbc,spring-data,spring-jdbc
I am doing a documentation of a Spring 1.2 implemented giant application for my company which wasn't documented while being coded around 8 years ago. Right now I am on one of the java classes and stuck on a particular method on how it is actually working, specially the part...

JPA/Spring returning JSON from 2 MySQL tables as nested Objects

java,mysql,json,jpa,spring-data
JPA/Spring returning JSON from 2 MySQL tables as nested Objects I'm brand new to JPA/Spring so if you could atleast point me in the right direction it would be extremely helpful!! Cheers! Here is what I get: [{"conId":1,"phone1":"test","tblPeople": {"pepId":1,"pepAccountIdFk":1,"firstName":"TestFirst","lastName":"Last","title":"Title","notes":"Notes"}}] What I want is: [{"conId":1,"phone1":"test", "pepId":1,"pepAccountIdFk":1,"firstName":"TestFirst","lastName":"Last","title":"Title","notes":"Notes"}] Java Class tblPeopleContactInfo: package...

spring-data-couchbase error while finding all documents with PageRequest

java,spring-data,spring-data-couchbase
Using Spring Data Couchbase I created a very simple repository public interface UserDao extends PagingAndSortingRepository<User, String> This should allow me to execute a paged findAll as follows: Page<User> userResult = repo.findAll(new PageRequest(1, 20)); However the the following is always thrown: Exception in thread "main" java.lang.IllegalStateException: Unknown query param: Page request...

Spring Data JPA and Exists query

java,hibernate,jpa,spring-data,jpql
I'm using Spring Data JPA (with Hibernate as my JPA provider) and want to define an exists method with a HQL query attached: public interface MyEntityRepository extends CrudRepository<MyEntity, String> { @Query("select count(e) from MyEntity e where ...") public boolean existsIfBlaBla(@Param("id") String id); } When I run this query, I get...

Spring Data Mongodb - obtaining last item on a page

java,pagination,spring-data,spring-data-mongodb
This is my current pagination method on Spring Data MongoDB: @RequestMapping(value="/nextposts", method=RequestMethod.GET) public List getNextPosts(@RequestParam int next) { Pageable pageable = new PageRequest(next, 5, new Sort(new Sort.Order(Direction.DESC, "id"))); page = repo.findAll(pageable); return page.getContent(); } As you can see, I'm obtaining the page as specified by the "next" variable and then...

RestResource: get id of subentity without extra request

java,spring,rest,spring-data,spring-data-rest
I have entities like this: @Entity class MyEntity { Long id; SecondEntity second; ... } @Entity class SecondEntity { Long id; ... } I use @RestResource for rest-API. If I request list of MyEntity I get result like: { "_links": { "self": {"href": "http://localhost:8080/api/MyEntity/1"}, "second": {"href": "http://localhost:8080/api/MyEntity/1/second"} } }, {...

Hibernate delete child when parent is getting updated in same transaction

hibernate,spring-data
I have defined two entities Customer and SalesOrder in my domain model with oneToMany relationship from customer to salesOrder. Below code deletes the sales order: SalesOrder salesOrder = salesOrderRepository.findByOrderNumber(orderNumber); if(null != salesOrder){ Customer customer = salesOrder.getCustomer(); customer.setCurrentCredit(customer.getCurrentCredit() - salesOrder.getTotalPrice()); Iterator<SalesOrder> iter = customer.getSalesOrders().iterator(); while(iter.hasNext()){ SalesOrder order = iter.next();...

Redis Serialization and Deserialization

redis,deserialization,spring-data,serializable,spring-data-redis
I have noticed that some of my serialized objects stored in Redis have problems deserializing. This typically occurs when I make changes to the object class being stored in Redis. I want to understand the problem so that I can have a clear design for a solution. My question is,...

Spring data DBRef lazy loading with REST - 500 server error

java,spring,mongodb,spring-data,spring-data-mongodb
I'm using Spring Data with MongoDB. I have the following object: @Document(collection = "Notification") public class Notification { @Id private String id; @DBRef (lazy=true) private User sender; } When I try to return this object using the following method, I receive a 500 error in my browser console and I...

RelationshipEntity not persisted

java,spring,neo4j,spring-data,spring-data-neo4j
I'm having problems with relation @RelationshipEntity(type = RelTypes.Tag.TAG_ON_OBJECT_EVALUATION) public class TagOnObjectEvaluation { @StartNode private Mashup taggableObject; @EndNode private Tag tag; // Other fields, getters and setters } In both the entities involved (Mashup and Tag), I have this field (with opposite Direction) @RelatedToVia(type = RelTypes.Tag.TAG_ON_OBJECT_EVALUATION, direction = Direction.INCOMING /*Direction.OUTGOING*/) private...

Spring JPA Projection including links

java,spring,jpa,spring-data,spring-data-rest
Given a simple model of Event that has a Set of Booking objects: Event: @Entity public class Event { @Id @GeneratedValue(strategy=GenerationType.AUTO) private Long eventId; private Date start; private Date end; private String title; @OneToMany(mappedBy="event") private Set<Booking> Bookings; protected Event() { // for JPA } // Getters and setters omitted for...

Understand different behaviours of Hibernate/JPA for findAll and findOne

hibernate,jpa,spring-data,spring-data-jpa
I was debugging a performance issue with a findAll method (from a Spring Data JPA Repository) and the problem was the fetch plan that was being used. (Hibernate was performing additional Selects to retrieve the additional entities instead of using a fetch join) My entity has some relations to another...

Dynamic spring data jpa repository query with arbitrary AND clauses

java,spring,spring-data,spring-data-jpa,querydsl
I'm using Spring data jpa repositories, Got a requirement to give search feature with different fields. Entering fields before search is optional.I have 5 fields say EmployeeNumber, Name, Married,Profession and DateOfBirth. Here i need to query only with the given values by user and other fields should be ignored.Ex, Input...

Spring Data Specifications, how to query LIKE for a @OneToMany relationship?

java,spring,jpa,spring-data,spring-data-jpa
I have an entity, called "Client", which contains a List users. public class Client { @OneToMany(fetch = FetchType.EAGER, mappedBy="client") private List<User> users; } I want to write a query which does something like: SELECT * FROM Client client JOIN Users user ON user.client_id = client.client_id WHERE ( user.name LIKE '%name%'...

Spring Data/Spring Boot circular dependency issue?

spring,spring-boot,spring-data,spring-data-jpa
I have a akward issue with a Spring Data JPA repository in a Spring Boot application. I have several repository interfaces which are only used directly via @Services and mockmvc integration tests. The services itself are used in @Controllers and also in Spring Converter classes. Everything was working fine until...

JPQL for a Unidirectional OneToMany

java,hibernate,jpa,spring-data,jpql
I need a jpql query for my Spring repository interface method, to retrieve all Posts for a given Semester. @LazyCollection(LazyCollectionOption.FALSE) @OneToMany(cascade = CascadeType.MERGE) @JoinTable ( name = "semester_post", joinColumns = {@JoinColumn(name = "semester_id", referencedColumnName = "id")}, inverseJoinColumns = {@JoinColumn(name = "post_id", referencedColumnName = "id", unique = true)} ) private List<PostEntity<?>>...

How to write a query with conditions such as A And (B Or C) with Spring Data query methods?

spring-data
Based on the Spring Data documentation, it is easy to do conditions such as A Or B. Example: List<Person> findByLastnameOrFirstname(String lastname, String firstname); I wouild like to know how to write a query with conditions A And (B Or C). Something like the following: List<Person> findByEmailAddressAnd(LastnameOrFirstname)(String emailAddress, String lastname, String...

Spring REST Data

maven,spring-boot,spring-data,dependency-management,spring-data-rest
I'm trying to expose Spring REST Data using a demo application found in the documentation: package hello; import java.util.List; import org.springframework.data.mongodb.repository.MongoRepository; import org.springframework.data.repository.query.Param; import org.springframework.data.rest.core.annotation.RepositoryRestResource; @RepositoryRestResource(collectionResourceRel = "people", path = "people") public interface PersonRepository extends MongoRepository<Person, String> { List<Person> findByLastName(@Param("name")...

Mongotemplate - Query ObjectId according to greater than (gt) or less than (lt) operator

mongodb,spring-data,objectid
When I type this into my consol, it works: db.posts.find({"_id": {$lt:ObjectId("55732dccf58c555b6d3f1c5a")}}).limit(5).sort({"_id":-1}) When I use mongotemplate, it doesn't work and returns a blank array: @RequestMapping(value="/next", method=RequestMethod.GET) public List getNextPost(@RequestParam String next) { Query query = new Query(); query.addCriteria(Criteria.where("_id").lt("55732dccf58c555b6d3f1c5a")); List<Posts> posts = template.find(query, Posts.class); return posts; } I tried it with this...

Spring boot don't let me create a repository without database

spring,spring-boot,spring-data
I've created a project on Spring Boot. I've two providers extending the same Abstract provider, and i load on startup the one i'm interested in via Spring Profile. One of the providers is based on JPA, the other have his interface implemented where i make calls to webservices. This is...

Is it possible to have “connection preparation” with Spring / JPA persistency

java,spring,jpa,spring-data
I have a Spring CrudRepository that is just an interface, and I have a persistence context class where I have defined my data source: @Configuration @EnableTransactionManagement public class PersistenceContext { @Bean(name="dataSource", destroyMethod = "close") public DataSource dataSource() throws SQLException { return ... public interface DataRepository extends CrudRepository<Data, Long> { Data...

how can i parameterize datasource properties on Spring 4?

java,spring,spring-mvc,spring-data,spring-jpa
I am using Spring 4.16. I want to parameterize my persistence data. This is my config right now: @Configuration @EnableTransactionManagement public class PersistenceConfiguration { @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { LocalContainerEntityManagerFactoryBean entityManager = new LocalContainerEntityManagerFactoryBean(); entityManager.setDataSource(this.dataSource()); entityManager.setPackagesToScan(new String[] {"com.example.movies.domain"}); JpaVendorAdapter vendorAdapter = new...

Spring Data MongoDB Credentials

java,spring,mongodb,openshift,spring-data
With Spring Data, I am trying to get a Mongo object that has username and password credentials. I need to set this programmatically, rather than with XML All of the examples that I have found use the deprecated system. I am looking for the current way to do this. Here...

Obtaining string query (JSON) from SearchQuery object

elasticsearch,spring-data,spring-data-elasticsearch
For debugging purposes, I need to know what query spring-data-elasticsearch is sending to the ElasticSearch cluster. I have tried to call the toString method on the SearchQuery object, and doesn't return what I need. What I am doing in Java (using spring-data-elasticsearch) is: private FilterBuilder getFilterBuilder(String id) { return orFilter(...

Spring Boot & Security with AngularJS Login page

java,angularjs,spring-security,spring-boot,spring-data
I'm following this tutorial/example of Dave Syer in order to implement a custom AngularJS login page with Spring Security. And the example works fine locally: https://github.com/dsyer/spring-security-angular/tree/master/single However, when I try to implement this myself, changing some things in a way i would like them to be, I'm not able to...

Why does Spring data's query builder not work for limiting query results?

java,spring-data
Context I have defined a repository interface (JpaRepository) and i want to limit the query results (documentation). I need the first result(s) and i prefer not to use pagination for limiting query size. I would rather use the query builder mechanism built into Spring Data repository infrastructure for constraining queries...

Change default sort order for Spring Data findAll() method

spring,jpa,spring-data,spring-data-jpa
I'm using Spring Data JPA and I wonder if it is possible to change the default sort order for a entity being used by the Spring Data findAll() method?

Spring config xml isn't valid after adding spring-data-jpa schema references

java,xml,spring,spring-data,spring-data-jpa
I have the following Exception while starting the spring context: java.lang.Exception: java.lang.IllegalStateException: ContainerBase.addChild: start: org.apache.catalina.LifecycleException: org.apache.catalina.LifecycleException: org.xml.sax.SAXParseException; systemId: http://www.springframework.org/schema/data/jpa/; lineNumber: 1; columnNumber: 55; White spaces are required between publicId and systemId. Before I added the spring-data-jpa to the spring config.xml everything worked fine. Why isn't the xml not valid anymore?...

Spring Boot: H2 database not saved to file

spring,spring-boot,spring-data,h2
I'm trying to persist an H2 in-memory DB to a file with Spring Boot to reuse the data in there. Unfortunately, the way to specify the datasource url like spring.datasource.url = jdbc:h2:file:~/WeatherDB;FILE_LOCK=FS (complete application.properties) doesn't work for me. I can't find a file generated by H2 anywhere on my hard...

adding spring-data-rest ontop of spring-data-jpa

spring,spring-boot,spring-data,spring-data-jpa,spring-data-rest
i created a maven project, and added all dependencies i need. i have some repositories using the spring-data-jpa, and i added some integration tests. now i need to add ontop of it spring-data-rest, if i understand it is based on springmvc. but all examples i found, i need to add...

Criteria in spring data

spring,hibernate,spring-data
I'm working on a web application using angular js, spring mvc and spring jpa data. I'm wondering if there is something similar to criteria and detachedcriteria(hibernate) to build advanced queries with spring jpa data.

Why is an excerpt projection not applied automatically for a Spring Data REST item resource?

spring,spring-mvc,spring-data,spring-data-rest
I made a projection which should expose nested entities: @Projection(name = "inlineBusiness", types = { UserModel.class }) public interface InlineBusinessUserModelProjection { String getUsername(); String getFirstName(); String getLastName(); Date getBirthdate(); String getEmail(); BusinessModel getBusiness(); } And the service repository: @RepositoryRestResource(collectionResourceRel = "users", path = "users", excerptProjection = InlineBusinessUserModelProjection.class) public interface UserRepository...

Spring Data Hibernate + Pageable: Returns empty results

java,spring,hibernate,spring-data
I am using Spring Data repositories without any problems. When I tried to add Paging (using the Pageable interface) it worked OK. However, when the returned result set is less then the Page size, the result is empty List. The following is my PageRequest. The default values for index and...

Mixing JdbcTemplate and raw JDBC

spring,spring-boot,spring-data,spring-jdbc
I am experiencing some strange behaviour which I can't easily explain. The following code runs fine: try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { statement.executeUpdate("DELETE FROM product"); } catch (Exception ex) { throw new RuntimeException(ex); } try (Connection connection = dataSource.getConnection(); Statement statement = connection.createStatement()) { statement.executeUpdate("INSERT INTO...

How should I use @Cacheable on spring data repositories

java,spring-boot,spring-data
When using, for example, MongoRepository there are some methods which I would like to mark as @Cacheable such as insert(entity) or findOne(id). Since its spring repository and not mind, how should I use @Cacheable on those methods?

Spring Boot custom implementations for Spring Data repositories with MappedSuperclass and subclasses

java,spring,spring-boot,spring-data,spring-data-jpa
Here is a simplified working code. There are a mapped superclass and two its subclasses (in real life superclass of course contains more fields) Animal.java @MappedSuperclass @lombok.NoArgsConstructor @lombok.RequiredArgsConstructor public abstract class Animal { @Id @GeneratedValue(strategy = GenerationType.AUTO) @lombok.Getter private Long id; @lombok.Getter @lombok.NonNull private String name; } Cat.java @Entity @Table...

JPA 2 multiple @CollectionTable in Entity causing unrelated outer joins

java,spring,hibernate,jpa,spring-data
Hi I have the following JPA entity class. It has two @CollectionTable mapping for Groups and Contact Id's. I am interesting in getting back a list of unique contact id's from the contact_details table and having a reference to them in my Users class variable contacts below: @Entity @Table(name =...

spring data jpa auditing failure for many to many mapping

spring-data
Hi I am getting hard time in saving one of the manytomany mapping entity due to an auditing issue. We are using spring data with base entity to manage the audit information. It all works fine but for one manytomany mapping I am getting sql exception Field 'createdon' doesn't have...

Spring Data-Couchbase Client Configuration with moxi Client Possible?

spring-data,couchbase,spring-data-couchbase
We are running client-side MOXI on the same machine as our Tomcat servers, with MOXI currently talking to a cluster of membase servers on 3 different machines. The java clients talk to MOXI using spymemcached communicating to MOXI through data port 11211. We are going to migrate to Couchbase now...

Strange behaviour from Hibernate with OneToMany relationship

hibernate,spring-data
My code is involving 3 entities: @Entity public class Data implements Serializable { ... @OneToMany(cascade={CascadeType.ALL},fetch = FetchType.EAGER, targetEntity = Bit.class,mappedBy = "data") private Collection<Bit> bit; @OneToMany(cascade={CascadeType.ALL},fetch = FetchType.EAGER, targetEntity = Linked.class,mappedBy = "data") private Collection<Linked> linked; } @Entity public class Linked implements Serializable { ... @EmbeddedId private LinkIdPK id; @ManyToOne(optional=true,fetch...

Mongodb java springdata unable to get result for date equals query

java,mongodb,spring-data
I have inserted some test records to the mongo database with following structure. { "_id" : ObjectId("5563fe96a826638b48c77c26"), "date" : ISODate("2015-05-02T07:00:00.326Z"), "createdDate" : ISODate("2015-05-26T05:03:18.899Z"), "updatedDate" : ISODate("2015-05-26T05:03:18.899Z"), "status" : 0 } Now when I try to query it using Spring data or via MongoDB I am always getting returned result list...

Gradle fails to resolve spring dependency

maven,gradle,spring-data,parent-pom
I am trying to build my project with the following build.gradle file. buildscript { repositories { mavenCentral() } dependencies { classpath('org.springframework.boot:spring-boot-gradle-plugin:1.2.1.RELEASE') } } apply plugin: 'java' apply plugin: 'idea' apply plugin: 'spring-boot' repositories { maven { url 'https://repo.spring.io/milestone' } mavenCentral() } dependencies { compile('org.springframework.boot:spring-boot-starter-web') compile('org.springframework.boot:spring-boot-starter-data-mongodb:1.2.2.RELEASE')...