How to search from spring cache using where condition? - spring

In the spring boot application let the entity is as follows
public class Employee{
private String location;
private String name;
private String lastName;
}
In my service, I am using #Cachable to find all
#Cacheable(value="employees")
public List<Employee> findAll() {
return employeeDAO.findAll();
}
How search from the cache using
findAllByLocationEqualsAndNameEquals(String location, String name)
without making a DB call?Please suggest.

Related

Why are nested objects retrieved from a OpenFeign request to a Spring Data Rest endpoint null?

I have the following domain classes in my client app:
#Value
public class Car {
private Long id;
private Model model;
}
#Value
public class Make {
private Long id;
private String name;
private Model model;
}
#Value
public class Model {
private Long id;
private String name;
}
My client app tries to get this data from a Spring Data Rest endpoint that return a HATEOAS response. The client does this via OpenFeign:
#FeignClient(name="car-service")
#Validated
public interface CarClient {
#GetMapping("/api/cars")
CollectionModel<Car> getAllCars();
}
But the each car has its make=null. How can I get make and model to be returned?

How to get the Prototype of Bean in Spring Boot

I am using Spring Boot and Spring Data JPA. I have created one entity as a Spring bean with prototype scope. How to I get the bean for each object to persist in database?
#Entity
#Table(name="sample")
#Scope(value=ConfigurableBeanFactory.SCOPE_PROTOTYPE)
public class Sample {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
private String name;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
If I don't use the entity as Spring bean then I will use the following code to get the object:
Sample sample = new Sample();
How should I use the object using the Prototype scope bean in Spring Boot?
You dont want to define scope for entity. Entities are not like spring bean.
Spring data uses three important components for persisting into the database.
1) Entity Class - Each table has to be defined its own java object model called entity class.
#Entity
#Table(name="sample")
public class Sample {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#Column(name="name") //Column name from the table
private String name;
2) Repo Interface- In Which you can define own implementation of SQL, and it would have save method by default.
public interface SampleRepo extends CrudRepository<Sample,Long>{
List<Sample> findByName(String name);
}
3) Client program:
private SampleRepo s;
//instantiate s using autowired setter/constructor
....
//Select example
List<Sample> sampleList=s.findByName("example");
//Insert example
//Id is auto. So no need to setup explicit value for it.
Sample entity=new Sample();
s.setName("Example");
s.save(entity);

Returning returned model object to json String using spring data jpa with hibernate

I am using spring data jpa with hibernate
This is my dao interface
#Repository
public interface IUserDAO extends JpaRepository<User, Integer>{
User findByUsername( final String username );
}
This is my User class
Entity
#Table(name="USER")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="ID", nullable = false)
private int id;
#Column(name="USERNAME", nullable = false)
private String username;
#Column(name="NAME", nullable = false)
private String name;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
This is my UserImplClass
This is my UserImplClass{
#Autowired
private IUserDAO iUserDAO;
public String findUserByUserName(String username) {
User user =iUserDAO.findByUsername(username);
Convert user to json object from framework level automatically
// i can add my one implemenation of converting user to json here ,but i want to achieve it from framework so that my code is not scattered on every service level
return "jsonStringOfUserObject"
}
Is it possible with spring data jpa with hibernate so that i do not have to write code for converting java object to json string in every service level?
I am using spring ,therefore i want to achieve it from spring .
You have two options to do what you want:
1) If you plan on returning this Object as an HTTP Response, and you use Spring MVC with Controllers you can annotate your controller method as follows:
public #ResponseBody User getUser(){
return userImplClass.findUserByUserName("yourusername");
}
2) If you want the UserImplClass itself to return a JSON String (which I do't recommend, but I leave you the decision), you can use Jackson Object Mapper to do it for you (you can inject it if you declare it as a bean on your configuration xml, or create a new instance of it, I personally prefer injecting it with #Autowired)
public String findUserByUserName(String username) {
User user =iUserDAO.findByUsername(username);
ObjectMapper mapper = new ObjectMapper(); // no need to do this if you inject via #Autowired
return mapper.writeValueAsString(user);
}

Hibernate Search + DbUnit Indexing

I am writing some JUnits for my hibernate search implementation.
I use a HSSQL in memory database. I use DBUnit to populate this DB (an XML file). It definitely works as other non-search tests work with the same data. The search code definitely works as I've tried it in the web-app and it returns the correct records.
I assume that Hibernate Search will only index database entries that have been inserted using Hibernate. I tried to index the db manually using : -
fullTextEntityManager.createIndexer().startAndWait();
I have put this in a bean that runs after Spring initialises
public class SearchIndexer {
#Autowired
private EntityManagerFactory entityManagerFactory;
public SearchIndexer(){
}
#PostConstruct
public void doIndexing(){
EntityManager em = entityManagerFactory.createEntityManager();
FullTextEntityManager fullTextEntityManager = Search.getFullTextEntityManager(em);
try {
fullTextEntityManager.createIndexer().startAndWait();
}
catch (InterruptedException e) {
e.printStackTrace();
}
}
}
I also Autowired it into my JUnit class and ran the doIndexing method manually (to be sure it was being picked up correctly AFTER the data was loaded).
#Before
public void setup() throws Exception{
dbUnitAdapter.setup("ClubDaoTest.xml");
searchIndexer.doIndexing();
super.before();
}
The dbUnitAdapter simply takes an XML file and inserts it in the db using DBUnit.
The entity is annotated like so: -
#Field
private String name;
#NotBlank
private String type;
#Field
private String address1;
#Field
private String county;
#Field
private String address2;
#Field
private String town;
#Field
private String country;
#Field
private String postcode;
private String telephone;
private String mobile;
private String fax;
#Field
private String email;
#Field
#NumericField
private long lft;
#Field
#NumericField
private long rgt;
I tried also tried inserting the data using hibernate (creating a Club entity), this didn't work either confusingly. I changed the the search index location from RAM to filesystem and used luke to read it. I could see the data that I'd tried inserting using hibernate, but no other data that I could see, although it was my first time using Luke, so I may have made a mistake.

spring data mongodb MongoRepository.save(T entity) method not working?

The code is listed below:
#Document
#XmlRootElement
public class User {
#Indexed(unique=true)
private String username;
private String firstName;
private String lastName;
private String password;
...... omit setters and getters
}
public interface UserRepo extends MongoRepository<User, String>{
}
public User update(User user) {
User existingUser = userRepo.findByUsername(user.getUsername());
if (existingUser == null) {
return null;
}
existingUser.setFirstName(user.getFirstName());
existingUser.setLastName(user.getLastName());
return userRepo.save(existingUser);
}
when update method invoked, the finds the user based on username and finishes without any exceptions, the returned User obj has all updated value but the underlying mongodb document is not changed! Can anyone help? Thanks.
you need an Id field with #Id annotation

Resources