I can't get an entity ID in spring boot - spring

I am learning Spring-Boot and I'm doing a little project to practice, but I have a problem.
This is a simple authentication app, you can register and log in. My aim is: If you log in your username should be appeared, and for further functions I need the ID as well.
So I have this code:
#PostMapping("/main")
public String login(#ModelAttribute Users user, Model model) {
time = sdf.format(new Date());
Users correctUser = serv.selectUser(user.getName(), user.getPassword());
if (correctUser != null) {
//Users data
login_name = user.getName();
actual_user_id = user.getId();
model.addAttribute("given_name", login_name);
System.out.println("DEBUG: " + user);
System.out.println(time + " Successful");
return "main_screen";
} else {
System.out.println(time + " Log in failed");
return "error_page";
}
}
I can get and storage the name well in login_name, but with the ID I have some problems. As you can see I use user.getId() same as with name, but either way I get null and can't storage the ID in my actual_user_id variable.
Here is my repository:
#Repository
public interface UserRepository extends JpaRepository<Users, Integer> {
Optional<Users> findFirstByName(String name);
Optional<Users> findUserByNameAndPassword(String name, String password);
}
And my service method:
public Users authentication(String name, String password) {
return repo.findUserByNameAndPassword(name, password).orElse(null);
}
EDIT: And this is my Users class
#Entity
#Table(name = "users")
public class Users {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
private String name;
private String password;
private String email;
public Integer getId() {
return 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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Override
public String toString() {
return "Users{" +
"id=" + id +
", name='" + name + '\'' +
", passowrd='" + password + '\'' +
", email='" + email + '\'' +
'}';
}
}
I think it should work, but I can't find the problem.
Can anyone help me?
As I can see, I get the name and the password with the findUserByNameAndPassword() and nothing else, however I should I suppose.

You look to be trying to get your id from the user passed to you in the post request:
actual_user_id = user.getId();
Try getting your information from the user you retrieved from the database:
actual_user_id = correctUser.getId();

Related

Password Encoder Match not working Spring boot

i am creating the Spring Boot application login with hash password.without set hash password login working successfully.with hash password set getting error while writing the code.
passwordEncoder.matches(loginDTO.getEmail())
it indicate the error was
'matches(java.lang.CharSequence, java.lang.String)' in 'org.springframework.security.crypto.password.PasswordEncoder' cannot be applied to '(java.lang.String)'
what i tried so far i attached the full code below.
LoginDTO.java
package com.example.Registation.Dto;
public class LoginDTO {
private String email;
private String password;
public LoginDTO() {
}
public LoginDTO(String email, String password) {
this.email = email;
this.password = password;
}
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;
}
#Override
public String toString() {
return "LoginDTO{" +
"email='" + email + '\'' +
", password='" + password + '\'' +
'}';
}
}
EmployeeController.java
#PostMapping(path = "/login")
public String loginEmployee(#RequestBody LoginDTO loginDTO)
{
String email = employeeService.loginEmployee(loginDTO);
return email;
}
Employee Service
public interface EmployeeService {
String loginEmployee(LoginDTO loginDTO);
}
EmployeeRepo
#EnableJpaRepositories
#Repository
public interface EmployeeRepo extends JpaRepository<Employee,Integer>
{
Optional<Employee> findOneByEmailAndPassword(String email, String password);
}
EmployeeIMPL
#Override
public String loginEmployee(LoginDTO loginDTO) {
CharSequence password = loginDTO.getPassword();
String encodedPassword = loginDTO.getPassword(); // assume this is the encoded password from the database
Optional<Employee> employee = employeeRepo.findOneByEmailAndPassword(loginDTO.getEmail(), passwordEncoder.matches(password,encodedPassword));
if (employee.isPresent()) {
return "Login Success for " + employee.get();
} else {
return "Login Fail";
}
}
}
import org.springframework.security.crypto.password.PasswordEncoder;
//PasswordEncoder bean
#Autowired
private PasswordEncoder passwordEncoder;
//check password
if (passwordEncoder.matches(changePasswordRequest.getOldPassword(), user.getPassword())){
}
Both password type is String.
OldPassword and Password type is String.

Foregine key is not updating in spring boot Jpa

Basically, I am trying to establish a relationship between my two tables using spring boots.
And the relationship which I had used was the #onetoone and #onetomany relationship.
But after building the relationship and creating the table in MySQL whenever I run the program my foreign key is not updating.
The relationship is one user can have many contacts. I have tried unidirectional as well as bidirectional mapping but it is not working.
I want in contact table there will be a separate column for the foreign key. Based on that key I will show all contacts for that particular user.
This is my contact entity...
package com.example.jpa.contactEntities;
#Entity
#Table(name = "Contact")
public class ContactEntities {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long c_id;
private String c_name;
private String second_c_name;
private String c_work;
private String c_emali;
private String c_phone;
private String c_image;
#Column(length = 5000)
private String c_description;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "contact_id")
private UserEntities userEntities;
public ContactEntities() {
super();
}
public ContactEntities(long c_id, String c_name, String second_c_name, String c_work, String c_emali,
String c_phone, String c_image, String c_description, UserEntities userEntities) {
super();
this.c_id = c_id;
this.c_name = c_name;
this.second_c_name = second_c_name;
this.c_work = c_work;
this.c_emali = c_emali;
this.c_phone = c_phone;
this.c_image = c_image;
this.c_description = c_description;
this.userEntities = userEntities;
}
public long getC_id() {
return c_id;
}
public void setC_id(int c_id) {
this.c_id = c_id;
}
public String getC_name() {
return c_name;
}
public void setC_name(String c_name) {
this.c_name = c_name;
}
public String getSecond_c_name() {
return second_c_name;
}
public void setSecond_c_name(String second_c_name) {
this.second_c_name = second_c_name;
}
public String getC_work() {
return c_work;
}
public void setC_work(String c_work) {
this.c_work = c_work;
}
public String getC_emali() {
return c_emali;
}
public void setC_emali(String c_emali) {
this.c_emali = c_emali;
}
public String getC_phone() {
return c_phone;
}
public void setC_phone(String c_phone) {
this.c_phone = c_phone;
}
public String getC_image() {
return c_image;
}
public void setC_image(String c_image) {
this.c_image = c_image;
}
public String getC_description() {
return c_description;
}
public void setC_description(String c_description) {
this.c_description = c_description;
}
public UserEntities getUserEntities() {
return userEntities;
}
public void setUserEntities(UserEntities userEntities) {
this.userEntities = userEntities;
}
#Override
public String toString() {
return "ContactEntities [c_id=" + c_id + ", c_name=" + c_name + ", second_c_name=" + second_c_name + ", c_work="
+ c_work + ", c_emali=" + c_emali + ", c_phone=" + c_phone + ", c_image=" + c_image + ", c_description="
+ c_description + ", userEntities=" + userEntities + "]";
}
}
this is my user entity...
package com.example.jpa.userEntities;
#Entity
#Table(name = "UserEntities")
public class UserEntities {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long userId;
#NotBlank
#Size(min = 2, max = 20)
private String userName;
#NotBlank
#Column(unique = true)
#Email(regexp = "^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\\.[a-zA-Z0-9-]+)*$")
private String userEmail;
#NotNull(message = "password should not be blank")
private String userPass;
private boolean enable;
private String role;
#Column(length = 500)
private String userAbout;
#OneToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL, mappedBy = "userEntities", orphanRemoval = true)
private List<ContactEntities> contactList = new ArrayList<>();
public UserEntities() {
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
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 getUserEmail() {
return userEmail;
}
public void setUserEmail(String userEmail) {
this.userEmail = userEmail;
}
public String getUserPass() {
return userPass;
}
public void setUserPass(String userPass) {
this.userPass = userPass;
}
public boolean isEnable() {
return enable;
}
public void setEnable(boolean enable) {
this.enable = enable;
}
public String getRoll() {
return role;
}
public void setRoll(String role) {
this.role = role;
}
public String getUserAbout() {
return userAbout;
}
public void setUserAbout(String userAbout) {
this.userAbout = userAbout;
}
public List<ContactEntities> getContactList() {
return contactList;
}
public void setContactList(List<ContactEntities> contactList) {
this.contactList = contactList;
}
#Override
public String toString() {
return "UserEntities [userId=" + userId + ", userName=" + userName + ", userEmail=" + userEmail + ", userPass="
+ userPass + ", enable=" + enable + ", role=" + role + ", userAbout=" + userAbout + ", contactList="
+ contactList + "]";
}
}
Repository of Contact
package com.example.jpa.repo;
import java.util.List;
import com.example.jpa.contactEntities.ContactEntities;
public interface ContactRepo extends JpaRepository<ContactEntities, Integer> {
#Query("from ContactEntities as c where c.userEntities.userId=:u_Id")
public List<ContactEntities> findContactsByUser(#Param("u_Id") long l);
}
Repository of User
package com.example.jpa.repo;
import com.example.jpa.userEntities.UserEntities;
#EnableJpaRepositories
public interface UserRepository extends JpaRepository<UserEntities, Integer> {
#Query("select u from UserEntities u where u.userEmail=:userEmail")
public UserEntities getUserByUserName(#Param("userEmail") String userEmail);
}
User controller
package com.example.jpa.controller;
#Controller
#RequestMapping("/user")
public class UserController {
#Autowired
private UserRepository userRepository;
#Autowired
private ContactRepo contactRepo;
#ModelAttribute
public void addCommonData(Model model, Principal principal) {
String username = principal.getName();
System.out.println("UserName:-" + username);
UserEntities userEntities = this.userRepository.getUserByUserName(username);
System.out.println("User:- " + userEntities);
model.addAttribute("userEntities", userEntities);
}
//dash board home
#RequestMapping("/index")
public String dashboard(Model model, Principal principal) {
return "normal/user_dashboard";
}
// open add form handler
#GetMapping("/add-contact")
public String openAddContactForm(Model model) {
model.addAttribute("title", "Add contact");
model.addAttribute("contactEntitie", new ContactEntities());
return "normal/add_contact";
}
// processing and contact form
#PostMapping("/upload")
public String processContact(#ModelAttribute ContactEntities contactEntitie,
#RequestParam("userImage") MultipartFile multipartFile, Principal principal, Model model,
HttpSession session) {
try {
model.addAttribute("contactEntitie", new ContactEntities());
String name = principal.getName();
UserEntities userEntities = userRepository.getUserByUserName(name);
userEntities.getContactList().add(contactEntitie);
// processing and uploading file....
if (multipartFile.isEmpty()) {
System.out.println("File is empty");
} else {
// upload the the file and update
contactEntitie.setC_image(multipartFile.getOriginalFilename());
File saveFile = new ClassPathResource("static/img").getFile();
// bring the folder path...
Path path = Paths
.get(saveFile.getAbsolutePath() + File.separator + multipartFile.getOriginalFilename());
Files.copy(multipartFile.getInputStream(), path, StandardCopyOption.REPLACE_EXISTING);
System.out.println("Image is uploaded");
}
userRepository.save(userEntities);
System.out.println("Datas are :" + contactEntitie);
// message success
session.setAttribute("message", new Messages("Your Contact is added !!! Add more...", "success"));
} catch (Exception e) {
System.out.println("Error: " + e.getMessage());
e.printStackTrace();
// error message
session.setAttribute("message", new Messages("Something went wrong !!! Try Again", "danger"));
}
return "normal/add_contact";
}
// show Contact handler
#GetMapping("/show-contacts")
public String showContact(Model model, Principal principal) {
model.addAttribute("title", "Show Contacts");
String userName = principal.getName();
UserEntities userEntities = userRepository.getUserByUserName(userName);
List<ContactEntities> contactList = contactRepo.findContactsByUser(userEntities.getUserId());
model.addAttribute("contactList", contactList);
return "normal/show_contacts";
}
}
All configuration class
User Details configuration
package com.example.jpa.Myconfiguration;
public class UserDetailsServiceImple implements UserDetailsService {
#Autowired
private UserRepository userRepository;
#Override
public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
// fetching data from DB
UserEntities userEntities = userRepository.getUserByUserName(username);
if (userEntities == null) {
throw new UsernameNotFoundException("Could not found user !!!");
}
CustomUserDetails customUserDetails = new CustomUserDetails(userEntities);
return customUserDetails;
}
}
package com.example.jpa.Myconfiguration;
public class CustomUserDetails implements UserDetails {
private UserEntities userEntities;
public CustomUserDetails(UserEntities userEntities) {
super();
this.userEntities = userEntities;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
SimpleGrantedAuthority simpleGrantedAuthority = new SimpleGrantedAuthority(userEntities.getRoll());
return List.of(simpleGrantedAuthority);
}
#Override
public String getPassword() {
return userEntities.getUserPass();
}
#Override
public String getUsername() {
return userEntities.getUserEmail();
}
#Override
public boolean isAccountNonExpired() {
return true;
}
#Override
public boolean isAccountNonLocked() {
return true;
}
#Override
public boolean isCredentialsNonExpired() {
return true;
}
#Override
public boolean isEnabled() {
return true;
}
}
Application property:-
#Database configuration
spring.datasource.url=jdbc:mysql://localhost:3306/smartcontact
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.NonRegisteringDriver
spring.jpa.properties.hibernate.dilact=org.hibernate.dialect.Mysql8Dialect
spring.jpa.hibernate.ddl-auto=update
spring.jpa.show-sql=false
spring.jpa.properties.hibernate.globally_quoted_identifiers=true
spring.servlet.multipart.enabled=true
spring.servlet.multipart.file-size-threshold=2KB
spring.servlet.multipart.max-file-size=10MB
spring.servlet.multipart.max-request-size=10MB

Login with SpringBoot

I'm taking the first steps with SpringBoot ... I want to make a service Log in where you put a user and a password and if it is correct it returns the user's data.
At the moment, with what I can do the user's data according to, but I can solve what I want, I would appreciate it.
The problem that I have 2. I do not know how to send 2 parameters "username", "password" for a moment Send 1.
Repository:
import org.springframework.data.repository.CrudRepository;
import prueba.Usuario;
public interface UsuRepository extends CrudRepository<Usuario,String>{
}
usuarioClass:
#Entity
#Table(name="usuario")
#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class Usuario {
#Id
#Column(name="id")
private int id;
#Column(name="name")
private String name;
#Column(name="email")
private String email;
public Usuario() {
}
public Usuario(int id, String name, String email) {
this.id = id;
this.name = name;
this.email = email;
}
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;
}
#Override
public String toString() {
return "User[id=" + id + ", name=" + name + ", email=" + email + "]";
}
Controller
#RestController
#RequestMapping(value={"/usu"})
public class UsuController {
#Autowired
UsuService usuRepository;
#RequestMapping("/")
String home() {
return "Servicio Usuario!";
}
#RequestMapping(method=RequestMethod.GET, path = "/Login/{userName}" , produces = MediaType.APPLICATION_JSON_VALUE)
public Usuario Login(#PathVariable("userName") String userName) {
Usuario tasks = usuRepository.getUsu(userName);
return tasks;
}
Interface:
public interface UsuService {
public List<Usuario> getUsus() ;
public Usuario getUsu(String name);
}
Service:
#Override
public Usuario getUsu(String user) {
Usuario usu;
return usu = usuRepository.findOne(user);
}
run:
http://localhost:8080/usu/Login/edu
Error:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Mon Jul 02 10:31:34 CEST 2018
There was an unexpected error (type=Internal Server Error, status=500).
Provided id of the wrong type for class prueba.Usuario. Expected: class java.lang.Integer, got class java.lang.String; nested exception is java.lang.IllegalArgumentException: Provided id of the wrong type for class prueba.Usuario. Expected: class java.lang.Integer, got class java.lang.String
I already did a test returning all the users and it works.
At the moment I want to have my username, I return my data, and then I will do the Log in with password. Thanks.
I saw others tutorials The Login with SpringBoot, but this tutorials has "Security, encriptyng , etc " but I am new With this, I need service Login easy...
I think you're mixing some concepts here. See you have this:
1) Class Usuario with an id of type int:
public class Usuario {
#Id
#Column(name="id")
private int id;
...
}
2) A request mapping receiving an user name of type String:
#RequestMapping(method=RequestMethod.GET, path = "/Login/{userName}" , produces = MediaType.APPLICATION_JSON_VALUE)
public Usuario Login(#PathVariable("userName") String userName) { ...
3) A repository configured with String as the id type of the Usuario entity:
public interface UsuRepository extends CrudRepository<Usuario,String>
Conclussion:
When you do:
public Usuario getUsu(**String** user) {
...
return usu = usuRepository.findOne(**user**);
}
You're asking the repository to find an Usuario entity with a String ID but Usuario has an int as an ID.
Therefore the error:
Provided id of the wrong type for class prueba.Usuario. **Expected**: class java.lang.Integer, **got** class java.lang.String; nested exception is java.lang.IllegalArgumentException: Provided id of the wrong type for class prueba.Usuario. Expected: class java.lang.Integer, got class java.lang.String
You need something like this:
public interface UsuRepository extends CrudRepository<Usuario,Integer> {
Usuario getByName(String username);
}
Hope I helped. :-)

DAO instance not working in service class - NullPointerException

In my spring boot project I created a Repository interface (which extends CRUDRepository) and an Entity class of the Table in my DB.
This is my Repo:
#Repository
public interface AuthPaymentDao extends CrudRepository<TFraudCard,String> {
#Query("SELECT t FROM TFraudCard t where t.tokenNumber = (?1)")
TFraudCard findByTokenNumber(String tokenNumber);
}
This is my Entity Class (TOKEN_NUMBER is the primary Key in the TFRAUDCARD TABLE):
#Entity
#Table(name = "TFRAUDCARD")
public class TFraudCard {
#Id
#Column(name="TOKEN_NUMBER")
private String tokenNumber;
#Column(name="TRANSACTIONNUMBER")
private int transactionNumber;
#Column(name="CARDNUMBER")
private int cardNumber;
#Column(name="DATEADDED", insertable = false, updatable = false, nullable = false)
private Timestamp dateAdded;
#Column(name="CALLINGENTITY", nullable = false)
private String callingEntity;
#Column(name="ACCOUNTID")
private String accountId;
#Column(name="ROUTINGNUMBER")
private String routingNumber;
#Column(name="BANKACCOUNTNUMBER")
private String bankAccountNumber;
#Column(name="COMMENTS")
private String comments;
#Column(name="USERID")
private String userId;
#Column(name="REMOVEDATE")
private Timestamp removeDate;
public String getTokenNumber() {
return tokenNumber;
}
public void setTokenNumber(String tokenNumber) {
this.tokenNumber = tokenNumber;
}
public int getTransactionNumber() {
return transactionNumber;
}
public void setTransactionNumber(int transactionNumber) {
this.transactionNumber = transactionNumber;
}
public int getCardNumber() {
return cardNumber;
}
public void setCardNumber(int cardNumber) {
this.cardNumber = cardNumber;
}
public Timestamp getDateAdded() {
return dateAdded;
}
public void setDateAdded(Timestamp dateAdded) {
this.dateAdded = dateAdded;
}
public String getCallingEntity() {
return callingEntity;
}
public void setCallingEntity(String callingEntity) {
this.callingEntity = callingEntity;
}
public String getAccountId() {
return accountId;
}
public void setAccountId(String accountId) {
this.accountId = accountId;
}
public String getRoutingNumber() {
return routingNumber;
}
public void setRoutingNumber(String routingNumber) {
this.routingNumber = routingNumber;
}
public String getBankAccountNumber() {
return bankAccountNumber;
}
public void setBankAccountNumber(String bankAccountNumber) {
this.bankAccountNumber = bankAccountNumber;
}
public String getComments() {
return comments;
}
public void setComments(String comments) {
this.comments = comments;
}
public String getUserId() {
return userId;
}
public void setUserId(String userId) {
this.userId = userId;
}
public Timestamp getRemoveDate() {
return removeDate;
}
public void setRemoveDate(Timestamp removeDate) {
this.removeDate = removeDate;
}
public TFraudCard() {
super();
}
public TFraudCard(String tokenNumber, int transactionNumber, int cardNumber, Timestamp dateAdded,
String callingEntity, String accountId, String routingNumber, String bankAccountNumber, String comments,
String userId, Timestamp removeDate) {
super();
this.tokenNumber = tokenNumber;
this.transactionNumber = transactionNumber;
this.cardNumber = cardNumber;
this.dateAdded = dateAdded;
this.callingEntity = callingEntity;
this.accountId = accountId;
this.routingNumber = routingNumber;
this.bankAccountNumber = bankAccountNumber;
this.comments = comments;
this.userId = userId;
this.removeDate = removeDate;
}
#Override
public String toString() {
return "TFraudCard [tokenNumber=" + tokenNumber + ", transactionNumber=" + transactionNumber + ", cardNumber="
+ cardNumber + ", dateAdded=" + dateAdded + ", callingEntity=" + callingEntity + ", accountId="
+ accountId + ", routingNumber=" + routingNumber + ", bankAccountNumber=" + bankAccountNumber
+ ", comments=" + comments + ", userId=" + userId + ", removeDate=" + removeDate + "]";
}
}
My Service Class:
Autowiring the DAO instance inside my Service Class:
Implementing the DAO instance inside a Method in the Service Class:
private void fraudCheck(PaymentDetail paymentDetail) throws RegularPaymentBusinessException {
logger.info("INSIDE FRAUD CHECK METHOD");
String pmtInd=paymentDetail.getPmtInd();
logger.info("pmtInd: " + pmtInd);
String tokenizedCardNum=paymentDetail.getTokenizedCardNum();
logger.info("tokenizedCardNum: " + tokenizedCardNum);
if(pmtInd.equalsIgnoreCase(VepsConstants.GIFT_CARD_IDENTIFIER) || pmtInd.equalsIgnoreCase(VepsConstants.CREDIT_CARD_IDENTIFIER) || pmtInd.equalsIgnoreCase(VepsConstants.DEBIT_CARD_IDENTIFIER)) {
logger.info("INSIDE CARD CHECK");
TFraudCard fraudCard = authPaymentDao.findByTokenNumber(tokenizedCardNum);
logger.info("fraudCard Details: " + fraudCard.toString());
if(fraudCard!=null) {
logger.info("INSIDE EXCEPTION FLOW FOR CARD FRAUD CHECK");
throw new RegularPaymentBusinessException(VepsConstants._9966, VepsConstants._9966_MESSAGE, VepsConstants.FAILURE);
}
}
}
Even though I pass the same token Number (tokenizedCardNumber) in my method as the data in the TOKEN_NUMBER column of my TFRAUDCARD table I still get a NullPointerException when I try to print a toString() of the Entity Object.
Here is the NullPointerException on my cloudFoundry logs (Click on it to see zoomed image) :
I'm providing the DB details in my dev properties file:
I have gone over every scenario in my head for why it breaks but I still can't come up with an answer. I'm using my variable marked with #Id i.e. the Primary Key for my find() method in the Repository.
I'm also adding a #Query annotation just to be even more specific.
It still does not work.

Programmatically set a partition-key

How do I programmatically set a partition-key to every instance of a class that I send?
For instance, If I send a Personinstance, then I want to set the partition-key to be person.getId().
class Person {
String id;
public Person(String id) {
this.id = id;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
#Override
public String toString() {
return "Person{" +
"id='" + id + '\'' +
'}';
}
}
#EnableBinding(Source.class)
public class SpringCloudStreamKinesisProducerApplication {
#InboundChannelAdapter(Source.OUTPUT)
public Person source() {
return new Person("my-id-123");
}
}
You can use the following property to set the partition key:
spring.cloud.stream.bindings.output.producer.partitionKeyExpression=payload.id
That will ensure that any Person instance that you are producing will be sent to the corresponding partition on the destination.

Resources