I'm trying to save a new user to Neo4j using spring-boot, I'm getting the error that cannot set java.lang.Long to my User domain. Tried a lot of ways but still no luck on this. Can anyone tell me what I'm doing wrong here?
package com.abc.userservice.domains;
import org.neo4j.ogm.annotation.GeneratedValue;
import org.neo4j.ogm.annotation.NodeEntity;
import org.springframework.data.annotation.Id;
#NodeEntity
public class User {
#Id
#GeneratedValue
private Long id;
private String fullName;
private String gender;
private String email;
private String password;
private String createdOn;
public User(){}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getFullName() {
return fullName;
}
public void setFullName(String fullName) {
this.fullName = fullName;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
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 getCreatedOn() {
return createdOn;
}
public void setCreatedOn(String createdOn) {
this.createdOn = createdOn;
}
}
This is my service code
public User createUser(User entity) {
return userRepository.save(entity);
}
This is my controller code
#RequestMapping(value = "/create", method = RequestMethod.POST)
public User createUser(User user) {
return userService.createUser(user);
}
This is my main application code
#SpringBootApplication
#EnableNeo4jRepositories("com.abc.userservice.repositories")
#ComponentScan(basePackages = "com.abc")
#EnableTransactionManagement
public class UserServiceApplication {
public static void main(String[] args) {
SpringApplication.run(UserServiceApplication.class, args);
}
}
When I'm trying to save a new user I'm getting this below error:
Can not set java.lang.Long field com.abc.userservice.domains.User.id to com.abc.userservice.domains.User
Related
Repository
*As I am trying to enter details of user but i am getting bean Exception i don't what i have missed
from repository interface i have implements JPA and i triad with crud as well . I dint mention any controller class yet
public interface UserRepository extends JpaRepository<User,Long> {
public User findByName(String username);
}
UserModel
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String username;
private String email;
private Date DOB;
private String Address;
public User() {
}
public User(Long id, String username, String email, Date DOB, String address) {
this.id = id;
this.username = username;
this.email = email;
this.DOB = DOB;
Address = address;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getDOB() {
return DOB;
}
public void setDOB(Date DOB) {
this.DOB = DOB;
}
public String getAddress() {
return Address;
}
public void setAddress(String address) {
Address = address;
}
}
UserService
Userservice i have given
public interface UserService {
//Creating User
public User CreateUser(User user) throws Exception;
}
ServiceImp
public class UserServiceImp implements UserService {
#Autowired
private UserRepository userData;
//Creating user
#Override
public User CreateUser(User user) throws Exception {
User local=this.userData.findByName(user.getUsername());
if(local!=null)
{
System.out.println("User is already present!!");
throw new Exception("User is already there");
}
else {
local=this.userData.save(user);
}
return local;
}
}
Main Class
This is the main class
#SpringBootApplication
public class UserInformationApplication implements CommandLineRunner {
public static void main(String[] args) {
SpringApplication.run(UserInformationApplication.class, args);
}
#Override
public void run(String... args) throws Exception {
System.out.println("starting Application");
}
}
Changing this
Use for Spring Version 2.x :
import javax.persistence.*;
to
Use for Spring Version 3.x :
import jakarta.persistence.*;
Worked for me
I am trying out some new design patterns in java but I am getting confused as to why mine will not work.
I am aiming to pass a user account into a data transfer object which can then be used to sign up a new user by checking if they exist or not and if not using the getters and setters to make a user and save it to a mongoDB database with a mapper.
It all seems to be going well until I get a unresolved method call on the setpassword in my service implementation and in my mapper and I do not know why.
I am getting my setFirstname by extending a base user in my useraccount which has a firstname field on it.
Any help would be great :)
package com.datingapp.model.user;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "userAccounts")
public class UserAccount extends User {
#Id
private String id;
private String email;
private String password;
private String lastname;
private String phoneNumber;
public UserAccount() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
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 getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
package com.datingapp.dto.model.user;
import com.datingapp.model.user.User;
import com.datingapp.model.user.UserAccount;
public class UserAccountDto extends User {
private String email;
private String lastname;
private String password;
private String phoneNumber;
public UserAccountDto() {
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
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 getPhoneNumber() {
return phoneNumber;
}
public void setPhoneNumber(String phoneNumber) {
this.phoneNumber = phoneNumber;
}
}
package com.datingapp.dto.mapper;
import com.datingapp.dto.model.user.UserAccountDto;
import com.datingapp.model.user.UserAccount;
import org.springframework.stereotype.Component;
#Component
public class UserAccountMapper {
public static UserAccountDto toUserAccountDto(UserAccount userAccount) {
return new UserAccountDto()
.setEmail(userAccount.getEmail())
.setFirstname(userAccount.getFirstname())
.setLastname(userAccount.getLastname())
.setPassword(userAccount.getPassword())
.setPhoneNumber(userAccount.getPhoneNumber());
}
}
package com.datingapp.service.user;
import com.datingapp.dto.mapper.UserAccountMapper;
import com.datingapp.dto.model.user.UserAccountDto;
import com.datingapp.model.user.UserAccount;
import com.datingapp.repository.user.UserAccountRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Component;
#Component
public class UserAccountImpl implements UserAccountService {
private UserAccountRepository userAccountRepository;
private BCryptPasswordEncoder bCryptPasswordEncoder;
#Autowired
public UserAccountImpl(UserAccountRepository userAccountRepository, BCryptPasswordEncoder bCryptPasswordEncoder) {
this.userAccountRepository = userAccountRepository;
this.bCryptPasswordEncoder = bCryptPasswordEncoder;
}
#Override
public UserAccountDto signup(UserAccountDto userDto) {
UserAccount user = userAccountRepository.findByEmail(userDto.getEmail());
if (user == null) {
user = new UserAccount()
.setEmail(userDto.getEmail())
.setPassword(bCryptPasswordEncoder.encode(userDto.getPassword()))
.setFirstName(userDto.getFirstname())
.setLastName(userDto.getFirstname())
.setMobileNumber(userDto.getPhoneNumber());
return UserAccountMapper.toUserAccountDto(userAccountRepository.save(user));
}
}
}
package com.datingapp.service.user;
import com.datingapp.dto.model.user.UserAccountDto;
import com.datingapp.model.user.UserAccount;
public interface UserAccountService {
UserAccountDto signup(UserAccountDto userAccountDto);
}
Your setters are void methods, that is to say they return nothing.
You will have your expected result by making a setter like :
public UserAccountDto setEmail(String email) {
this.email = email;
return this ;
}
You have to add return this in your setters.
I know Pythagus already answered your question, but let me give you a tip.
Try to use Lombok. Lombok is a java lib which helps you to avoid boilerplate code. For example, with the #Data annotation, you are telling Lombok to create, under the hood, all your getters and setters. It will help you a lot.
I am developing an REST API application using spring boot and is struck up with the One to Many mapping while using mappedBy property.
I have User class and Usermeata class, a user can have more than one usermeta.
While the program successfully save the foreign while using JoinColumn, I want to know what mistake I am committing while using mappedby.
Here is my code:
User Entity class:
#Entity
#Table(name="User")
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long userId;
#Column(unique=true)
private String username;
#Column(unique=true)
private String emailId;
private String password;
private String firstName;
private String lastName;
private String phoneNo;
#OneToMany(fetch=FetchType.EAGER,cascade=CascadeType.ALL,mappedBy="user")
// #JoinColumn(name="user_id")
private List<UserMeta> userMetaList=new ArrayList();
public List<UserMeta> getUserMetaList() {
return userMetaList;
}
public void setUserMetaList(List<UserMeta> userMetaList) {
this.userMetaList = userMetaList;
}
public Long getUserId() {
return userId;
}
public void setUserId(Long userId) {
this.userId = userId;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getPhoneNo() {
return phoneNo;
}
public void setPhoneNo(String phoneNo) {
this.phoneNo = phoneNo;
}
}
UserMeta class:
#Entity
public class UserMeta {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long userMetaId;
#ManyToOne
#JoinColumn(name="user_id")
private User user;
private String _key;
private String _value;
public Long getUserMetaId() {
return userMetaId;
}
public void setUserMetaId(Long userMetaId) {
this.userMetaId = userMetaId;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String get_key() {
return _key;
}
public void set_key(String _key) {
this._key = _key;
}
public String get_value() {
return _value;
}
public void set_value(String _value) {
this._value = _value;
}
}
UserService.class
#Service
public class UserService {
#Autowired
private UserRepository userRepository;
public User getUser(Long userId) {
return userRepository.getOne(userId);
}
public List<User> getAllUser() {
return userRepository.findAll();
}
public User addUser(User user) {
return userRepository.save(user);
}
public void removeUser(User user) {
userRepository.delete(user);
}
public void updateUser(User user) {
userRepository.save(user);
}
}
POST request:
{
"username":"myusername",
"emailId":"myemailid#gmail.com1",
"password":"2323#123",
"firstName":"myfname",
"lastName":"mlname",
"phoneNo":"000000",
"userMetaList":[
{
"_key":"api_key",
"_value":"api_key_value"
},
{
"_key":"prop1",
"_value":"val1"
}
]
}
Now the tables are created and updated with the values, however the column user_id in the table usermeta is always null..
I am trying to retrieve data from mongodb via spring framework.
At first I made return type Map<String, Object>, but I decided to change to User value object.
Below is the class for User VO
#Document(collection = "user")
public class User {
#Id
#Field(value="id")
private String id;
#Field(value="name")
private String name;
#Field(value="password")
private String password;
#Field(value="professional")
private String professional;
#Field(value="email")
private String email;
#Field(value="gravatar")
private String gravatar;
#PersistenceConstructor
public User(String id, String name, String password, String professional, String email, String gravatar) {
super();
this.id = id;
this.name = name;
this.password = password;
this.professional = professional;
this.email = email;
this.gravatar = gravatar;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getProfessional() {
return professional;
}
public void setProfessional(String professional) {
this.professional = professional;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGravatar() {
return gravatar;
}
public void setGravatar(String gravatar) {
this.gravatar = gravatar;
}
};
and Here is #repository to retrieve data
#Repository
public class MongoMemberDao implements CommonDao<String, Map<String, Object>, Exception> {
#Autowired
MongoTemplate template;
final String COLLECTION_NAME = "user";
#SuppressWarnings("unchecked")
#Override
public Map<String, Object> read(String key) throws Exception {
Query findQuery = new Query();
findQuery.addCriteria(Criteria.where("id").is(key));
return template.findOne(findQuery, Map.class, COLLECTION_NAME);
}
public User readByDocument(String id) throws Exception {
Query findOneQuery = new Query();
findOneQuery.addCriteria(Criteria.where("id").is(id));
return template.findOne(findOneQuery, User.class, COLLECTION_NAME);
}
};
read method returns fine, but readByDocument does not(returns null not User instance). I read official document. But I do not get any clue of it.
FYI, The parameter Query looks same for both.
Query: { "id" : "system"}, Fields: null, Sort: null
I want to know why readByDocument returns null
Thanks.
---- Edit
Follow is my Database Config
#Configuration
public class MongoConfig extends AbstractMongoConfiguration {
private final String MONGO_URL = "127.0.0.1";
private final Integer MONGO_PORT = 27017;
#Override
protected String getDatabaseName() {
return "tfarm";
}
#Override
// #Bean
public Mongo mongo() throws Exception {
return new MongoClient(MONGO_URL, MONGO_PORT);
}
}
And I added this to WebApplictaionInitializer implement.
For current solution
I found follow on official site
A field annotated with #Id (org.springframework.data.annotation.Id)
will be mapped to the _id field.
A field without an annotation but named id will be mapped to the _id
field.
The default field name for identifiers is _id and can be customized
via the #Field annotation.
So I changed my VO like...
#Document(collection = "user")
public class User {
#Id
private ObjectId _id;
#Field(value="id")
private String id;
#Field(value="name")
private String name;
#Field(value="password")
private String password;
#Field(value="professional")
private String professional;
#Field(value="email")
private String email;
#Field(value="gravatar")
private String gravatar;
#PersistenceConstructor
public User(String id, String name, String password, String professional, String email, String gravatar) {
super();
this.id = id;
this.name = name;
this.password = password;
this.professional = professional;
this.email = email;
this.gravatar = gravatar;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public ObjectId get_id() {
return _id;
}
public void set_id(ObjectId _id) {
this._id = _id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getProfessional() {
return professional;
}
public void setProfessional(String professional) {
this.professional = professional;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGravatar() {
return gravatar;
}
public void setGravatar(String gravatar) {
this.gravatar = gravatar;
}
};
Added ObjectId. In alternative, just removing #Id annotation works fine too. However
#Id
#Field(value="id")
String id;
will not work. Thanks for help.
while getting values in the form the bindFromRequest().get() it returns only null value.I got all the String type is null and integr as zer0. Here is my code for controller and model packages and how I can resolve this error:
enter code here
In controller:
public static Result getShow(){
Register register=Form.form(Register.class).bindFromRequest().get();
register.save();
System.out.println(register);
return ok("#Required annotation kicked in.."+register);
}
In Models:
package models;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="register")
public class Register {
//private static final long serialVersionUID = 1L;
private String firstname;
private String lastname;
#Id
private String displayname;
private String date;
private String email;
private String password;
private String confirm_password;
private String gender;
private int phone_no;
private String address;
private int zipcode;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getLastname() {
return lastname;
}
public void setLastname(String lastname) {
this.lastname = lastname;
}
public String getDisplayname() {
return displayname;
}
public void setDisplayname(String displayname) {
this.displayname = displayname;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
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 getConfirm_password() {
return confirm_password;
}
public void setConfirm_password(String confirm_password) {
this.confirm_password = confirm_password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public int getPhone_no() {
return phone_no;
}
public void setPhone__no(int phone_no) {
this.phone_no = phone_no;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public int getZipcode() {
return zipcode;
}
public void setZipcode(int zipcode) {
this.zipcode = zipcode;
}
}
If bindFromRequest().get() returns null, then the Form didn't validate. To debug this, log Form.form(Register.class).bindFromRequest().errors(), to see the validation errors in the Form. Beyond that no one can tell you what's wrong without seeing the Register class, and the data you're trying to bind to it.
You shouldn't be blindly calling get() on the Form and trying to save it, as this obviously can fail. At least check that it hasErrors() before trying to save it. And if it does have validation errors, you should be passing that Form back to the view to show those errors to the user.
See Handling Binding Failure in the docs.