How to use OrderBy with GreaterThan Spring JPA - java

I want to add in my Repository interface a method which find all the data greater than a long publishdata value and Order it Decreacingly:
I tried this, but it doesn't seems to be working:
#Repository
public interface NoticiaRepository extends CrudRepository<Noticia,Long>{
Noticia findById(long id);
List<Noticia> findByOrderPublishdateGreaterThanDesc(long publishdate);
}

List<Noticia> findByPublishdateGreaterThanOrderByPublishdateDesc(Long publishdate)

Related

What is the best way to use findAll with Pageable in Spring?

I have employee class
#Entity
class Employee {
#Id
Integer id;
String name;
Integer age;
}
and another class EmployeeInfo:
class EmployeeInfo {
Integer id;
String name;
}
Now, I need to build a service to get a paginated list of EmployeeInfo by using findAll(Pageable pageable)
from the repository
#Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
what is the best way to do that? I want to avoid getting the page from findAll and create a new object of EmployeeInfo then adding it to a list in a loop
You can utilize spring-data-jpa projections.
There are many ways to use them (open/closed projections, class or interface based, etc.), but since you already have a EmployeeInfo class, it can be achieved by defining a new method in your repository:
#Repository
public interface EmployeeRepository extends JpaRepository<Employee, Long> {
Page<EmployeeInfo> getAllBy(Pageable pageable);
}
Note that your projection DTO class properties must exactly match properties in the aggregate root (entity class).
Also reference documentation suggest to define .equals() and .hashcode() methods.
Other methods can be found in the official documentation.

Java spring JPA Repository Entity is not deleted

In my code, I fetch an entity and try to delete it, using the interface ProductRepository which extends JpaRepository:
#Repository
public interface ProductRepository extends JpaRepository<Product, Long> {}
Code, and System.out.println() output from code:
#PostMapping("/admin/product/delete")
public String deleteProduct(
#RequestParam String productId
){
Long id = Long.parseLong(productId);
System.out.println("long id from deleteProduct: " + id);
productService.deleteProductById(id);
return "redirect:/product";
}
sysout:
long id from deleteProduct: 38
Service method deleteProductById():
public void deleteProductById(long productId){
Product product = productRepository.getOne(productId);
System.out.println("Product:\n" + product);
productRepository.delete(product);}
sysout from deleteProductById:
Product: Product{id=38, productName='zip',
producer=lightmarket.mvc.model.domain.Producer#182a383}
But the entity is not deleted...
I must point out that all other CRUD operations work. Create, Update, Read - all are alright! Only 'delete' is not working.
JpaRepository extends CrudRepository, so you can use:
Crudrepository.deleteById() which in the case of your generic types, takes a long (See the documentation at ).
So, in your service, you would have something like:
#Service
public class ProductService {
#Autowired
ProductRepository repo;
public void deleteProductById(Long id) {
System.out.println("Deleting product with id: " + id);
// USE deleteById(Long id) and directly pass the id
// Defined in CrudRepository
repo.deleteById(id);
// DON'T use delete() and pass a product
//repo.delete(product);
}
}
Then your controller calls service.deleteProductById() from the service like normal
See documentation: https://docs.spring.io/spring-data/commons/docs/current/api/org/springframework/data/repository/CrudRepository.html?is-external=true#deleteById-ID-
Maybe there is something wrong with your equals and hashcode of the Product class and the object you load from database is not the same you are trying to delete.
A better way for deleting a product by id would be using the id instead of the product object.
You could replace
productRepository.delete(product);
with
productRepository.delete(productId);
where productId is of type Long.
This would also avoid the additional query.

How to find letter in all columns with Spring Data JpaRepository

Here is my Repository
public interface NoteRepository extends JpaRepository<Note,Long> {
List<Note> findByContentContains(String content);
and my method in class NoteController which return me words with "e" in column Content
#GetMapping("/notesletter")
public List<String> getLetters(){
return noteRepository.findByContentContains("e")
.stream()
.map(note -> note.getContent())
.collect(Collectors.toList());
}
Please, help me to find a method which will return every words with letter "e",for example, from all columns.
I am working with Postman
Of course you can you native queries
#Query("select u from Note u where u.COL1 = ?1 and u.COL2 = ?1")
List<Note> findByContentContains(String content)
or use jpa feature as given below, Note findByLastnameOrFirstnameStartingWith is mentioned to understand easily, so replace your firstname,lastname as colu1name,col2name respectively.Refer here for more jpa method conventions`
public interface NoteRepository extends JpaRepository<Note,Long> {
List<Note> findByLastnameOrFirstnameStartingWith(String param1,String param2)
static List<Note> findByContentContains(String content){
findByLastnameOrFirstnameStartingWith(content,content);
}
}
You can try the or operation in the method name like below.
Or findByLastnameOrFirstname
https://docs.spring.io/spring-data/jpa/docs/1.5.0.RELEASE/reference/html/jpa.repositories.html
Other approaches are possible too.
If you know the native query or JPQL equivalent that returns the results checking all the columns of the entity.
Use of
#Query above the method in repository interface can take a JPQL or native query.
#NamedQuery annotation is also available if you know the query. This annotation to be used over the Entity class, name attribute is used to specify the accessing method name which returns the data, this can be used in repository interface.

JpaRepository query "in" (Hibernate)

I have a JpaRepository:
public interface UserRepository extends JpaRepository<User, Long> {
List<User> getByFirstName(String firstName);
}
But how to search in several values? I need something like this:
List<User> getByFirstNames(List<String> firstNames);
You need to change the signature of the method to:
List<User> getByFirstNameIn(List<String> firstNames);
Take a look at all the supported method of Spring Data JPA on their reference.
The following code is working,
Code in Repository,
List<Shop> findByNameIn(List<String> names);
Code in controller,
List<String> names=new ArrayList<String>();
names.add("gunaa");
names.add("pranav");
List<Shop> sl=shopService.findByNameIn(names);
for(Shop s:sl)
System.out.println(s.getName());

How to delete items in MongoRepository using query annotation?

I'm using Spring Data with MongoDB using MongoRepository.
I was wondering if it is possible do a delete by filter using query annotation. I have been looking here and google and I cannot find any documentation.
#Query(value="{'id' : $0}", delete = true)
public Person deleteById (String id);
Maybe you can use repository delete queries. Here is an example from documentation:
public interface PersonRepository extends MongoRepository<Person, String> {
List <Person> deleteByLastname(String lastname);
Long deletePersonByLastname(String lastname);
}
Using return type List will retrieve and return all matching documents before actually deleting them. A numeric return type directly removes the matching documents returning the total number of documents removed.
Try this, it's work for me.
#Repository
public interface DepartmentDao extends MongoRepository<Department, String> {
#DeleteQuery
void deleteByDepartment(String department);
}
OR
#Query(value="{'_id' : ?0}", delete = true)
public void deleteById(String id);
Unfortunately spring data doesn't provides any method to delete documents based on a query. And the #Query annotation is only for find documents.
What you could do is implement a custom repository that deletes documents based on what you want.
How to delete a list of ids in the query ?
#Query(value="{idList : $0}", delete = true)
Repository:
#Component
public interface SomeRepository extends MongoRepository<SomeObject, String> {
#Query("{ '_id' : ?0 }")
SomeObject findById(String _id);
}
Code in some class:
#Autowired
private SomeRepository pRepo;
public void delete(String id) {
pRepo.delete(pRepo.findById(id));
}
#Repository
public interface DepartmentDao extends MongoRepository<Department, String> {
void deleteByDepartment(String department);
}
is clean and shorter.

Categories

Resources