Password and username in distinct collections (Spring security) - java

I'm trying to implement authentication with Spring Security and my problem is that I'm using a MongoDB base where the username and the associated password are in two distinct collections. So when I implement UserDetails, I can't return the password properly. Here is what I've tried:
package com.example.springmongo.user;
import java.util.Collection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.annotation.Id;
import org.springframework.data.mongodb.core.mapping.Document;
import org.springframework.data.mongodb.core.mapping.Field;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
#Document(collection = "users")
public class User implements UserDetails {
/**
*
*/
private static final long serialVersionUID = -2217225560457250699L;
#Autowired
private UserPassService userPassService;
#Id
private String id;
#Field(value = "iduser")
private Long iduser;
#Field(value = "name_complete")
private String name_complete;
#Field(value = "mail")
private String mail;
#Field(value = "active")
private Double active;
#Field(value = "creationDate")
private String creationDate;
#Field(value = "last_login")
private String last_login;
public User() {
super();
}
public User(String id, Long iduser, String name_complete, String mail, Double active, String creationDate, String last_login) {
super();
this.id = id;
this.iduser = iduser;
this.name_complete = name_complete;
this.mail = mail;
this.active = active;
this.creationDate = creationDate;
this.last_login = last_login;
}
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public Long getIduser() {
return iduser;
}
public void setIduser(Long iduser) {
this.iduser = iduser;
}
public String getName_complete() {
return name_complete;
}
public void setName_complete(String name_complete) {
this.name_complete = name_complete;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public Double getActive() {
return active;
}
public void setActive(Double active) {
this.active = active;
}
public String getCreationDate() {
return creationDate;
}
public void setCreationDate(String creationDate) {
this.creationDate = creationDate;
}
public String getLast_login() {
return last_login;
}
public void setLast_login(String last_login) {
this.last_login = last_login;
}
#Override
public String toString() {
return "name: " + this.name_complete + ", mail: " + this.mail + ", id: " + this.id;
}
#Override
public Collection<? extends GrantedAuthority> getAuthorities() {
// TODO Auto-generated method stub
return null;
}
#Override
public String getPassword() {
return this.userPassService.getUserPassword(this.iduser);
}
#Override
public String getUsername() {
return this.getMail();
}
#Override
public boolean isAccountNonExpired() {
if (this.getActive() != null && this.getActive().equals(1.0)) {
return true;
}
return false;
}
#Override
public boolean isAccountNonLocked() {
if (this.getActive() != null && this.getActive().equals(1.0)) {
return true;
}
return false;
}
#Override
public boolean isCredentialsNonExpired() {
if (this.getActive() != null && this.getActive().equals(1.0)) {
return true;
}
return false;
}
#Override
public boolean isEnabled() {
if (this.getActive() != null && this.getActive().equals(1.0)) {
return true;
}
return false;
}
}
Unfortunately, I can't access my UserPassService from an entity like this. So how can I access the password ?
Thanks in advance !

You cant use #Autowired on spring components in entity class as a field. Use like this ;
private transient UserPassService userPassService;
and add setter method of this ;
#Autowired
public void setUserPassService(UserPassService userPassService) {
this.userPassService = userPassService;
}
Beaware of creatation of Entity class with new is making this service is null. If you create with new , call setUserPassService method with autowired object of UserPassService.

Related

com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `response` out of START_ARRAY token

I keep getting this response when im trying to execute my retrofit call for this reseponse:
package retrofit.responses;
import java.util.HashMap;
import java.util.Map;
import javax.annotation.Generated;
import com.fasterxml.jackson.annotation.JsonAnyGetter;
import com.fasterxml.jackson.annotation.JsonAnySetter;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
#JsonInclude(JsonInclude.Include.NON_NULL)
#JsonPropertyOrder({
"id",
"version",
"createdDate",
"modifiedDate",
"rie",
"line1",
"line2",
"line3",
"line4",
"line5",
"county",
"postCode",
"country",
"primary",
"accomodationStatus",
"addressType",
"effectiveFrom",
"effectiveTo",
"secured"
})
#Generated("jsonschema2pojo")
public class ReferralResponse {
#JsonProperty("id")
private Object id;
#JsonProperty("version")
private Integer version;
#JsonProperty("createdDate")
private Object createdDate;
#JsonProperty("modifiedDate")
private Object modifiedDate;
#JsonProperty("rie")
private Boolean rie;
#JsonProperty("line1")
private String line1;
#JsonProperty("line2")
private Object line2;
#JsonProperty("line3")
private Object line3;
#JsonProperty("line4")
private String line4;
#JsonProperty("line5")
private Object line5;
#JsonProperty("county")
private Object county;
#JsonProperty("postCode")
private String postCode;
#JsonProperty("country")
private Object country;
#JsonProperty("primary")
private Boolean primary;
#JsonProperty("accomodationStatus")
private AccomodationStatus accomodationStatus;
#JsonProperty("addressType")
private Object addressType;
#JsonProperty("effectiveFrom")
private Long effectiveFrom;
#JsonProperty("effectiveTo")
private Object effectiveTo;
#JsonProperty("secured")
private Boolean secured;
#JsonIgnore
private Map<String, Object> additionalProperties = new HashMap<String, Object>();
#JsonProperty("id")
public Object getId() {
return id;
}
#JsonProperty("id")
public void setId(Object id) {
this.id = id;
}
#JsonProperty("version")
public Integer getVersion() {
return version;
}
#JsonProperty("version")
public void setVersion(Integer version) {
this.version = version;
}
#JsonProperty("createdDate")
public Object getCreatedDate() {
return createdDate;
}
#JsonProperty("createdDate")
public void setCreatedDate(Object createdDate) {
this.createdDate = createdDate;
}
#JsonProperty("modifiedDate")
public Object getModifiedDate() {
return modifiedDate;
}
#JsonProperty("modifiedDate")
public void setModifiedDate(Object modifiedDate) {
this.modifiedDate = modifiedDate;
}
#JsonProperty("rie")
public Boolean getRie() {
return rie;
}
#JsonProperty("rie")
public void setRie(Boolean rie) {
this.rie = rie;
}
#JsonProperty("line1")
public String getLine1() {
return line1;
}
#JsonProperty("line1")
public void setLine1(String line1) {
this.line1 = line1;
}
#JsonProperty("line2")
public Object getLine2() {
return line2;
}
#JsonProperty("line2")
public void setLine2(Object line2) {
this.line2 = line2;
}
#JsonProperty("line3")
public Object getLine3() {
return line3;
}
#JsonProperty("line3")
public void setLine3(Object line3) {
this.line3 = line3;
}
#JsonProperty("line4")
public String getLine4() {
return line4;
}
#JsonProperty("line4")
public void setLine4(String line4) {
this.line4 = line4;
}
#JsonProperty("line5")
public Object getLine5() {
return line5;
}
#JsonProperty("line5")
public void setLine5(Object line5) {
this.line5 = line5;
}
#JsonProperty("county")
public Object getCounty() {
return county;
}
#JsonProperty("county")
public void setCounty(Object county) {
this.county = county;
}
#JsonProperty("postCode")
public String getPostCode() {
return postCode;
}
#JsonProperty("postCode")
public void setPostCode(String postCode) {
this.postCode = postCode;
}
#JsonProperty("country")
public Object getCountry() {
return country;
}
#JsonProperty("country")
public void setCountry(Object country) {
this.country = country;
}
#JsonProperty("primary")
public Boolean getPrimary() {
return primary;
}
#JsonProperty("primary")
public void setPrimary(Boolean primary) {
this.primary = primary;
}
#JsonProperty("accomodationStatus")
public AccomodationStatus getAccomodationStatus() {
return accomodationStatus;
}
#JsonProperty("accomodationStatus")
public void setAccomodationStatus(AccomodationStatus accomodationStatus) {
this.accomodationStatus = accomodationStatus;
}
#JsonProperty("addressType")
public Object getAddressType() {
return addressType;
}
#JsonProperty("addressType")
public void setAddressType(Object addressType) {
this.addressType = addressType;
}
#JsonProperty("effectiveFrom")
public Long getEffectiveFrom() {
return effectiveFrom;
}
#JsonProperty("effectiveFrom")
public void setEffectiveFrom(Long effectiveFrom) {
this.effectiveFrom = effectiveFrom;
}
#JsonProperty("effectiveTo")
public Object getEffectiveTo() {
return effectiveTo;
}
#JsonProperty("effectiveTo")
public void setEffectiveTo(Object effectiveTo) {
this.effectiveTo = effectiveTo;
}
#JsonProperty("secured")
public Boolean getSecured() {
return secured;
}
#JsonProperty("secured")
public void setSecured(Boolean secured) {
this.secured = secured;
}
#JsonAnyGetter
public Map<String, Object> getAdditionalProperties() {
return this.additionalProperties;
}
#JsonAnySetter
public void setAdditionalProperty(String name, Object value) {
this.additionalProperties.put(name, value);
}
}
and im trying to getID and use that in another call. This is an object that I am trying to turn into an integer an then use that in a seperate call again.
referralResponseResponse = call1.getReferral(token).execute();
int i = (int) referralResponseResponse.body().getId();
System.out.println("Int: " + i);
I should also note the json that I'm using this data from is very large so ive just used jsonpogo to extract this information to a java file and then use the parts that apply to me, I dont imagine i have to set up a java class for every part of the retruned json
Try to add following annotation for your POJO class:
#JsonIgnoreProperties(ignoreUnknown = true)

React & Java: How do I get the accountId (foreign key in the transaction table) to populate in the db?

In the mysql database, the transaction table has successfully had the accountId field added via Java code. However, whenever I add a transaction on the React frontend, the account_id column value in the database is null. What could I be doing wrong?
Account entity:
#Entity
public class Account {
#Id
#GeneratedValue
public long id;
private String username;
private String accountName;
private Date asOfDate;
#OneToMany(mappedBy="account", cascade = {CascadeType.PERSIST, CascadeType.MERGE})
private List<Transaction> transactions = new ArrayList<>();
protected Account() {
}
public Account(String username, String accountName, Date asOfDate) {
super();
this.username = username;
this.accountName = accountName;
this.asOfDate = asOfDate;
}
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 getAccountName() {
return accountName;
}
public void setAccountName(String accountName) {
this.accountName = accountName;
}
public Date getAsOfDate() {
return asOfDate;
}
public void setAsOfDate(Date asOfDate) {
this.asOfDate = asOfDate;
}
public List<Transaction> getTransactions() {
return transactions;
}
public void setTransactions(List<Transaction> transactions) {
this.transactions = transactions;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Account other = (Account) obj;
if (id != other.id)
return false;
return true;
}
}
Transaction entity:
#Entity
public class Transaction {
#Id
#GeneratedValue
private long id;
private String username;
private Date transactionDate;
private String transactionType;
private String depositCategory;
private String withdrawalCategory;
private double transactionAmount;
private String notes;
#ManyToOne
#JoinColumn(name="account_id")
private Account account;
protected Transaction() {
}
public Transaction(String username, Date transactionDate, String transactionType, String depositCategory,
String withdrawalCategory, double transactionAmount, String notes){
super();
this.username = username;
this.transactionDate = transactionDate;
this.transactionType = transactionType;
this.depositCategory = depositCategory;
this.withdrawalCategory = withdrawalCategory;
this.transactionAmount = transactionAmount;
this.notes = notes;
}
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 Date getTransactionDate() {
return transactionDate;
}
public void setTransactionDate(Date transactionDate) {
this.transactionDate = transactionDate;
}
public String getTransactionType() {
return transactionType;
}
public void setTransactionType(String transactionType) {
this.transactionType = transactionType;
}
public String getDepositCategory() {
return depositCategory;
}
public void setDepositCategory(String depositCategory) {
this.depositCategory = depositCategory;
}
public String getWithdrawalCategory() {
return withdrawalCategory;
}
public void setWithdrawalCategory(String withdrawalCategory) {
this.withdrawalCategory = withdrawalCategory;
}
public double getTransactionAmount() {
return transactionAmount;
}
public void setTransactionAmount(double transactionAmount) {
this.transactionAmount = transactionAmount;
}
public String getNotes() {
return notes;
}
public void setNotes(String notes) {
this.notes = notes;
}
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (id ^ (id >>> 32));
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Transaction other = (Transaction) obj;
if (id != other.id)
return false;
return true;
}
}
TransactionJpaResource:
#CrossOrigin(origins = "http://localhost:4200")
#RestController
public class TransactionJpaResource {
#Autowired
private TransactionService transactionService;
#Autowired
private TransactionJpaRepository transactionJpaRepository;
#GetMapping("/jpa/users/{username}/transactions")
public List<Transaction> getAllTransactions(#PathVariable String username) {
return transactionJpaRepository.findByUsername(username);
}
#GetMapping("/jpa/users/{username}/transactions/{id}")
public Transaction getTransaction(#PathVariable String username, #PathVariable long id) {
return transactionJpaRepository.findById(id).get();
}
// DELETE /users/{username}/transactions/{id}
#DeleteMapping("/jpa/users/{username}/transactions/{id}")
public ResponseEntity<Void> deleteTransaction(#PathVariable String username, #PathVariable long id) {
transactionJpaRepository.deleteById(id);
return ResponseEntity.noContent().build();
}
//Edit/Update a Transaction
//PUT /users/{username}/transactions/{id}
#PutMapping("/jpa/users/{username}/transactions/{id}")
public ResponseEntity<Transaction> updateTransaction(
#PathVariable String username,
#PathVariable long id, #RequestBody Transaction transaction){
transaction.setUsername(username);
Transaction transactionUpdated = transactionJpaRepository.save(transaction);
return new ResponseEntity<Transaction>(transaction, HttpStatus.OK);
}
#PostMapping("/jpa/users/{username}/transactions")
public ResponseEntity<Void> createTransaction (
#PathVariable String username, #RequestBody Transaction transaction){
transaction.setUsername(username);
Transaction createdTransaction = transactionJpaRepository.save(transaction);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest()
.path("/{id}").buildAndExpand(createdTransaction.getId()).toUri();
return ResponseEntity.created(uri).build();
}
}
TransactionJpaRepository:
#Repository
public interface TransactionJpaRepository extends JpaRepository<Transaction, Long> {
List<Transaction> findByUsername(String username);
}
Relevant React code from the transactions form:
let username = AuthenticationService.getLoggedInUsername();
fetch(`http://localhost:8080/jpa/users/${username}/transactions`, {
method: "POST",
body: JSON.stringify({
accountId: this.state.accountId,
transactionDate: this.state.transactionDate,
transactionType: this.state.transactionType,
depositCategory: this.state.depositCategory,
withdrawalCategory: this.state.withdrawalCategory,
transactionAmount: this.state.transactionAmount,
notes: this.state.notes,
}),
headers: {
Accept: "application/json",
"Content-Type": "application/json",
},
})
.then((result) => result.text())
.then((data) => console.log(data));
};
...
handleAccountNameChange = (event) => {
this.setState({ accountId: event.target.value });
};
This is what I did to fix the issue:
In React, in the transactions form:
fetch(`http://localhost:8080/jpa/users/${username}/transactions`, {
method: "POST",
body: JSON.stringify({
username: this.state.username,
transactionDate: this.state.transactionDate,
transactionType: this.state.transactionType,
depositCategory: this.state.depositCategory,
withdrawalCategory: this.state.withdrawalCategory,
transactionAmount: this.state.transactionAmount,
notes: this.state.notes,
account: ({
id: this.state.accountId,
username: this.state.username,
accountName: this.state.accountName,
asOfDate: this.state.asOfDate
})
}),
In the Account entity:
#Entity
#Table(name = "account")
public class Account {
#Id
#GeneratedValue
public long id;
private String username;
private String accountName;
private Date asOfDate;
#OneToMany(mappedBy = "account", cascade = { CascadeType.PERSIST, CascadeType.ALL, CascadeType.MERGE })
#JsonIgnore
private List<Transaction> transactions = new ArrayList<>();
In the Transaction entity:
#Entity
#Table(name = "transaction")
public class Transaction {
In TransactionJpaResource:
#PostMapping("/jpa/users/{username}/transactions")
public ResponseEntity<String> createTransaction(#PathVariable String username,
#RequestBody Transaction transaction) {
transaction.setUsername(username);
Transaction createdTransaction = transactionJpaRepository.save(transaction);
URI uri = ServletUriComponentsBuilder.fromCurrentRequest().path("/{id}")
.buildAndExpand(createdTransaction.getId()).toUri();
ResponseEntity<Object> build = ResponseEntity.created(uri).build();
int statusCodeValue = build.getStatusCodeValue();
if (build.getStatusCodeValue() == 201) {
return new ResponseEntity<String>("Data has been Inserted Successfully", HttpStatus.OK);
} else {
return new ResponseEntity<String>("Something went wrong", HttpStatus.INTERNAL_SERVER_ERROR);
}
}

How to join multiple tables without relationship

This is my 1st project in Java/Hibernate.
I m trying to join two tables but even after searching a lot, I couldn't find the proper solution to achieve what i want.
Let me explain you what i have currently.
I have two entities:
#Entity
#Table(name = "admin")
public class AdminLogin {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private String firstName;
private String lastName;
private String username;
private String password;
private String status;
private String userRole;
public int getId() {
return id;
}
public void setId(int 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 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 getStatus() {
return status;
}
public void setStatus(String status) {
this.status = status;
}
public String getUserRole() {
return userRole;
}
public void setUserRole(String userRole) {
this.userRole = userRole;
}
}
#Entity
#Table(name = "user_balance_log")
public class UserBalanceLog {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int userId;
private int adminId;
private Float balance;
private String balanceType;
private String message;
#Temporal(javax.persistence.TemporalType.DATE)
private Date dateCreated;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public int getAdminId() {
return adminId;
}
public void setAdminId(int adminId) {
this.adminId = adminId;
}
public Float getBalance() {
return balance;
}
public void setBalance(Float balance) {
this.balance = balance;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public String getBalanceType() {
return balanceType;
}
public void setBalanceType(String balanceType) {
this.balanceType = balanceType;
}
}
I want to join the adminId from User Balance Log Entity to Admin Login Entity.
This is what i have currently.
Session session = this.sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(UserBalanceLog.class, "ubl");
criteria.setProjection(Projections.projectionList().add(Projections.property("balance"),"balance").add(Projections.property("balanceType"),"balanceType").add(Projections.property("message"),"message").add(Projections.property("dateCreated"),"dateCreated"));
criteria.addOrder(Order.desc("id"));
if (parameters.get("userId") != null) {
criteria.add(Restrictions.eq("userId", new Integer(parameters.get("userId"))));
}
if (parameters.get("balanceType") != null) {
criteria.add(Restrictions.eq("balanceType", parameters.get("balanceType")));
}
if (parameters.get("dateCreated") != null) {
criteria.add(Restrictions.eq("dateCreated", parameters.get("dateCreated")));
}
List userBalanceList = criteria.list();
Please guide me.
Thanks
Finally i figured it out myself of course with the help/guidance of #vc73.
This is the updation i had to do in model:
#Entity
#Table(name = "user_balance_log")
public class UserBalanceLog {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
private int userId;
#ManyToOne
#JoinColumn(name="adminId")
private AdminLogin adminId;
private Float balance;
private String balanceType;
private String message;
#Temporal(javax.persistence.TemporalType.DATE)
private Date dateCreated;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public int getUserId() {
return userId;
}
public void setUserId(int userId) {
this.userId = userId;
}
public AdminLogin getAdminId() {
return adminId;
}
public void setAdminId(AdminLogin adminId) {
this.adminId = adminId;
}
public Float getBalance() {
return balance;
}
public void setBalance(Float balance) {
this.balance = balance;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Date getDateCreated() {
return dateCreated;
}
public void setDateCreated(Date dateCreated) {
this.dateCreated = dateCreated;
}
public String getBalanceType() {
return balanceType;
}
public void setBalanceType(String balanceType) {
this.balanceType = balanceType;
}
}
and in the DAO:
Session session = this.sessionFactory.getCurrentSession();
Criteria criteria = session.createCriteria(UserBalanceLog.class, "ubl");
criteria.createAlias("ubl.adminId", "a");
criteria.setProjection(Projections.projectionList().add(Projections.property("balance").as("balance")).add(Projections.property("balanceType").as("balanceType")).add(Projections.property("message").as("message")).add(Projections.property("dateCreated").as("dateCreated")).add(Projections.property("a.username").as("username")));
criteria.addOrder(Order.desc("id"));
if (parameters.get("userId") != null) {
criteria.add(Restrictions.eq("userId", new Integer(parameters.get("userId"))));
}
if (parameters.get("balanceType") != null) {
criteria.add(Restrictions.eq("balanceType", parameters.get("balanceType")));
}
if (parameters.get("dateCreated") != null) {
criteria.add(Restrictions.eq("dateCreated", parameters.get("dateCreated")));
}
criteria.setResultTransformer(Criteria.ALIAS_TO_ENTITY_MAP);
criteria.setFirstResult(start);
criteria.setMaxResults(Pagination.limitPerPage);
List userBalanceList = criteria.list();
I hope it will help someone else.

Hibernate not deleting rows

I am currently developing a Java EE application using hibernate as ORM.
I am using the DAO design pattern. I want to delete a row from the contact table but I don't know why it is not working. When I delete société it works.
I have a relation between société and contact. When a contact has idSociéte=null it is deleted, but if it exist it will not delete it. When I did delete in phpmysadmin it works even if idSociété not null.
#Transactional(readOnly = false)
public class GenericDaoImp<T> implements GenericDao<T> {
#PersistenceContext
private EntityManager em;
protected Class<T> daoType;
public GenericDaoImp() {
Type t = getClass().getGenericSuperclass();
ParameterizedType pt = (ParameterizedType) t;
daoType = (Class) pt.getActualTypeArguments()[0];
}
public EntityManager getEm() {
return em;
}
public void setEm(EntityManager em) {
this.em = em;
}
public Class<T> getDaoType() {
return daoType;
}
public void setDaoType(Class<T> daoType) {
this.daoType = daoType;
}
public void insert(T t) {
// TODO Auto-generated method stub
em.persist(t);
}
public void update(T t) {
// TODO Auto-generated method stub
em.merge(t);
}
public void delete(T t) {
// TODO Auto-generated method stub
Object managed = em.merge(t);
em.remove(managed);
}
public T findById(Class<T> t, int id) {
// TODO Auto-generated method stub
return em.find(daoType, id);
}
public List<T> findAll() {
// TODO Auto-generated method stub
Query query = em.createQuery("SELECT e FROM " + daoType.getName() + " e");
return (List<T>) query.getResultList();
}
}
package biz.picosoft.entity;
#Entity
#Table(name = "Contacte")
public class Contacte implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idContact")
int idContact;
#Column(name = "nom")
String nom;
#Column(name = "mail")
String mail;
#Column(name = "téléphone")
String téléphone;
#Column(name = "adresse")
String adresse;
#ManyToOne
#JoinColumn(name = "société_id")
private Société société;
public Contacte() {
super();
}
public long getIdContact() {
return idContact;
}
public Contacte(String nom, String mail, String téléphone, String adresse, Société société) {
super();
this.nom = nom;
this.mail = mail;
this.téléphone = téléphone;
this.adresse = adresse;
this.société = société;
}
public Contacte(int idContact, String nom, String mail, String téléphone, String adresse, Société société) {
super();
this.idContact = idContact;
this.nom = nom;
this.mail = mail;
this.téléphone = téléphone;
this.adresse = adresse;
this.société = société;
}
public void setIdContact(int idContact) {
this.idContact = idContact;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getMail() {
return mail;
}
public void setMail(String mail) {
this.mail = mail;
}
public String getTéléphone() {
return téléphone;
}
public void setTéléphone(String téléphone) {
this.téléphone = téléphone;
}
public String getAdresse() {
return adresse;
}
public void setAdresse(String adresse) {
this.adresse = adresse;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + (int) (idContact ^ (idContact >>> 32));
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Contacte other = (Contacte) obj;
if (idContact != other.idContact)
return false;
return true;
}
public Société getSociété() {
return société;
}
public void setSociété(Société société) {
this.société = société;
}
}
package biz.picosoft.daoImpl;
#Component
public class ContacteDaoImpl extends GenericDaoImp<Contacte> implements ContacteDao {
}
package biz.picosoft.entity;
import java.io.Serializable;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.FetchType;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToMany;
import javax.persistence.Table;
#Entity(name = "société")
#Table(name="société")
public class Société implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "idSociété")
int idSociété;
#Column(name = "nom")
String nom;
#Column(name = "email")
String email;
#Column(name = "télèphone")
String télèphone;
#Column(name = "adress")
String adress;
#OneToMany (fetch = FetchType.EAGER,mappedBy = "société", cascade = CascadeType.ALL)
private List<Contacte> contacts;
public Société(String nom, String email, String télèphone, String adress) {
super();
this.nom = nom;
this.email = email;
this.télèphone = télèphone;
this.adress = adress;
}
public Société(int idSociété, String nom, String email, String télèphone, String adress) {
super();
this.idSociété = idSociété;
this.nom = nom;
this.email = email;
this.télèphone = télèphone;
this.adress = adress;
this.contacts = contacts;
}
public Société() {
super();
}
public int getIdSociété() {
return idSociété;
}
public void setIdSociété(int idSociété) {
this.idSociété = idSociété;
}
#Column(name = "nom")
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getTélèphone() {
return télèphone;
}
public void setTélèphone(String télèphone) {
this.télèphone = télèphone;
}
public String getAdress() {
return adress;
}
public void setAdress(String adress) {
this.adress = adress;
}
public List<Contacte> getContacts() {
return contacts;
}
public void setContacts(List<Contacte> contacts) {
this.contacts = contacts;
}
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + idSociété;
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Société other = (Société) obj;
if (idSociété != other.idSociété)
return false;
return true;
}
}
when a contact has idSociéte=null it is deleted but if it exist it
will not delete it.
It means if the idSociete is not null and have some value for eg. 123. You need to check if any of the contact have the same idSociete. if it's present with any other contact then your contact will not be deleted as Many contacts can be associated with same société. Try with single contact and a single société associated with it.

Nested JSON data show in a Vaadin grid

I'm new to Java and Vaadin and stuck during display data in a Vaadin grid. I have data in JSON format like:
[
{
"id":1,
"name":"testSiteC",
"accountId":1,
"accountData":{
"id":1,
"name":"testAccountA",
"code":"AC0001",
"salesStaffId":200,
"samplingDate":1493038800000,
"startDate":1493038800000,
"creditPeriod":15,
"cinNo":"testCinNo",
"vatRegistrationNo":"testVatRegistrationNo",
"panNo":"testPanNo",
"serviceTaxRegistrationNo":"testServiceTaxRegistrationNo",
"isActive":true,
"billingType":"testBillingType",
"billingBasis":"cup count basis",
"billingAddress":"billingAddress",
"consigneeAddress":"test",
"clientRelationshipManagerStaffId":2,
"opsManagerId":1,
"serviceTaxId":1,
"createdOn":1483209000000,
"updatedOn":1494949002000
},
"building":"3rd floor",
"locality":"Koramangala",
"city":"Bangalore",
"state":"Karnataka",
"country":"India",
"peopleCount":100,
"staffInCharge":1,
"dailyStartTime":"23:34:23",
"dailyEndTime":"23:34:34",
"createdOn":1493799889000,
"updatedOn":1494945760000,
"isActive":true,
"opsStartDate":1493730000000
}
]
Bean to be nested:
package com.chaipoint.boxc.common.model;
import java.io.Serializable;
import java.sql.Time;
import java.sql.Timestamp;
import java.util.Date;
public class SiteResponse implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private Integer accountId;
private AccountResponse accountData;
private String building;
private String locality;
private String city;
private String state;
private String country;
private Integer peopleCount;
private Integer staffInCharge;
private Time dailyStartTime;
private Time dailyEndTime;
private Date createdOn;
private Timestamp updatedOn;
private Boolean isActive;
private Date opsStartDate;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getAccountId() {
return accountId;
}
public void setAccountId(Integer accountId) {
this.accountId = accountId;
}
public AccountResponse getAccountData() {
return accountData;
}
public void setAccountData(AccountResponse accountData) {
this.accountData = accountData;
}
public String getBuilding() {
return building;
}
public void setBuilding(String building) {
this.building = building;
}
public String getLocality() {
return locality;
}
public void setLocality(String locality) {
this.locality = locality;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Integer getPeopleCount() {
return peopleCount;
}
public void setPeopleCount(Integer peopleCount) {
this.peopleCount = peopleCount;
}
public Integer getStaffInCharge() {
return staffInCharge;
}
public void setStaffInCharge(Integer staffInCharge) {
this.staffInCharge = staffInCharge;
}
public Time getDailyStartTime() {
return dailyStartTime;
}
public void setDailyStartTime(Time dailyStartTime) {
this.dailyStartTime = dailyStartTime;
}
public Time getDailyEndTime() {
return dailyEndTime;
}
public void setDailyEndTime(Time dailyEndTime) {
this.dailyEndTime = dailyEndTime;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public Timestamp getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Timestamp updatedOn) {
this.updatedOn = updatedOn;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public Date getOpsStartDate() {
return opsStartDate;
}
public void setOpsStartDate(Date opsStartDate) {
this.opsStartDate = opsStartDate;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
Bean containing a nested bean
public class SitePantryResponse implements Serializable {
/**
*
*/
private static final long serialVersionUID = 1L;
private Long id;
private String name;
private Integer siteId;
private SiteResponse siteData;
private Integer floorNo;
private Date createdOn;
private Timestamp updatedOn;
private Boolean isActive;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getSiteId() {
return siteId;
}
public void setSiteId(Integer siteId) {
this.siteId = siteId;
}
public SiteResponse getSiteData() {
return siteData;
}
public void setSiteData(SiteResponse siteData) {
this.siteData = siteData;
}
public Integer getFloorNo() {
return floorNo;
}
public void setFloorNo(Integer floorNo) {
this.floorNo = floorNo;
}
public Date getCreatedOn() {
return createdOn;
}
public void setCreatedOn(Date createdOn) {
this.createdOn = createdOn;
}
public Timestamp getUpdatedOn() {
return updatedOn;
}
public void setUpdatedOn(Timestamp updatedOn) {
this.updatedOn = updatedOn;
}
public Boolean getIsActive() {
return isActive;
}
public void setIsActive(Boolean isActive) {
this.isActive = isActive;
}
public static long getSerialversionuid() {
return serialVersionUID;
}
}
So, while displaying data into the grid like table.addColumn(SitePantryResponse::getSiteData::getName).setCaption("Site Name") it throws:
The target type of this expression must be a functional interface` error.
SitePantryResponse::getSiteData::getName
It's not possible to chain method references like that. You can use simple lambda expression instead:
table.addColumn(r -> r.getSideDate().getName()).setCaption("Site Name")
or if you really want to use method references, you can use a helper method which will chain them and return ValueProvider which can be later passed to Grid.addColumn:
<A, B, C> ValueProvider<A, C> chain(Function<A, B> f1, Function<B, C> f2) {
return f1.andThen(f2)::apply;
}
With this you can write:
table.addColumn(chain(SitePantryResponse::getSiteData, SiteResponse::getName)).setCaption("Site Name")
but, as you can see, this makes the code more complicated and longer, so there is no reason to use this approach over simple lambda expression.

Categories

Resources