How to update particular column of all rows using spring data mongo - spring-boot

I have Tenant table where only one tenant should be active at a time.
To activate a tenant i am using following code. Is there a better way to change particular column of all rows using spring data mongo.
tenantRepository.save(tenantRepository.findAll().stream().map(t -> {
t.setActive(false);
return t;
}).collect(Collectors.toList()));
tenant.setActive(true);
tenantRepository.save(tenant);

If you want to update specific column(s) in Spring data Mongo, simply define your custom repository interface and its implementation like:
Define Custom Interface
public interface TenantRepositoryCustom {
Integer updateStatus(List<String> id, TenantStatus status, Date date);
}
Implement your Custom Interface
#Repository
public class TenantRepositoryCustomImpl implements TenantRepositoryCustom{
#Autowired
MongoTemplate template;
#Override
Integer updateStatus(List<String> id, TenantStatus status, Date date) {
WriteResult result = template.updateMulti(new Query(Criteria.where("id").in(ids)),
new Update().set("status", status).set("sentTime", date), Tenant.class);
return result.getN();
}
Extends you Default Tenant Repository from Custom Repository:
public interface TenantRepository extends MongoRepository<Tenant, String>, TenantRepositoryCustom{
}
Use Custom repository in Service
#Service
public class TenantService{
#Autowired
TenantRepository repo;
public void updateList(){
//repo.updateStatus(...)
}
}
Note:
This is less error prone as compared to using #Query, as here you will have to just specify column's names and values instead of complete query.

Related

Find All based on the flag value in Spring Data JPA

I want to fetch all the records based on the flag value. Flag value can be either 'A' for Active or 'I' for Inactive.
I want to fetch both Active and Inactive records and put them in some kind of List or Map.
These are my repository and entity class:
#Repository
public interface StatusRepository extends JpaRepository<StatusEntity,Long>{
}
public class StatusEntity{
#Id
#Column(name="id_status")
private Long idStatus;
#Column(name="name")
private String name;
#Column(name="status_flg")
private String statusFlg;
}
I am able to fetch all the records using statusRepository.findAll(). I was wondering if there is something like statusRepository.findAllByStatusFlg(String flag) or statusRepository.findByStatusFlg(String flag)?
Is there any way to fetch all the records by specifying where condition on certain columns?
P.S. I am using spring-boot-starter-data-jpa 2.3.2.RELEASE
You should make yourself familiar with the basics of spring data. As you thought, you can define a query method in your StatusRepository that fetches your StatusEntitys according to your needs.
#Repository
public interface StatusRepository extends JpaRepository<StatusEntity,Long>{
List<StatusEntity> findByStatusFlg(String flag);
}

Spring Data JPA - findBy mapped object

In my legacy application, I have a country table, state table and a mapping table for country and state with few additional columns.
I have created an entity class like this.
class CountryStateMapping {
#Id
private long id;
private Long countryId;
#OneToOne
#JoinColumn(name="state_id")
private State state;
//getters seters
}
My repository.
public interface CountryStateMapping extends JpaRepository<CountryStateMapping, Long>{
Optional<CountryStateMapping> findByStateId(long stateId);
Optional<CountryStateMapping> findByState(State state);
}
I would like to check if the state exists in the mapping table. Both of the below approaches do not work.
countryStateMapping.findByStateId(long stateId)
countryStateMapping.findByState(State state)
What is the right way?
Its not the correct way i feel.The correct way for doing this will be
public interface CountryStateMappingRepository extends JpaRepository<CountryStateMapping, Long> {
Optional<CountryStateMapping> findByStateId(long stateId);
#Query("select s.something from State s" )
Optional<CountryStateMapping> findByState(State state);
}
This implies two things
By extending JpaRepository we get a bunch of generic CRUD methods to create, update, delete, and find
2.It allows Spring to scan the classpath for this interface and create a Spring bean for it.
Also you need some configuration.For that you need to create a configuration class to be used with your data source.You can find many examples to do the same and one such is https://www.baeldung.com/the-persistence-layer-with-spring-data-jpa.
You can also use custom queries and simple queries using the #Query annotation.
Thanks
Try with an underscore for id like below;
public interface CountryStateMapping<CountryStateMapping, Long>{
Optional<CountryStateMapping> findByState_Id(long stateId);
Optional<CountryStateMapping> findByState(State state);
}

How to get the specific property value from .properties file in Spring Data Repository interface method #Query

I am able to get the property value in Spring classes like below:
#Value("${database.name}")
private String databaseName;
I have to execute a native query by joining different tables which are in different databases.
#Query(value="select t1.* FROM db1.table1 t1 INNER JOIN db2.table2 t2 ON t2.t1_id1 = t1.id1")
Instead of hard coding database names i.e., db1 and db2 here, I have to get them from properties file.
how to get the property value inside the #Query annotation in Spring Data JPA Repository ?
I don't know if it is possible, but if not, you can consider this approach:
Instead of using properties in Repository's #Query directly, you can use params in the query but when you call the actual method - you can provide values from .properties.
Imagine you have simple repository:
public interface UserRepository extends JpaRepository<User, Long> {
// query with param
#Query("select u from User u where u.lastname = :lastname")
User findByLastname(#Param("lastname") String lastname);
}
Then, let's say you have some Service or Controller where you need to use your Repository - you can inject properties there and pass them to your method:
#Service
public class UserService {
// this comes from .properties
#Value("${user.lastName}")
private String userLastName;
#Autowired
private UserRepository userRepository;
public User getUser() {
// you pass it as param to the repo method which
// injects it into query
return userRepository.findByLastname(userLastName);
}
}
This is just an example. But I believe it may be useful.
Happy hacking :)

How to paginate a list of object (not mapped domain object) using custom pagination with spring data

I have a repository called BananaRepositoryImpl that contains a function that return a list of BananaDTO ( the legacy code can't return the mapped entity ( Banana.java ),it's a constraint and I can't change this behavior :( )
public class BananaRepositoryImpl implements BananaRepository{
#Autowired
EntityManager em;
public List<BananaDTO> findAllBananes(){
//logic to get list of bananasDTO object types using Query query = em.createQuery(JPQL_QUERY_HERE);
}
}
Knowing that the BananaDTO object is a DTO for Banana.java class which looks like this :
#Data
#Entity
public class Banana{
private Long id;
private Double price;
private Double weight;
}
What I should do is to implement pagination over the findAllBananes() method so that I can return a Page using spring Data ( or another approach ).
Assuming the attributes of the BananaDTO is a subset of the Banana entities attributes you can use class-based projection support of Spring Data JPA, i.e. you just add a Pageable as a parameter to your method and return a Page<BananaDTO>:
interface BananaRepository extends CrudRepository<Banana, Long> {
Page<BananaDTO> findAllBananes(Pageable page)
}

auditing filelds in spring data

I'm beginner in java programming. And I try to write simple stand alone application with spring data. To basic example which is here http://spring.io/guides/gs/accessing-data-jpa/ I want to add, auditing mechanism which will store previous values for objects. I want in customer entity, on #PreUpdate store old values in another table, but I do not know how.
#Entity
#EntityListeners(AuditingEntityListener.class)
public class Customer implements Serializable {
...
#Transient
private transient Customer savedState;
#PreUpdate
public void onPreUpdate() {
if (!savedState.firstName.equals(this.firstName)) {
log.info(String.format("first name was modified, new value =%s, old value=%s",this.firstName, savedState.firstName ));
}
}
#PostLoad
private void saveState(){
this.savedState = (Customer) SerializationUtils.clone(this); // from apache commons-lang
}

Resources