Get all documents based on query using Spring MongoOperations - java

My User POJO look like:
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "User")
public class User {
#Id
private String id;
private String username;
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
I am able to get single document based on this query:
Query searchQuery = new Query(Criteria.where("name").is("shashi"));
mongoOperations.findOne(searchQuery, User.class);
I want to get all the document for this query. Some method call like mongoOperations.findAll(searchQuery, User.class);
How I can do this?

You have Two Option,
Option 1:
List<User> listUser = mongoOperations.find(searchQuery, User.class);
System.out.println("Number of user = " + listUser.size());
Option 2:
List<User> listUser = mongoOperation.findAll(User.class);
System.out.println("Number of user = " + listUser.size());
Note: For further details You can refer THIS LINK

Related

CrudRepository query with parameter

I would like to know if there is any way to use a parameter from a function I pass to a repository can be used in the #Query.
I would like to sort users by gaming platform so I added the following function to my UserRepository:
#Repository
public interface UserRepository extends CrudRepository<DbUser, Integer> {
#Query("SELECT * from users WHERE platform = *****parameter here***** ")
public List<DbUser> findAllByPlatform(String platform);
}
Does anybody know if this is possible? If so, how? If not, is there a clean workaround? Thanks in advance.
EDIT: My DbUser class:
#Entity
#Table(name = "users")
public class DbUser {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="user_id")
private int UserId;
#Column(name="user_name")
private String UserName;
#Column(name="email_address")
private String EmailAddress;
#Column(name="password_hash")
private int PasswordHash;
#Column(name="platform")
private String Platform;
#Column(name="platformid")
private String PlatformID;
#Convert(converter = StringListConvertor.class)
private ArrayList<String> Wishlist;
public DbUser(String userName, String emailAddress, int passwordHash, String platform, String platformID, String newWishlistItem){
UserName = userName;
EmailAddress = emailAddress;
PasswordHash = passwordHash;
Platform = platform;
PlatformID = platformID;
Wishlist.add(newWishlistItem);
}
public DbUser() {
}
public int getUserId() {
return UserId;
}
public void setUserId(int userId) {
UserId = userId;
}
public String getUserName() {
return UserName;
}
public void setUserName(String userName) {
UserName = userName;
}
public String getEmailAddress() {
return EmailAddress;
}
public void setEmailAddress(String emailAddress) {
EmailAddress = emailAddress;
}
public int getPasswordHash() {
return PasswordHash;
}
public void setPasswordHash(int passwordHash) {
PasswordHash = passwordHash;
}
public String getPlatform() {
return Platform;
}
public void setPlatform(String platform) {
Platform = platform;
}
public String getPlatformID() {
return PlatformID;
}
public void setPlatformID(String platformID) {
PlatformID = platformID;
}
public ArrayList<String> getWishlist() {
return Wishlist;
}
public void setWishlist(ArrayList<String> wishlist) {
Wishlist = wishlist;
}
}
If you're using Spring data, annotate parameter with #Param and supply variable name to be used in query:
#Query("SELECT * from users WHERE platform = :pltfrm")
public List<DbUser> findAllByPlatform(#Param("pltfrm") String platform);
You can do something like that
#Query("SELECT * from users WHERE platform = %?1")
spring data jpa documentation

Exception : Session Issue ids for this class must be manually assigned before calling save(): org.me.Testservices.TblUsers

I'm getting an exception
Session Issue ids for this class must be manually assigned before
calling save(): org.me.Testservices.TblUsers
package org.me.Testservices;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.persistence.UniqueConstraint;
/**
* TblUsers generated by hbm2java
*/
#Entity
#Table(name="tbl_users"
,catalog="ceotrp"
, uniqueConstraints = #UniqueConstraint(columnNames="Mobile_No")
)
public class TblUsers implements java.io.Serializable {
private String email;
private String username;
private String password;
private Date createTime;
private String mobileNo;
private String tblUsersType;
private String tblUserscol;
public TblUsers() {
}
public TblUsers(String email, String username, String password) {
this.email = email;
this.username = username;
this.password = password;
}
public TblUsers(String email, String username, String password, Date createTime, String mobileNo, String tblUsersType, String tblUserscol) {
this.email = email;
this.username = username;
this.password = password;
this.createTime = createTime;
this.mobileNo = mobileNo;
this.tblUsersType = tblUsersType;
this.tblUserscol = tblUserscol;
}
#Id
#Column(name="email", unique=true, nullable=false)
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name="username", nullable=false, length=16)
public String getUsername() {
return this.username;
}
public void setUsername(String username) {
this.username = username;
}
#Column(name="password", nullable=false, length=32)
public String getPassword() {
return this.password;
}
public void setPassword(String password) {
this.password = password;
}
#Temporal(TemporalType.TIMESTAMP)
#Column(name="create_time", length=26)
public Date getCreateTime() {
return this.createTime;
}
public void setCreateTime(Date createTime) {
this.createTime = createTime;
}
#Column(name="Mobile_No", unique=true, length=14)
public String getMobileNo() {
return this.mobileNo;
}
public void setMobileNo(String mobileNo) {
this.mobileNo = mobileNo;
}
#Column(name="tbl_UsersType", length=1)
public String getTblUsersType() {
return this.tblUsersType;
}
public void setTblUsersType(String tblUsersType) {
this.tblUsersType = tblUsersType;
}
#Column(name="tbl_Userscol", length=45)
public String getTblUserscol() {
return this.tblUserscol;
}
public void setTblUserscol(String tblUserscol) {
this.tblUserscol = tblUserscol;
}
}`
>I AM NEW TO HIBERNATE in NETBEANS 8.2 . The Select Query is Working Fine ,but INSERT is Not Happening .
>>The Code Below Demonstrates how I am using hibernate and the Above Code for Inserting in MySQL 8.0 (Which is Of course not Happening)
public String registernewUser( String name , String email,String password,String MObileNo,String Utype)
{
TblUsers ins =new TblUsers();
ins.setUsername(name);
ins.setPassword(password);
ins.setMobileNo(MObileNo);
ins.setTblUsersType(Utype);
ins.setTblUserscol("D");
ins.setTblUsersType("C");
try{
/* session.beginTransaction();
session.save(ins);
session.getTransaction().commit();
session.close();*/
Transaction t= session.beginTransaction();
session.save(ins);
t.commit();
return "Operation executed";
}
catch(Throwable ex)
{
System.err.println("Session Issue " + ex.getMessage());
return ex.getMessage();
}
}
}
If you need other files I can provide them. I am trying to create a web service for an Android App and also I am fond of Hibernate Technologies. Please let me know the best way to optimize the above code . I am using Glassfish Server to test the web service.
TblUsers #Entity class has a String type for its #Id field, so it can't generate ids for you.The value of identifier has to be set by the application before save.
public String registernewUser( String name , String email,String password,String MObileNo,String Utype)
{
TblUsers ins =new TblUsers();
ins.setUsername(name);
ins.setEmail(email); // set email
ins.setPassword(password);
ins.setMobileNo(MObileNo);
ins.setTblUsersType(Utype);
ins.setTblUserscol("D");
ins.setTblUsersType("C");
try{
/* session.beginTransaction();
session.save(ins);
session.getTransaction().commit();
session.close();*/
Transaction t= session.beginTransaction();
session.save(ins);
t.commit();
return "Operation executed";
}
catch(Throwable ex)
{
System.err.println("Session Issue " + ex.getMessage());
return ex.getMessage();
}
}
}

Getting same value on Fetctype Lazy and Eager

I am new to Jpa and I added spring boot jpa in my spring boot for One to One mappings. So,
package com.jpa.onetoone.onetoonejpa.model;
import org.hibernate.annotations.GeneratorType;
import javax.persistence.*;
#Entity
public class User {
#Id
#GeneratedValue
private Long id;
private String username;
private String password;
#OneToOne(cascade=CascadeType.ALL,mappedBy = "user",fetch = FetchType.LAZY)
private Address address;
public User(String username, String password) {
this.username = username;
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
#Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
public User() {
}
}
Address.java file is
package com.jpa.onetoone.onetoonejpa.model;
import com.fasterxml.jackson.annotation.JsonIgnore;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.OneToOne;
#Entity
public class Address {
#Id
#GeneratedValue
private Long id;
private String homeAddress;
private int homeNumber;
#OneToOne
#JsonIgnore
private User user;
public Address(String homeAddress, int homeNumber) {
this.homeAddress = homeAddress;
this.homeNumber = homeNumber;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getHomeAddress() {
return homeAddress;
}
public void setHomeAddress(String homeAddress) {
this.homeAddress = homeAddress;
}
public int getHomeNumber() {
return homeNumber;
}
public void setHomeNumber(int homeNumber) {
this.homeNumber = homeNumber;
}
public Address() {
}
}
I have added one to one relationship between User and Address.I have inserted the data in database and want to acquire data through RestController.So,I am just testing my application using FetchType.Lazy and FetchType.Eager in User class but I am getting the same Json.There is no change in JSOn with the FetchType.
When I hit the URL :http://localhost:8080/users in both fetchtype.lazy and fetchtype.eager i am getting the same JSON as the address field needs to be eradicated as I use fetchtype.lazy in Address field.
#OneToOne(cascade=CascadeType.ALL,mappedBy = "user",fetch = FetchType.LAZY)
private Address address;
The JSON i am getting in both case is:
[
{
"id":3,
"username":"ashwin",
"password":"karki",
"address":{
"id":4,
"homeAddress":"kapan",
"homeNumber":71444
}
}
]
Another question I want to ask is,when I try to access http://localhost:8080/address ,I also want User object associated with address.The loop went to infinite and I added JsonIgnore,then the Json is printed like below.Is there any way, we can access both user from address and address from user when hitting these two URL?
[
{
"id":4,
"homeAddress":"kapan",
"homeNumber":71444
}
]
DefaultController.java
package com.jpa.onetoone.onetoonejpa.controller;
import com.jpa.onetoone.onetoonejpa.model.Address;
import com.jpa.onetoone.onetoonejpa.model.User;
import com.jpa.onetoone.onetoonejpa.repository.AddressRepository;
import com.jpa.onetoone.onetoonejpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
#RestController
public class DefaultController {
#Autowired
private UserRepository userRepository;
#Autowired
private AddressRepository addressRepository;
#GetMapping(value = "/users")
public List<User> getUsers() {
List<User> users = userRepository.findAll();
return users;
}
#GetMapping(value = "/address")
public List<Address> getAddress() {
List<Address> address = addressRepository.findAll();
return address;
}
}
There is no change in JSON with the FetchType - and should not. The fetch type is a strategy of loading data from a database.
With EAGER user and address loads at the same time, with one SQL call:
#GetMapping(value = "/users")
public List<User> getUsers() {
List<User> users = userRepository.findAll(); // users and addresses was loaded
return users;
}
With LAZY, address will not be loaded while you don't read them. But, when you return users from a controller, JSON mapper read address property, so it will be loaded with one SQL call per user:
#GetMapping(value = "/users")
public List<User> getUsers() {
List<User> users = userRepository.findAll(); // users was loaded
return users; // addresses was loaded for each user one by one
}
And the second question. There are many ways. See JsonView, for example.
Use #JsonManagedReference and #JsonBackReference annotations to avoid your application of infinite loop. You can review the following questions:
Difference between #JsonIgnore and #JsonBackReference, #JsonManagedReference
Infinite Recursion with Jackson JSON and Hibernate JPA issue

Exclude some fields form MongoOperations result

My User POJO looks like the following:
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "User")
public class User {
#Id
private String id;
private String username;
private String password;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
I am able to get all document based on the query:
List<User> testBedsFromDB = mongoOperations.findAll(User.class);
I want to skip some of the fields like password. I want to get all the document with values only in id and username, password may be null or empty. How I can achieve this?
I was able to get all field excluding one field. Code spinet bellow:
Query searchQuery = new Query();
searchQuery.fields().exclude("password");
List<User> userList = mongoOperations.find(searchQuery, User.class);
With above code password field value will be null.
You can use multiple exclude like:
searchQuery.fields().exclude("username").exclude("password");

check if an email in my database while sign up, using hibernate

I am programming an IHM for sign up the users, I need to check if this user is already in database(mysql), checking by his email . can you help me please.
I can save my user now but how to check if this user by his email
this is my Dao layer class :
public class UserDaoMysql implements UserDao {
private Session session;
private void openSession(){
SessionFactory sessionFactory=HibernateUtil.getSessionFactory();
session = sessionFactory.openSession();
session.beginTransaction();
}
private void closeSession(){
session.getTransaction().commit();
session.close();
}
public void insert(User user) {
if(checkEmail(user)){
openSession();
User p = new User(user.getName(), user.getEmail(), user.getPassword());
session.save(p);
System.out.println("sauvegarde reussi");
closeSession();
}
}
public boolean checkEmail(User user){
return true;
}
}
this is my user bean :
#ManagedBean(name="user")
public class User {
private int id;
private String name;
private String email;
private String password;
private String confirmationPass;
// private image
public User() {
super();
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmationPass() {
return confirmationPass;
}
public void setConfirmationPass(String confirmationPass) {
this.confirmationPass = confirmationPass;
}
public User(int id, String name, String email, String password,
String confirmationPass) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
this.confirmationPass = confirmationPass;
}
public User(int id, String name, String email, String password) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
}
public User(String name, String email, String password) {
super();
this.name = name;
this.email = email;
this.password = password;
}
#Override
public String toString() {
return "User [id=" + id + ", Name=" + name + ", email=" + email
+ ", password=" + password + "]";
}
public void save(){
UserBusiness userBusiness = new UserBusinessImp();
userBusiness.add(new User(name, email,password));
}
}
And I have a table user in my database.
thanks for your help in advance
I would use NamedQuery for this. Define named query in your User entity like this:
...
#NamedQueries({
#NamedQuery(name = "User.findByEmail",
query = "SELECT u FROM User u WHERE u.email = :email")})
#ManagedBean(name="user")
public class User {
...
And then add method like this to your DAO
public List<User> getUsersByEmail(String email){
openSession();
Session session;
Query query = session.getNamedQuery("User.findByEmail");
query.setString("email", email);
Lis<Users> users = query.list();
closeSession();
return users;
}
This method is little bit more generic you can make it more specific returning user count only.

Categories

Resources