FAQ Database Discussion Community


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...

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...

How to store an entity together with its relations?

java,spring,jpa,spring-data-jpa
Imagine the following entities: @Entity public class Car { @Id @GeneratedValue private long id; private String manufacturer; private String model; @OneToMany(mappedBy = "car") private Set<Tire> tires = new HashSet<>(); // Getters & setters } @Entity public class Tire { @Id @GeneratedValue private long id; @ManyToOne @JoinColumn(name = "car_id") private Car...

Will Spring JPA repository save() do an update, sometimes !!?

spring,jpa,spring-data-jpa,one-to-one
I've two jpa entities, say A and B. Entity A composes B and has a OneToOne mapping with cascade=MERGE, orphanRemoval=false, etc. The persistence execution is as below Create B as, B b = new B() and set only pre-persistence data, some date info is automatically set when object is saved....

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...

Failed to instantiate Pageable bean

java,spring,spring-mvc,spring-data-jpa
I use Spring 4.1.6.RELEASE and Spring Data Jpa 1.8.0.RELEASE. I have a problem with org.springframework.data.domain.Pageable bean creation. It is used in my controller: @Controller public class ItemsController { @Autowired ProductService itemsService; @RequestMapping(value = "/openItemsPage") public String openItemsPage() { return "items"; } @RequestMapping(value = "/getItems", method = RequestMethod.GET) @ResponseBody public Item[]...

How to write a custom CrudRepository method(@Query) to filter the result in my case

java,mysql,spring,hibernate,spring-data-jpa
I am new to Spring JPA and Repository stuff. I have an Auction class with a bunch of fields in it, and one of the field is category. I want a custom method in CrudRepository to filter the results by Category.name; @XmlRootElement @Entity(name="AUCTION") public class Auction implements Serializable{ private static...

From Spring data JPA Spring Cloud AWS

spring-data-jpa,porting,spring-cloud
I'm at design phase of my project and I have a doubt. I'm modelling my system and I will use Spring Data JPA for persistence layer. Although, there is high chances of cloud deploy. Is it traumatic the portability from Spring Data JPA to Spring Clous AWS (RDS)? I didn't...

Spring Data - Why it's not possible to have paging with native query

java,spring,spring-data-jpa
Let's say we have an entity called MyEntity. It is possible to query pageable results using @Query and with named queries, e.g. @Query(value = "select e from MyEntity e where e.enabled = true") Page<MyEntity> findAllEnabled(Pageable pageable); However, it is not possible to achieve the same with native query, so this...

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?

How to reference the 'normal' spring data repo from a custom implementation?

java,spring-data,spring-data-jpa
I want to extend a JpaRepository with a custom implementation, so i add a MyRepositoryCustom interface and a MyRepositoryImpl class extending this interface. Is there a way to call methods from JpaRepository inside my custom class? Note: This was also asked as a comment on http://stackoverflow.com/a/11881203/40064, but I think it...

Spring Boot extending CrudRepository

java,spring,hibernate,spring-boot,spring-data-jpa
I'm using Hibernate in a Spring Boot app. I'm making a new CrudRepository for all my Model objects, to do basic CRUD tasks. They look like this: @Repository public interface FoobarCrudRepo extends CrudRepository<Foobar, Long> { } But then I always need to do some additional things, like custom search queries...

Vaadin and JPARepository: transaction errors

java,spring-boot,vaadin,spring-data-jpa,vaadin7
I'm having troubles in integrating Vaadin and spring-data (JPARepositories in particular). After following the guidance of Vaadin's team with their last webinar I managed to configure my application using Spring starter (spring boot), adding Vaadin, JPA and a Postgresql database. Using this method was really straightforward and loading entities to...

call stored procedure JPA 2.1 Repository with Spring

java,spring,hibernate,jpa,spring-data-jpa
I'm trying to call a stored procedure in MySQL call: "searchContext". I have tried the solution : here and here But how can I get the EntityManager reference? If I'm using JPA Repositories like this: public interface ActiveContextRepository extends JpaRepository<ActiveContext, Long> { ActiveContext findByIdUser(Integer idUser); } I got null pointer...

Spring MVC: how to get case-insensitive ordering from Pageable

spring,spring-mvc,spring-data-jpa
I am trying to support case-insensitive ordering in my Spring MVC app when users click on the column headings on my web page. When the page is rendered a Thymeleaf extension creates an anchor and the href is the current URL with some parameters supported by Pageable: i.e. page, size...

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...

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...

How to eliminate bogus “Referenced bean … not found” warnings in STS?

eclipse,spring,spring-integration,spring-data-jpa,spring-tool-suite
STS (3.6.1 and others), Spring 4.1.x (latest), Spring Integration 4.1.2 In many Spring projects I work on in Eclipse/STS, we have numerous "Referenced bean not found" warnings. These often refer to internal Spring beans/classes, not legitimate mis-configuration of our own beans. Here's an example from one of our Spring Data...

Spring data rest one to many delete child objects

json,spring,hibernate,spring-data-jpa,spring-data-rest
I have a one to many relationship between Team and Player, I am able to create a Team with the following JSON { "id": 1, "name": "MyTeam5", "players": [ { "name": "player5" }, { "name":"player10" } ] } However, when I try to delete a child object by removing 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...

Why does STS warn me about non matching parameters?

java,spring,spring-data-jpa,spring-tool-suite
I am using Spring Data Jpa and created a JpaRepository for my User class. The repository works but Spring Tool Suite gives me a warning for one method. Following are examples of my domain model classes and the repository: User: @Entity public class User { @Id @GeneratedValue private long id;...

Spring Data JPA. How to get only a list of IDs from findAll() method

spring,spring-data-jpa,specifications,criteria-api
I have a very complicated model. Entity has a lot relationship and so on. I try to use Spring Data JPA and I prepared a repository. but when I invoke a metod findAll() with specification for the object a have a performance issue because objects are very big. I know...

Nested @Transactional annotation behaviour on Spring Data JPA

java,spring,jpa,spring-data,spring-data-jpa
I have an entity User, a Repository/Dao class UserDao (using Spring Data JPA) and a Service class UserService with a method addUser annotated as @Transactional: @Service public class UserService { @Autowired private UserDao userDao; @Transactional public void addUser() throws Exception { User user = new User(); user.setUsername("aaa"); // Save the...

Spring Data JPA PropertyReferenceException?

spring-data-jpa
I use Spring Data JPA 1.8.0.RELEASE entity Attachment has a property named relate_id, I add a method findByRelate_id(String rid) in Repository, but I got a exception: Caused by: org.springframework.data.mapping.PropertyReferenceException: No property relate found for type Attachment! I realy need my field name is relate_id, not change to relateId, And I...

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...

How to query an entity property by null using spring?

java,spring,spring-data-jpa
I'm using a spring CrudRepository to query database entities. The following should work, but does not. public interface MyEntityRepository<MyEntity> extends CrudRepository<MyEntity, Long> {} @Entity public class MyEntity() { private Long id; private Date reservation; } findByReservationIsNull(new PageRequest(0, 2, new Sort(Direction.DESC, "reservation")))); I'm just getting the following exception as a result....

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...

How to pass jpql to query method in spring jpa?

jpa,spring-data-jpa
Our project involves hundreds of tables/entities, so it's boring to create a single repository for every entity. We want to create a generic repository for common query use which might have a below look: @Repository public interface GenericRepo extends JpaRepository<Ctmpdis,Integer> { public List findByQl(String jpql,Map params); } I want to...

Spring Data JPA OneToOne entity not found

hibernate,spring-boot,spring-data-jpa
I am using Spring-boot 1.2.1, with Spring-Data-JPA and Hibernate. I have a simple OneToOne mapping that saves the entities properly, but when I try and GET the value, it fails because it can't find the child entity. I have an entity: @Entity @Table(name = "OPERATORY") public class Operatory { @Id...

Does the number of APIs on Spring JPA Repository affect start-up time?

java,spring,hibernate,jpa,spring-data-jpa
From experience, I know having too many named queries in Hibernate hbm XML will cause it to start more slowly as it has to pre-compile them all. Question: Will I encounter this same thing if I move my persistence layer to Spring Data JPA Repository and use say, the JpaRespository,...

Nested Transactions theoretically available, but not used

java,hibernate,postgresql,spring-data-jpa
I am trying to prevent multiple object creation in an import service which runs on several server nodes in several threads. My only chance to do so seems to be using a unique constraint on the database, which is the only single point, where everything comes together again. My services...

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...

Optimistic locking not throwing exception when manually setting version field

hibernate,jpa,spring-data-jpa
I have a Spring Boot 1.3.M1 web application using Spring Data JPA. For optimistic locking, I am doing the following: Annotate the version column in the entity: @Version private long version;. I confirmed, by looking at the database table, that this field is incrementing properly. When a user requests an...

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 boot rest service, how to get it to marshal the links as properties?

spring-boot,spring-data-jpa,spring-data-rest,spring-hateoas
first question here so be gentle :) I've got a JPA project which I want to expose as REST. I've done this so far: My entity: @Entity public class SignUpSheet { @Id @GeneratedValue private Long id; @Column private String name; @Column private String description; @Column @Temporal(TemporalType.TIMESTAMP) private Date dateTime; @ManyToOne...

Spring boot: How to configure pagination on a @RepositoryRestResource?

pagination,spring-boot,spring-data-jpa,spring-data-rest
I've looked at both this and this question. But I have still not been able to setup paging for a repository method. Not sure if I'm affected by a bug or simply not writing this correctly. Basically I'm asking if someone could provide an example of how to implement paging...

Unable to resolve a bean for 'javax.persistence.EntityManager'

java,spring,hibernate,jpa,spring-data-jpa
I am trying to implement a application using Spring (+JPA) and Hibernate using anotations. I recentrly added the JPA part. Since then i get: javax.enterprise.inject.UnsatisfiedResolutionException: Unable to resolve a bean for 'javax.persistence.EntityManager' with qualifiers [@javax.enterprise.inject.Default(), @javax.enterprise.inject.Any()]. Error. I also get following warnings: WARN: WELD-000411: Observer method [BackedAnnotatedMethod] protected...

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%'...

JPA entity gets updated on Ubuntu but throws Optimistic Locking Exception on Windows

java,spring,hibernate,jpa,spring-data-jpa
Consider this example in which I have created two JPA entities and used Spring Data JPA repositories to perform simple CRUD - import java.sql.Timestamp; import javax.persistence.Version; @MappedSuperclass public class AbstractValueObject { @Id @GeneratedValue private Long id; @Version @Column(name = "time_stamp") private Timestamp version; public Long getId() { return id; }...

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...

Load JPA repository queries from a property file

java,spring,jpa,spring-data-jpa
I need to load queries in a repository from a property file. For example, here: @Repository public interface StudentRepository extends JpaRepository<Student, Integer> { @Query(value="SELECT * FROM student where year= :le", native=true) public List<Student> getStudentsByLevel(@Param("le") int level); } I need to load the "SELECT * FROM student where year= :le" string...

Spring data JPA and parameters that can be null

java,parameters,null,spring-data-jpa
My understanding is, that with Spring data JPA I cannot have a query method to fetch all rows where a column equals a given non-null method parameter and use the same method to fetch all rows where this column is NULL when the method parameter is null. Is that correct?...

JpaRepository caches newly created object. How to refresh it?

java,jpa,spring-data-jpa
I have a JpaRepository persisting newly created entity in Spring MVC app. This entity looks like this (very simplified): @Entity public class Translation { ..... @Id @GeneratedValue(strategy = GenerationType.AUTO) private long id; @ManyToOne(fetch = FetchType.LAZY) private Version version; .... } and Version entity: @Entity public class Version { @Id @GeneratedValue(strategy...

Multi-Tenancy with Hibernate and Spring Data JPA, how does schema approach work

hibernate,spring-mvc,spring-data-jpa,multi-tenant
i ve read the Hibernate documenation for multitenancy (HERE) several times as well as many other threads. What i have: I have a working application, which serves data (e.g. Products) via rest-service. MYSQL(5.6) -> HIBERNATE(4.3.7 FINAL) -> SPRING DATA JPA (1.7.1) -> SPRING MVC (4.1.4) -> REST (jackson -> json)...

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...

Spring Data Jpa. How to cleaning data from repositories befor run unit test from particular test classes?

spring,unit-testing,jpa,spring-data-jpa
I have problem with unit tests for persistance stuff written in spring data jpa. For particular repositories I have a unit tests to be sure that everything works correctly. Also I have a integration tests. Each tests are passed when I run it for particular test classes. But when i...

Spring data: order by result of condition for each row

spring-data,spring-data-jpa,criteria-api,querydsl
In plain SQL is possible to calculate runtime variables, like IF/SUM for each row, and possible to use it for ordering. My question about possibility of doing things like that in QueryDSL/Criteria API Is it possible or not? I have entity called OrderSummary, with following fields: @Entity @Table(name = "orders")...

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....

Generics error “bound dismatch” using Spring SimpleJpaRepository

java,spring,generics,spring-data-jpa
i am using Spring data and when i try to create a bean of SimpleJpaRepository the compiler marks me an error. This is the code @Bean protected <domainClass, Long> SimpleJpaRepository<domainClass, **Long**> getSimpleJpaRepository(Class domainClass) { return new SimpleJpaRepository<>(domainClass, this.entityManager); } That Long i marked with * has the error: "Bound dismatch:...

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...

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...

How can i externalize datasource configuration with spring-boot?

spring,spring-boot,spring-data-jpa
I'm currently trying to move an existing spring-application to spring-boot and therefore recreate things that worked without boot. I want to configure some properties (like spring.datasource.*) from an external source. specificly a folder with several properties files. I set up a configuration class that creates propertyPlaceholder configurers like this: @Configuration...

Differents application Context in Spring 4

spring,spring-mvc,spring-security,spring-data-jpa
I have a login service in my application implementing UserDetailsService: @Service @Transactional public class LoginService implements UserDetailsService { @Autowired UserService userService; public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException { Assert.notNull(username); UserDetails result = userService.loadUserDetailsByUsername(username); Assert.notNull(result); // WARNING: The following sentences prevent lazy initialisation problems! Assert.notNull(result.getAuthorities());...

Expose @Service methods as Rest endpoints using spring-data-rest

spring,spring-data-jpa,spring-data-rest
I using spring-data-rest in conjunction to spring-data-jpa which exposes all my spring-data-jpa interfaces as REST resources in HAL JSON format. I would like to expose my @Service methods in the same fashion. Is this possible? If not, what is the best way to implement an endpoint that may need to...

@EnableJpaRepositories will not work with JPA Data repository

datasource,spring-boot,spring-data-jpa,spring-jpa
I'm trying to run Spring Boot with two data sources. So far so good, but the problem occurred when I tried to use Spring JPA Data. SimpleJPARepository do not reflect the transaction manager set by @EnableJpaRepositories( basePackages = "cz.data.external", entityManagerFactoryRef = "externalEntityManagerFactory", transactionManagerRef = "externalTransactionManager") It seems it still uses...

Spring data JPA Repository Match All Columns or whole pojo

java,spring,spring-mvc,jpa,spring-data-jpa
I tried to search but didn't find accurate solution. I have Address entity. With every new Address request, first I want to check whether same exist in database or not. My application is for warehouse & there are chances that same address request will come multiple time. Address Entity @Entity...

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...

How to create forms for multiple database tables?

java,spring,jpa,spring-data-jpa
I have an application that processes text files. Depending on the file generator, it searches for some defined texts. Then it executes different actions on the found texts. These actions are stored in a database and correspond to the following entities: @Entity @Table(name = "file_generator") public class FileGenerator { @Id...

Multiple persistence unit throwing error no persistence found error Spring+JPA

spring,hibernate,maven,spring-data-jpa
xml as follows , Its having multiple persistence units , seems only one is like getting recognised. <?xml version="1.0" encoding="UTF-8"?> <persistence version="2.1" xmlns="http://xmlns.jcp.org/xml/ns/persistence" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/persistence http://xmlns.jcp.org/xml/ns/persistence/persistence_2_1.xsd"> <persistence-unit name="webApp-integration">...

JPA annotation for MS SQL Server 2008 R2 IDENTITY column

hibernate,sql-server-2008,jpa,spring-data-jpa
I want to know proper JPA annotation setup to handle MS Server 2008 R2 IDENTITY column. MS Server 2008 R2 (RTM) doesn't support SEQUENCE, but the IDENTITY gives auto increment when I tested by raw sql. However, by JPA I can't make it work by any strategy (IDENTITY, AUTO, TABLE)...

Spring Data JPA; save() auto increment primary key error

mysql,spring,hibernate,jpa,spring-data-jpa
I have a USER table with UserId as primary key, which is int and auto incremented in MySQL. @Id @GeneratedValue @Column(name="USER_ID") private Integer userId; When I run userRepository.save(user); I am getting an error saying: org.springframework.beans.InvalidPropertyException: Invalid property 'userId' of bean class [com.mysite.model.User]: Getter for property 'userId' threw exception; nested exception...

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...

Query boolean with multiple parameters

spring,spring-data-jpa
As stated in the docs(http://docs.spring.io/spring-data/jpa/docs/current/reference/html/),i´m trying to write a query like this: public Page<AnyObject> findByActiveTrueAndUser(Boolean ativo, User user, Pageable pageable); But I´m getting the following error:What could be wrong? Parameter value [true] did not match expected type [.com.User]...

spring MVC use @JsonView on spring-data Page

spring-mvc,jackson,spring-data-jpa,jhipster
I'm using Spring-MVC, Spring-data-jpa, jackson on a Jhipster project. I managed to use the @JsonView annotation on an object and it works well when the method in the rest controller return a type ResponseEntity<List<MyObject>> but I can't make it work when the method return type is ResponseEntity<Page<MyObject>>. I've tried to...

Spring JPA Repository query filter by a relationship table

java,spring,jpa,spring-data,spring-data-jpa
If I have a many-to-many relationship between JPA entities as below, how can I retrieve a list of Person (I am interested in the person attributes) that are employees of a specific company? The relationship between Person and Company is many-to-many. The relationship table Employee has the FK to Person...

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...

Error creating bean 'entityManagerFactory', Nested HibernateException: Unable to get the default Bean Validation factory

java,spring,hibernate,jpa,spring-data-jpa
Many question have been asked on this topic, but none them seems to resolve my issue. I trying a sample project with Maven, Spring, Hibernate and JPA with Mysql 5.5. It is a test desktop app. I don't know, where I am gong wrong. mvn clean install is giving Build...

Spring JPA repositories & JSR310 & native queries

java,spring,spring-data-jpa
It appears that the JSR310 Type Instant is bound as VARBINARY in native queries: @Query(value = "select * from state_entry where timestamp > ?1 and deleted = false limit 10", nativeQuery = true) log output: 2015-01-29 15:41:26.685 TRACE 12250 --- [ XNIO-1 task-1] o.h.type.descriptor.sql.BasicBinder : binding parameter [1] as [VARBINARY]...

Spring boot JPA insert in TABLE with uppercase name

java,mysql,spring,jpa,spring-data-jpa
i have a table entity mapped as : @Entity public class ItemsToRegister implements Serializable{ @Id @Column(name = "ID_ITEM_TO_REGISTER") @GeneratedValue(strategy = GenerationType.AUTO) private int id; ..... When i try to insert new record in database, the table name was translated in lowercase as : items_to_register , but my table name is...

How to force Hibernate JPA to create a join query

hibernate,spring-data-jpa
I am currently working on a spring boot app using Spring Data JPA and Hibernate. My current setup looks like: My TeamMapping Repository: public interface TeamMembershipMapping Repository extends JpaRepository<TeamMembershipMapping, Integer> { public List<TeamMembershipMapping> getByMemberId(Integer memberId, Pageable pageable); } My TeamMembershipMapping Entity: @Entity @Table(name = "teamMembership") public class TeamMembershipMapping { @Id...

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?...

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....

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...

Spring Data JPA querying with transitive sorting

spring,hibernate,spring-data-jpa
I got a problem with simple Spring Data issue. Let's assume we got two entities. public class Request { // all normal stuff @ManyToOne private Document doc; } public class Document { private Long id; private String name; } Simple relation. My question is - is it possible to retrieve...

Why does Spring Data JPA + Hibernate generate incorrect SQL?

java,spring,hibernate,spring-data-jpa
I have two entities with a one-to-many relationship. I want to get all entities that are tied to a set of the other entity. This are my classes: public class Instance { @Id @GeneratedValue private long id; @OneToMany(mappedBy = "instance") private Set<Action> actions = new HashSet<>(); } public class Action...

Spring Data JPA Persisting Entity with a nested Composite Primary Key entity with itself a nested entity which is detached at persist time

java,spring,jpa,spring-data,spring-data-jpa
I have three jpa entities I’m trying to get working together. BoxProfile, BoxProfileItemAssignment and BoxItem all code listed below. BoxProfileItemAssignment has a @EmbeddedId using @MapId to map the composite key. BoxProfile has a set of BoxProfileItemAssignments, the assignments are a BoxItem and quantity value. I want to be able to...

Best way to implement an “reorderable” Entity

java,hibernate,jpa,hibernate-mapping,spring-data-jpa
I have a list of entities shown to the user more or less as a list. Now the user may not only add or delete entities but also reorder the existing ones (with the typical "go up", "go down", "go to the top", "go to the bottom" operations). But what...

Hibernate fails to load JPA 2.1 Converter when loaded with spring-boot and spring-data-jpa

java,hibernate,spring-boot,spring-data-jpa,jpa-2.1
I have a custom converter for UUID to transfer it to a string instead a binary: package de.kaiserpfalzEdv.commons.jee.db; import javax.persistence.AttributeConverter; import javax.persistence.Converter; import java.util.UUID; @Converter(autoApply = true) public class UUIDJPAConverter implements AttributeConverter<UUID, String> { @Override public String convertToDatabaseColumn(UUID attribute) { return attribute.toString(); } @Override public UUID convertToEntityAttribute(String dbData) { return...

How to update an object with another object value in JPQL using Spring JPA

spring,spring-data,jpql,spring-data-jpa,spring-jpa
I'm facing a problem in JPQL. I have two entities like below class Employee{ private Long id; private String name; private Department department; public void setId(Long id){ this.id = id; } public void setName(String name){ this.name = name; } public void setDepartment(Department department){ this.department = department } public Long getId(){...

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'transactionManager' is defined @Spring + JPA

java,spring,hibernate,spring-data-jpa
Following is my applicationContext.xml <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean" id="entityManagerFactory2"> <property name="persistenceXmlLocation" value="classpath*:META-INF/persistence.m3.xml" /> <property name="persistenceUnitName" value="M3tables" /> <property name="packagesToScan" value="com.foo.webapp.integration.model.m3" /> </bean> <bean class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean"...

JSON not returning columns in Spring Data REST

json,spring,rest,spring-data-jpa,spring-data-rest
I am trying out examples for Spring Data REST however the JSON object returned in my testing does not return the column names (which were earlier 'PUT') and just returns the links to the objects. What could be wrong? Scenario: Entity: 'User' @Entity @Data public class User { @Id @GeneratedValue(strategy...

Extend CrudRepository interfaces into base interface

java,interface,spring-data-jpa
How to extend interfaces CrudRepository<T, ID>, MongoRepository<T, ID>, PagingAndSortingRepository<T, ID> into BaseRepository<T, ID>? (if possible) I want to have access methods of three interfaces. I've tried: @SuppressWarnings("rawtypes") public interface BaseRepositoryDao<T, ID> extends CrudRepository, MongoRepository, PagingAndSortingRepository { } How can I archive that? Thanks EDIT: MongoRepository already extends PagingAndSortingRepository ...

Spring Data, JPA @ManyToOne lazy initialization not working

java,spring,hibernate,jpa,spring-data-jpa
I know there are many similar questions about this trouble but nothing works for me. I have @ManyToOne relationship between Aim and User. @ManyToOne(fetch = FetchType.LAZY, optional = false) @JoinColumn(name = "user_id", nullable = false, updatable = false) private User user; and @OneToMany(fetch = FetchType.LAZY, mappedBy = "user") private Collection<Aim>...

How to add some custom behavior to Spring Data Jpa generated query?

spring-data,spring-data-jpa
I am using Spring Data Jpa with a legacy Oracle database. Some of our tables used char instead of varchar2 type. That causes some issue when I am using Spring Data Jpa generated query. For example, I have an entity which named User @Entity @Table(name = "USERS") public class User...