I have done this is the past with mySQL but I need to use Oracle:
This is a very simple register user:
application.properties
#Oracle database setup
spring.datasource.url=jdbc:oracle:thin:#999.999.999.11:1521:d3SID
spring.datasource.username=userName
spring.datasource.password=password
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver
server.port = 4000
UserInformation model
#Entity
public class UserInformation {
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private Long id;
#Column(name = "firstName")
#Min(2) #Max(15)
#NotNull
private String firstName;
#Column(name = "lastName")
private String lastName;
#Column(name = "userName")
private String userName;
#Column(name = "password")
private String 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 getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#Override
public boolean equals(Object o) {
if (this == o) {
return true;
}
if (!(o instanceof UserInformation)) {
return false;
}
UserInformation that = (UserInformation) o;
return id.equals(that.id);
}
#Override
public int hashCode() {
return id.hashCode();
}
#Override
public String toString() {
return "Applicant{" + "firstName='" + firstName + '\'' + ", lastName='" + lastName + '\'' + ", userName='" + userName + '\'' + ", password='" +
password + '\'' + '}';
}
}
JPA repo
public interface UserLoginRepo extends JpaRepository<UserInformation, Long> {}
Controller method
#RequestMapping(value = "/register", method = RequestMethod.POST)
public UserInformation registerUser(#RequestBody UserInformation user){
return userService.save(user);
}
When I run SELECT * FROM USERINFORMATION; nothing displays.
From my understanding I should not need to set up JPA config since I am doing it in applications.properties.
Did you check if the UserInformation object is coming from request body? As I know you shouldn't use "#RequestBody", just put "UserInformation user" must be in the parameters.
Related
I am working on a Spring Boot project and decided to use MongoDB . I just want to generate sequence number in MongoDB. So even if 100s of different clients trying to do that, I do not want to conflict any generated number. Is there any way to do that ?
Also I tried to make something like this :
SequenceNumber sequenceNumber;
String SEQUENCE_NAME = "example";
sequenceNumber = mongoOperations.findAndModify(query(where("_id").is(SEQUENCE_NAME)),
new Update().inc("number", 1), options().returnNew(true).upsert(true),
SequenceNumber.class);
return sequenceNumber.getNumber();
Is this correct ?
Thanks for answers !
https://www.javaprogramto.com/2019/05/spring-boot-mongodb-auto-generated-field.html
First, create a collection that will store the auto-incremented value in it. This can be created using either the mongo shell or MongoDB Compass
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "database_sequences")
public class DatabaseSequence {
#Id
private String id;
private long seq;
public DatabaseSequence() {}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public long getSeq() {
return seq;
}
public void setSeq(long seq) {
this.seq = seq;
}
}
Let’s then create a users_db collection. This collection stores the users that are being used.
import org.springframework.data.annotation.Id;
import org.springframework.data.annotation.Transient;
import org.springframework.data.mongodb.core.mapping.Document;
#Document(collection = "users_db")
public class User {
#Transient
public static final String SEQUENCE_NAME = "users_sequence";
#Id
private long id;
private String firstName;
private String lastName;
private String email;
public User() { }
public User(String firstName, String lastName, String email) {
this.firstName = firstName;
this.lastName = lastName;
this.email = email;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "User{" + "id=" + id + ", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' + ", email='" + email + '\'' + '}';
}
I have my entity class called employee and I want to soft delete my entity when I select and press delete button. I can able to select multiple employees as well, So in Java I used List of employee Entities and I want to update whole list into database table if I use merge of entityManager I can able to update only one row i.e only one entity so how do I solve this problem?
Here is some sample code.
#Entity
#Table(name="EmpInfo",schema="Auth")
public class EmpInfo{
#Id
#Column(name="EmpId")
private String userId;
#Column(name="EmailId")
private String emailId;
#Column(name="FirstName")
private String firstName;
#Column(name="LastName")
private String lastName;
#Column(name="MiddleName")
private String middleName;
#Column(name="UserAttributes")
private String userAttributes;
#Column(name="AddedDate")
private Timestamp addedDate;
#Column(name="ModifiedDate")
private Timestamp modifiedDate;
#Column(name="LastLoginDate")
private Timestamp lastLoginDate;
#Column(name="IsDeleted")
private int isDeleted;
#Column(name="AddedBy")
private String addedBy;
#Transient
private String addedByEmailId;
public String getAddedByEmailId() {
return addedByEmailId;
}
public void setAddedByEmailId(String addedByEmailId) {
this.addedByEmailId = addedByEmailId;
}
public EmpInfo() {
// TODO Auto-generated constructor stub
}
public EmpInfo(EmpInfo uInfo){
super();
this.userId=uInfo.userId;
this.emailId=uInfo.emailId;
this.firstName=uInfo.firstName;
this.lastName=uInfo.lastName;
this.middleName=uInfo.middleName;
this.userAttributes=uInfo.userAttributes;
this.addedDate=uInfo.addedDate;
this.lastLoginDate=uInfo.lastLoginDate;
this.modifiedDate=uInfo.modifiedDate;
this.addedBy=uInfo.addedBy;
this.roles=uInfo.roles;
}
public List<RoleName> getRoles() {
return roles;
}
public void setRoles(List<RoleName> roles) {
this.roles = roles;
}
public int getIsDeleted() {
return isDeleted;
}
public void setIsDeleted(int isDeleted) {
this.isDeleted = isDeleted;
}
public Date getAddedDate() {
return addedDate;
}
public void setAddedDate(Timestamp addedDate) {
this.addedDate = addedDate;
}
public Date getModifiedDate() {
return modifiedDate;
}
public void setModifiedDate(Timestamp modifiedDate) {
this.modifiedDate = modifiedDate;
}
public Date getLastLoginDate() {
return lastLoginDate;
}
public void setLastLoginDate(Timestamp lastLoginDate) {
this.lastLoginDate = lastLoginDate;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public String getEmailId() {
return emailId;
}
public void setEmailId(String emailId) {
this.emailId = emailId;
}
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 getMiddleName() {
return middleName;
}
public void setMiddleName(String middleName) {
this.middleName = middleName;
}
public String getUserAttributes() {
return userAttributes;
}
public void setUserAttributes(String userAttributes) {
this.userAttributes = userAttributes;
}
public String getAddedBy() {
return addedBy;
}
public void setAddedBy(String addedBy) {
this.addedBy = addedBy;
}
#Override
public String toString() {
return "EmpInfo [userId=" + userId + ", emailId=" + emailId + ", firstName=" + firstName + ", lastName="
+ lastName + ", middleName=" + middleName + ", userAttributes=" + userAttributes + ", addedDate="
+ addedDate + ", modifiedDate=" + modifiedDate + ", lastLoginDate=" + lastLoginDate + ", isDeleted="
+ isDeleted + ", addedBy=" + addedBy + "]";
}
}
public interface EmpInfoRepository extends JpaRepository<EmpInfo, String> {
}
use this to save list of entities as follows
#Autowired
private EmpInfoRepository empInfoRepository;
empInfoRepository.save(listOfEntity)
Since there is no custom implementation defined, implementation done by SimpleJpaRepository will be used, which will update the entities according to the #Id annotated field
My application fails to start because spring can't see bean.
I'm trying to run mu application and add created user to db. I have no idea how to create missing bean. I found that there must be annotation #Repository above interface, so I placed it, but it still doesn't work.
User:
import javax.persistence.*;
import java.io.Serializable;
import java.time.LocalDate;
#Entity
public class User implements Serializable, UserInterface {
private static final long serialVersionUID = 8062231146287834334L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column
private String login;
#Column
private String password;
#Column
private String email;
#Column
private Long phoneNumber;
#Column
private String firstName;
#Column
private String lastName;
#Column
private LocalDate dateOfBirth;
#Column
private String address;
#Column
private String city;
#Column
private String zipCode;
public User() {
//constructor for hibernate
}
private User(String login, String password, String email, Long phoneNumber, String firstName,
String lastName, LocalDate dateOfBirth, String address, String city, String zipCode) {
this.login = login;
this.password = password;
this.email = email;
this.phoneNumber = phoneNumber;
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = dateOfBirth;
this.address = address;
this.city = city;
this.zipCode = zipCode;
}
#Override
public String getLogin() {
return login;
}
#Override
public String getPassword() {
return password;
}
#Override
public String getEmail() {
return email;
}
#Override
public Long getPhoneNumber() {
return phoneNumber;
}
#Override
public String getFirstName() {
return firstName;
}
#Override
public String getLastName() {
return lastName;
}
#Override
public LocalDate getDateOfBirth() {
return dateOfBirth;
}
#Override
public String getAddress() {
return address;
}
#Override
public String getCity() {
return city;
}
#Override
public String getZipCode() {
return zipCode;
}
#Override
public String toString() {
return "User{" +
"login='" + login + '\'' +
", password='" + password + '\'' +
", email='" + email + '\'' +
", phoneNumber=" + phoneNumber +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", dateOfBirth=" + dateOfBirth +
", address='" + address + '\'' +
", city='" + city + '\'' +
", zipCode='" + zipCode + '\'' +
'}';
}
public static class UserBuilder {
private String login;
private String password;
private String email;
private Long phoneNumber;
private String firstName;
private String lastName;
private LocalDate dateOfBirth;
private String address;
private String city;
private String zipCode;
public UserBuilder setUserLogin(String login) {
this.login = login;
return this;
}
public UserBuilder setUserPassword(String password) {
this.password = password;
return this;
}
public UserBuilder setUserEmail(String email) {
this.email = email;
return this;
}
public UserBuilder setUserPhoneNumber(Long phoneNumber) {
this.phoneNumber = phoneNumber;
return this;
}
public UserBuilder setUserFirstName(String firstName) {
this.firstName = firstName;
return this;
}
public UserBuilder setUserLastName(String lastName) {
this.lastName = lastName;
return this;
}
public UserBuilder setUserDateOfBirth(String dateOfBirth) {
this.dateOfBirth = LocalDate.parse(dateOfBirth);
return this;
}
public UserBuilder setUserAddress(String address) {
this.address = address;
return this;
}
public UserBuilder setUserCity(String city) {
this.city = city;
return this;
}
public UserBuilder setUserZipCode(String zipCode) {
this.zipCode = zipCode;
return this;
}
public User build() {
boolean isAllFielsdAreFull = login != null && password != null && email != null
&& phoneNumber != null && firstName != null
&& lastName != null && dateOfBirth != null && address != null
&& city != null && zipCode != null;
if (isAllFielsdAreFull) {
return new User(login, password, email, phoneNumber, firstName, lastName, dateOfBirth, address, city, zipCode);
} else {
throw new RuntimeException("Some fields are null!");
}
}
}
}
UserRepo:
package wawer.kamil.library;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import wawer.kamil.library.domain.User;
#Repository
public interface UserRepo extends JpaRepository<User, Long> {
}
Controller:
package wawer.kamil.library;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.event.ApplicationReadyEvent;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Controller;
import wawer.kamil.library.domain.User;
#Controller
public class Start {
private UserRepo userRepo;
#Autowired
public Start(UserRepo userRepo) {
this.userRepo = userRepo;
}
#EventListener(ApplicationReadyEvent.class)
public void run() {
User user = new User.UserBuilder()
.setUserLogin("Mareczek")
.setUserPassword("Mareczek3#")
.setUserEmail("mareczek#gmail.com")
.setUserPhoneNumber(515791468L)
.setUserFirstName("Marek")
.setUserLastName("Kowalski")
.setUserDateOfBirth("1990-12-12")
.setUserAddress("Kowalska 12")
.setUserCity("Lublin")
.setUserZipCode("20-123")
.build();
userRepo.save(user);
}
}
spring.jpa.hibernate.ddl-auto=update
spring.datasource.url=jdbc:mysql://0.0.0.0:32768/library
?serverTimezone=Europe/Warsaw
spring.datasource.username=root
spring.datasource.password=root
Main class:
package wawer.kamil.library;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
#SpringBootApplication
public class LibraryApplication {
public static void main(String[] args) {
SpringApplication.run(LibraryApplication.class, args);
}
}
Error Logs:
Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2019-06-10 11:19:30.771 ERROR 6282 --- [ main] o.s.b.d.LoggingFailureAnalysisReporter :
***************************
APPLICATION FAILED TO START
***************************
Description:
Parameter 0 of constructor in wawer.kamil.library.Start required a bean of type 'wawer.kamil.library.UserRepo' that could not be found.
Action:
Consider defining a bean of type 'wawer.kamil.library.UserRepo' in your configuration.
Process finished with exit code 1
I would like to run my application, and add user to db.
You need to enable repositories
#SpringBootApplication
#EnableJpaRepositories // this will fix the issue
public class LibraryApplication {
public static void main(String[] args) {
SpringApplication.run(LibraryApplication.class, args);
}
I have the following JPA models:
Issue
#Entity
public class Issue {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private String title;
private String text;
#ManyToOne
#JoinColumn(name="user_id")
private User user;
public Issue() {}
public Issue(String title, String text) {
this.title = title;
this.text = text;
}
public long getId() {
return id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
#Override
public String toString() {
return "Issue [id=" + id + ", title=" + title + ", text=" + text + ", user=" + user + "]";
}
}
User
#Entity
public class User {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private long id;
private String username;
private String firstname;
private String lastname;
public User() {}
public User(String username) {
this.username = username;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
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;
}
#Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", firstname=" + firstname + ", lastname=" + lastname
+ "]";
}
}
And an Issue repository that extends PagingAndSortingRepository and contains the method List<Issue> findByUser(User user); See below:
public interface IssueRepository extends PagingAndSortingRepository<Issue,Long> {
List<Issue> findByUser(User user);
}
I'm trying to find a way to navigate these relationships with HTTP calls, namely how do I call findByUser(User user) and get all the issues for that user?
Using the following call I can execute that particular query:
GET http://localhost:8080/issues/search/findByUser
But I'm unclear what I should be providing as the User? Do I send the id as a query param? Do I construct an object and send that as a query param? Am I just modeling this the wrong way?
I'd like to get back a JSON list containing all the Issues for this particular User.
Thanks in advance for any help or guidance.
Changing the repository to this solved the issue. The key is to do the lookup based on a field of the User, not the User itself.
public interface IssueRepository extends PagingAndSortingRepository<Issue,Long> {
List<Issue> findByUserUsername(#Param("username") String username);
}
GET http://localhost:8080/issues/search/findByUserUsername?username=jerney
This returns a list of issues.
put another read only column like
#Column(name = "user_id", insertable = false, updatable = false)
private Long userId;
in Issue entity and use findByUserId(Long userId) repo method to find it and pass userId parameter(i.e path varible) to controller to do this using http calls.
You can use a simple findOne(Long userId) if you need only one record as its probably faster than query by string field
I'm using Firebase as a backend, I was able to fetch the data but I can't map it to a Java class. I also tried to map using JSONObject, but the problem is I should ignore the key(1) since I'm querying based on the email value.
Data
users
1:
email: sample#email.com
firstName: Big
lastName: Ben
groups:
instructor: true
Firebase related code:
Firebase ref = new Firebase("firebaseURL");
Query queryRef = ref.orderByChild("email").equalTo(mEmailEdit.getText().toString()).limitToFirst(1);
// Attach an listener to read the data at our posts reference
queryRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot snapshot) {
User user = snapshot.getValue(User.class);
System.out.println("user : " + user);
System.out.println("children : " + snapshot.getChildren().iterator().next());
mProgressDialog.dismiss();
}
#Override
public void onCancelled(FirebaseError firebaseError) {
System.out.println("The read failed: " + firebaseError.getMessage());
}
});
User.java
public class User {
private String email;
private String firstName;
private String lastName;
private Group group;
public User(){}
public User(String email, String firstName, String lastName) {
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
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 Group getGroup() {
return group;
}
public void setGroup(Group group) {
this.group = group;
}
#Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
return email.equals(user.email);
}
#Override
public int hashCode() {
return email.hashCode();
}
public class Group{
private boolean isInstructor;
private boolean isManager;
public Group(){}
public Group(boolean isInstructor, boolean isManager) {
this.isInstructor = isInstructor;
this.isManager = isManager;
}
public boolean isInstructor() {
return isInstructor;
}
public void setIsInstructor(boolean isInstructor) {
this.isInstructor = isInstructor;
}
public boolean isManager() {
return isManager;
}
public void setIsManager(boolean isManager) {
this.isManager = isManager;
}
#Override
public String toString() {
return "Group{" +
"isInstructor=" + isInstructor +
", isManager=" + isManager +
'}';
}
}
#Override
public String toString() {
return "User{" +
"email='" + email + '\'' +
", firstName='" + firstName + '\'' +
", lastName='" + lastName + '\'' +
", group=" + group +
'}';
}
}
I already get it. From onDataChanged method, I placed the code below to map the data to User class.
snapshot.getChildren().iterator().next().getValue(User.class)
// snapshot.getChildren().iterator().next() // returns the child of the returned data
// .getValue(User.class) // since we already retrieved the child, and we're
// // now referring to User class data, we can now
// // map the data using Firebase method (getValue(Class<T>))