Exclude some fields form MongoOperations result - java

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");

Related

How to check the user's verification code?

I am very new to Spring Boot. This is what I want to do: The user's email is test#example.com. That user already exists in my database, but I would like to know if their verificationCode is 123.
Entity:
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String email;
private String password;
private String verificationCode;
#Column(name = "verified", columnDefinition = "default false")
private boolean verified = false;
#CreationTimestamp
private Date registrationDate;
protected Users() {}
public Users(String email, String password, String verificationCode) {
this.email = email;
this.password = password;
this.verificationCode = verificationCode;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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 getVerificationCode() {
return verificationCode;
}
public void setVerificationCode(String verificationCode) {
this.verificationCode = verificationCode;
}
public boolean isVerified() {
return verified;
}
public void setVerified(boolean verified) {
this.verified = verified;
}
}
So with userRepository.findByEmail("test#example.com") I am getting the correct user, but how do I check their verification code?
if you're using userRepository.findByEmail("test#example.com"), just take the verification code from entity.
private static final String CODE = "123";
final User user = userRepository.findByEmail("test#example.com");
if (CODE.equals(user.getVerificationCode())) {
// do something
}
Another option to have it within query.
userRepository.findByEmailAndVerificationCode("test#example.com", CODE);
Or you can have something similar as Philipp wrote, but I would not get whole entity just find out if it exist. So solution would be
if (userRepository.existsByCode(CODE)) {
// do something
}
You search for something like that:
public void checkVerificationCode(final String verificationCode) {
final User user = userRepository.findByEmail("test#example.com");
if (!user.getVerificationCode(verificationCode)) {
throw new VerificationCodeException("Incorrect verification code.");
}
}

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();
}
}
}

AutoIncrement Id PostgreSQL and Spring Boot Data JPA

I'm having problems trying to create a new record in my PostgreSQL database. I just want to POST to the REST service a new user (int:id, String:email, String:password) but, I'm having this error:
"exception": "org.springframework.dao.DataIntegrityViolationException",
"message": "could not execute statement; SQL [n/a]; constraint [id]; nested exception is org.hibernate.exception.ConstraintViolationException: could not execute statement
These are my Java classes:
Domain
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String email;
private String password;
public User() {}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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;
}
}
Controller
#RestController
#RequestMapping("/users")
public class UserController {
#Autowired
private UserService userService;
#RequestMapping(method = RequestMethod.GET)
public List<User> findAll() {
return userService.findAll();
}
#RequestMapping(method = RequestMethod.POST)
public User addUser(#RequestBody User user) {
userService.addUser(user);
return user;
}
}
Service
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
public List<User> findAll() {
return (List<User>) userRepository.findAll();
}
public User addUser(User user) {
userRepository.save(user);
return user;
}
}
Repository
public interface UserRepository extends CrudRepository<User, Integer> {
// TODO
}
SQL
CREATE TABLE users(
id INT PRIMARY KEY NOT NULL,
email TEXT NOT NULL,
password CHAR(20) NOT NULL
);
Please, somebody help me, because I don't know how to tackle this issue.
I found the solution. I need to change the script for these one:
CREATE TABLE users(
id SERIAL PRIMARY KEY NOT NULL,
email TEXT NOT NULL,
password TEXT NOT NULL
);
Then, the Entity should be annotated with this:
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(columnDefinition = "serial")
private Long id;
private String email;
private String password;
public User() {}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
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;
}
}
SQL should be like this..
CREATE TABLE users(
id INT PRIMARY KEY BIGINT NOT NULL AUTO_INCREMENT,
email TEXT NOT NULL,
password CHAR(20) NOT NULL
);

Get all documents based on query using Spring MongoOperations

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

LazyInitializationException in Hibernate and Jersey

Hi I am doing a project using Hibernate and Jersey.
In the service layer I am getting a 'LazyInitializationException'. I searched a lot about it.
I saw a solution for creating custom AccessorType. But still I am getting the exception.
Can anyone help me??
I am including more details about it.
Bean: User
#XmlRootElement
#XmlAccessorType(XmlAccessType.PROPERTY)
#XmlAccessorFactory(XmlAccessorFactoryImpl.class)
public class User {
private String userName;
private String password;
private String email;
private String fname;
private String lname;
private Set<MachineTemplate> machineTemplates;
private String photoUrl;
public User() {
machineTemplates = new HashSet<>();
}
public User(String userName) {
this.userName = userName;
}
public User(String userName, String password, String email, String fname,
String lname) {
this.userName = userName;
this.password = password;
this.email = email;
this.fname = fname;
this.lname = lname;
this.machineTemplates = new HashSet<>();
}
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFname() {
return fname;
}
public void setFname(String fname) {
this.fname = fname;
}
public String getLname() {
return lname;
}
public void setLname(String lname) {
this.lname = lname;
}
public Set<MachineTemplate> getMachineTemplates() {
return machineTemplates;
}
public void setMachineTemplates(Set<MachineTemplate> machineTemplates) {
this.machineTemplates = machineTemplates;
}
public String getPhotoUrl() {
return photoUrl;
}
public void setPhotoUrl(String photoUrl) {
this.photoUrl = photoUrl;
}
}
DAO Layer method
public User get(String uName) {
Session session = getSessionFactory().openSession();
User u = (User) session.get(User.class, uName);
session.close();
}
Service Layer method
#GET
#Path("/{userName}")
#Produces(MediaType.APPLICATION_JSON)
public User getUserInfo(#PathParam("userName") String userName) {
return userHelper.getUser(userName);
}
The exception says you are trying to load an lazy collection which of out of session. Meaning you need to initialize the collection object before you use. The initialization should happen either in entity setter method or in DAO class. Initializing in setter method of an entity is not recommended usually since it couples your entity with hibernate framework. So best place is DAO layer. But here I have mentioned just for your reference.
Try this
public void setMachineTemplates(Set<MachineTemplate> machineTemplates) {
Hibernate.initialize(machineTemplates);
this.machineTemplates = machineTemplates;
}
Hope this is helpful!
You get the LazyInitializationException when trying to access a lazy fetched atttribute on an entity detached from the persistence context.
It usually means that your hibernate session ( / JPA entityManager) have been already closed when you access the lazy attribute.
see Struggling to understand EntityManager proper use
Actually I dont want to load the machineTemplates data. So I did like
public Set<MachineTemplate> getMachineTemplates() {
if(Hibernate.isInitialized(machineTemplates))
return machineTemplates;
return null;
}

Categories

Resources