I am examining example Blog example of CouchDB. I use Ektorp at Spring for CouchDB. I wanted to implement it into my application. I have users at my couch db when I use that:
#GenerateView
#Override
public List<User> getAll() {
ViewQuery q = createQuery("all")
.descending(true)
.includeDocs(true);
return db.queryView(q, User.class);
}
However it returns just last record. Any ideas to get all users?
It works well problem was about db names that's written at Spring configuration file.
Related
I have four tables in a database. When the user uses the Search option from the React application I want the search button to query all the tables and display data from all the tables which is AWS RDS MYSQL. How should I proceed? I am using Spring boot, mysql, and react.
I would recommend taking a look at JPA Respositories. Since your db seams to be small, a simple repository method like that one should make the trick.
However, if you have a more complicated requirement, you can use a Spring Projection. Create a query that retrieves all the fields you'll need, even if they're from different tables, and map the result into a Spring Projection
Using spring data jpa you should create a method in your repository that returns a list of your projection class:
public interface MyRepository extends Repository<MyEntityProjection, Long> {
#Query("SELECT ... WHERE field = ?1")
List<MyEntityProjection> getData(String param);
}
The projection class should be something like this:
public interface MyEntityProjection {
String getField();
String getField2();
}
Adding as many fields as your query returns.
Read the docs I linked for more information and examples.
I'm refactoring a code base to get rid of SQL statements and primitive access and modernize with Spring Data JPA (backed by hibernate). I do use QueryDSL in the project for other uses.
I have a scenario where the user can "mass update" a ton of records, and select some values that they want to update. In the old way, the code manually built the update statement with an IN statement for the where for the PK (which items to update), and also manually built the SET clauses (where the options in SET clauses can vary depending on what the user wants to update).
In looking at QueryDSL documentation, it shows that it supports what I want to do. http://www.querydsl.com/static/querydsl/4.1.2/reference/html_single/#d0e399
I tried looking for a way to do this with Spring Data JPA, and haven't had any luck. Is there a repostitory interface I'm missing, or another library that is required....or would I need to autowire a queryFactory into a custom repository implementation and very literally implement the code in the QueryDSL example?
You can either write a custom method or use #Query annotation.
For custom method;
public interface RecordRepository extends RecordRepositoryCustom,
CrudRepository<Record, Long>
{
}
public interface RecordRepositoryCustom {
// Custom method
void massUpdateRecords(long... ids);
}
public class RecordRepositoryImpl implements RecordRepositoryCustom {
#Override
public void massUpdateRecords(long... ids) {
//implement using em or querydsl
}
}
For #Query annotation;
public interface RecordRepository extends CrudRepository<Record, Long>
{
#Query("update records set someColumn=someValue where id in :ids")
void massUpdateRecords(#Param("ids") long... ids);
}
There is also #NamedQuery option if you want your model class to be reusable with custom methods;
#Entity
#NamedQuery(name = "Record.massUpdateRecords", query = "update records set someColumn=someValue where id in :ids")
#Table(name = "records")
public class Record {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
//rest of the entity...
}
public interface RecordRepository extends CrudRepository<Record, Long>
{
//this will use the namedquery
void massUpdateRecords(#Param("ids") long... ids);
}
Check repositories.custom-implementations, jpa.query-methods.at-query and jpa.query-methods.named-queries at spring data reference document for more info.
This question is quite interesting for me because I was solving this very problem in my current project with the same technology stack mentioned in your question. Particularly we were interested in the second part of your question:
where the options in SET clauses can vary depending on what the user
wants to update
I do understand this is the answer you probably do not want to get but we did not find anything out there :( Spring data is quite cumbersome for update operations especially when it comes to their flexibility.
After I saw your question I tried to look up something new for spring and QueryDSL integration (you know, maybe something was released during past months) but nothing was released.
The only thing that brought me quite close is .flush in entity manager meaning you could follow the following scenario:
Get ids of entities you want to update
Retrieve all entities by these ids (first actual query to db)
Modify them in any way you want
Call entityManager.flush resulting N separate updates to database.
This approach results N+1 actual queries to database where N = number of ids needed to be updated. Moreover you are moving the data back and forth which is actually not good too.
I would advise to
autowire a queryFactory into a custom repository
implementation
Also, have a look into spring data and querydsl example. However you will find only lookup examples.
Hope my pessimistic answer helps :)
I am relatively new to hibernate. I am developing a java application which uses hibernate to do the basic CRUD operations. I wanted to add some logic specifically when I am doing a read from database. For all the operations, I do a session.createQuery to generate the query and do the operation. Is there some flag available in session object or any other related objects which differentiates a read/find operation from the rest of the CRUD operations. I wanted to add the logic where I create the HQL query from the session object.
Thanks in advance for any help in this regard.
you can use criteria, for example to find all objects related to the class USER:
public List<USER> findAllOBJECTS() {
Criteria criteria = createEntityCriteria().addOrder(Order.asc("nom"));;
return (List<USER>) criteria.list();
}
or if you want to search for a user by his login for example:
public USER findByLOGIN(String login) {
Criteria crit = createEntityCriteria();
crit.add(Restrictions.eq("login", login));
USER user = (USER)crit.uniqueResult();
return user;
}
I have spring dao bean called HostelDaoImpl. It uses hibernate criteria api to retrieve results.
public class HostelDaoImpl extends AbstractGenericDao<Hostel, Integer> implements HostelDao {
public HostelDaoImpl() {
super(Hostel.class);
}
public List<Hostel> findHostelBy(HostelSearch hs) {
Criteria criteria = currenSession().createCriteria(Hostel.class);
criteria.setReadOnly(true);
Calendar beginDate = hs.getBeginDate();
String country = hs.getCountry();
if (beginDate != null)
criteria.add(Restrictions.le("beginDate", beginDate));
if (country != null) {
criteria.add(Restrictions.eq("country", country));
}
criteria.setProjection(Projections.rowCount());
Integer foundHostelsCount = (Integer) criteria.uniqueResult();
if (foundHostelsCount > 100) {
// do pagination
}
}
}
Now in place of those comments I need pagination.
I want to create Criteria only once and then store Criteria somewhere and call Criteria's setFirstResult and setMaxResults each time when user requests new portion of data.
Where to store Criteria if spring bean HostelDaoImpl is singleton and if I create instance variable Criteria criteria it is concurrently unsafe.
Where to store Criteria so that it is thread safe?
But if you know better way to achieve hibernate pagination in spring bean please provide it.
Thanks!
You can use CRUD repositories. It supports pagination
http://docs.spring.io/spring-data/data-commons/docs/1.6.1.RELEASE/reference/html/repositories.html
I'm using the Jquery plugin JQGrid to show in a table the results, and it's very easyly to hibernate pagination.
http://jqgrid.com/
You can use pageRequest for pagination.
follow the steps on this link.
This link is very helpful. The link explains everything till JSP page.
I am getting into java here. Fun and frustrating all at the same time :)
I have a simple method called showUsernames():
public String showUsernames(){
TimesheetUserDAO su = new TimesheetUserDAO();
Session session = su.getSession();
setUsers(su.findByUsername(_users));
session.close();
return SUCCESS;
}
...however, I am having a time getting just the usernames out of the database. It is possible with the Hibernate DAO to get this correct? I am able to use su.findAll() and return everything.
Any thoughts? Need more code? Thanks :)
The DAO probably executee a request like
select u from User u where ...
Change the query to
select u.name from User u where ...
Of course, instead of having a List<User> as a result, you'll have a List<String>.
This is basic stuff described in the Hibernate reference documentation. Have you read it?
Also, getting the session from the DAO and closing it manually like this shows a design problem. This should be encapsulated by the service layer or, even better, by the declarative transaction handling.