I have a spring project. The following first one is my @Repository class, and th
ID: 3920223 • Letter: I
Question
I have a spring project. The following first one is my @Repository class, and the second one is my @Service class. The third one is the class I define data in database. The question is, I have extends QuerydslPredicateExecutor<T> in repository class, so I can use findAll() with predicate in it, now, how can I create a predicate in the @Service class. Because I'm using repository.findAll() in @Service class so I need to obtain predicates in it. I know there is JPA criteria api that can build predicate, but it's not clear online, can someone give me an example, it doesn't have to be criteria api.
@Repository
public interface InventoryRepository extends MongoRepository<InventoryTable,String>, QuerydslPredicateExecutor<InventoryTable> {
}
@Service
public class InventoryService {
@Autowired
private InventoryRepository InventoryRepository;
}
@Document()
public class InventoryTable {
@Id
String id;
String pid;
String serial_number;
String device_type;
String org_id;
String site_id;
String building_id;
String floor_id;
FloorPosition floor_position;
String model;
String mac;
String firmware_version;
Date claimed_on;
String claimed_by;
List<String> tags;
public InventoryTable() {
}
}
Explanation / Answer
In Spring data mongo, You can use Predicate by using QueryDSL.
What is QueryDSL????
QueryDSL is way to achieve type-safe queries in java which means queries defined using QueryDSL is limited to datatype specified by the user.
Let say, you have a DB object, namely, User, once you define QueryDSL as User it will fetch only object of user datatype only not as string.
It helps us to avoid syntactically invalid queries and makes query definition easy.
Let's take example in your case to use Perdicate using QueryDSL;
in @Service class, You have to define method as(you can also use the Method in your service class)
public List<InventoryTable> getAllInventoryDetails(){
QInventoryTable inventoryTable = new QInventoryTable("inventoryTable");
Predicate predicate = inventoryTable.pid.eq("ID00001");
List<InventoryTable> results = InventoryRepository.findAll(predicate);
return results;
}
Here , QInventoryTable is a class that is generated which is a Predicate that allows you to write type safe queries.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.