I am developing shopping cart web app which have completed up to display product to add cart. I am trying to map every customer (One To One) to cart Entity, cart entity (one to one) to cart item Entity, and cart item entity (Many to One) to Product entity. But I got a 404 error.
Please check my code below.
Mapping plan:
Customer-----one to one------>Cart----one to one---->Cart Item----Many to one--->Product
Customer Entity
package com.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToOne;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
#Entity
public class Customer {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="Cid")
private int customerId;
#Column(name="password")
#NotEmpty(message="Name is mandatory")
private String password;
#Column(name="Email")
#NotEmpty(message="Name is mandatory")
private String email;
#NotEmpty(message="First Name is mandatory")
#Column(name="firstname")
private String firstName;
#NotEmpty(message="Last Name is mandatory")
#Column(name="lastname")
private String lastName;
#Column(name="Mobile")
#NotEmpty(message="Mobile is mandatory")
private String mobile;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="address_id")
private Address delAdderss;
private boolean enabled;
private String role;
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="cart_id")
private Cart cart;
public Cart getCart() {
return cart;
}
public void setCart(Cart cart) {
this.cart = cart;
}
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 getMobile() {
return mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public int getCustomerId() {
return customerId;
}
public void setCustomerId(int name) {
this.customerId = 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;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Address getDelAdderss() {
return delAdderss;
}
public void setDelAdderss(Address delAdderss) {
this.delAdderss = delAdderss;
}
}
Cart Entity
package com.model;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.OneToOne;
#Entity
public class Cart {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int cart_id;
#Column
private double total;
#Column
#OneToOne(cascade=CascadeType.ALL)
#JoinColumn(name="item_id")
private CartItem cartItem;
public int getCart_id() {
return cart_id;
}
public void setCart_id(int cart_id) {
this.cart_id = cart_id;
}
public double getTotal() {
return total;
}
public void setTotal(double total) {
this.total = total;
}
public CartItem getCartItem() {
return cartItem;
}
public void setCartItem(CartItem cartItem) {
this.cartItem = cartItem;
}
}
Cart Item Entity
package com.model;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.OneToOne;
#Entity
public class CartItem {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int item_id;
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="id")
private List<Product> product;
public int getItem_id() {
return item_id;
}
public void setItem_id(int item_id) {
this.item_id = item_id;
}
public List<Product> getProduct() {
return product;
}
public void setProduct(List<Product> product) {
this.product = product;
}
}
Product Entity
package com.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Transient;
import org.springframework.web.multipart.MultipartFile;
#Entity
public class Product {
#Id #GeneratedValue(strategy=GenerationType.AUTO)
private int id;
#Column
private String product_Name;
#Column
private String descripction;
#Column
private int price;
#Column
private Date mfg_Date;
#Transient
private MultipartFile image;
public MultipartFile getImage() {
return image;
}
public void setImage(MultipartFile image) {
this.image = image;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getProduct_Name() {
return product_Name;
}
public void setProduct_Name(String product_Name) {
this.product_Name = product_Name;
}
public String getDescripction() {
return descripction;
}
public void setDescripction(String descripction) {
this.descripction = descripction;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public Date getMfg_Date() {
return mfg_Date;
}
public void setMfg_Date(Date mfg_Date) {
this.mfg_Date = mfg_Date;
}
}
Why are you using cart item entity, According to me it should be Customer one on one with Cart, And a Cart as one to many with Products. I think there is no need for cart items table/entity.
Related
i used optimistic lock by only write #version in entity ..
and it work when version is 0 , so if i updated the entity and the version was 0 it work and do the update and make the version 1 automatically , but once the version is 1 , it wont accept any other update ... what can i do ..
i thought of doing it manually without #version , like compairing the entety version with its value before update if equall do update or else no ... but how to use it using #version
package com.hariri_stocks.models;
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.OneToOne;
import javax.persistence.Table;
import javax.persistence.Version;
#Table
#Entity
public class Estates {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column
private long id;
#Column
private String place;
#Column
private int price;
#Column
private long stocks_num;
#Column
private boolean sold = false;
#Version
private long version;
#OneToOne(mappedBy = "estate_id",fetch = FetchType.EAGER, cascade = CascadeType.ALL )
private SoldEstates sold_estate_id;
public Estates() {
super();
}
public Estates(String place, int price, long stocks_num, SoldEstates sold_estate_id) {
super();
this.place = place;
this.price = price;
this.stocks_num = stocks_num;
this.sold_estate_id = sold_estate_id;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getPlace() {
return place;
}
public void setPlace(String place) {
this.place = place;
}
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public long getStocks_num() {
return stocks_num;
}
public void setStocks_num(long stocks_num) {
this.stocks_num = stocks_num;
}
public long getVersion() {
return version;
}
public void setVersion(long version) {
this.version = version;
}
public boolean isSold() {
return sold;
}
public void setSold(boolean sold) {
this.sold = sold;
}
public SoldEstates getSold_estate_id() {
return sold_estate_id;
}
public void setSold_estate_id(SoldEstates sold_estate_id) {
this.sold_estate_id = sold_estate_id;
}
}
I'm having a 403 forbidden request when requesting POST using postman, get is working perfectly and im not using any of spring security tools just spring boot because i have seen some answers talking about disabling csrf which is not my case because im not using any of spring security.
Here is My Entity class:
package com.example.demo.entity;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.PrePersist;
import javax.persistence.Table;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.Size;
#Entity
#Table(name="clients")
public class Clients {
#Id
#Column(name="phone")
private Long phone;
#NotBlank(message="Required Field")
#Column(name="firstname")
private String firstname;
#NotBlank(message="Required Field")
#Column(name="lastname")
private String lastname;
#NotBlank(message="Required Field")
#Column(name="birthDate")
private String birthDate;
#NotBlank(message="Required Field")
#Column(name="email")
private String email;
#NotBlank(message="Required Field")
#Column(name="addressClient")
private String addressClient;
#NotBlank(message="Required Field")
#Column(name="gender")
private String gender;
#Column(name="inscriptionDate")
private Date inscriptionDate;
#NotBlank(message="Required Field")
#Size(min=8 , message="Password needs to be more than 8 characters")
#Column(name="passwordClient")
private String passwordClient;
public Clients() {
}
public Clients(Long phone, #NotBlank(message = "Required Field") String firstname,
#NotBlank(message = "Required Field") String lastname,
#NotBlank(message = "Required Field") String birthDate, #NotBlank(message = "Required Field") String email,
#NotBlank(message = "Required Field") String addressClient,
#NotBlank(message = "Required Field") String gender, Date inscriptionDate,
#NotBlank(message = "Required Field") #Size(min = 8, message = "Password needs to be more than 8 characters") String passwordClient) {
super();
this.phone = phone;
this.firstname = firstname;
this.lastname = lastname;
this.birthDate = birthDate;
this.email = email;
this.addressClient = addressClient;
this.gender = gender;
this.inscriptionDate = inscriptionDate;
this.passwordClient = passwordClient;
}
#PrePersist
public void newDate() {
this.inscriptionDate=new Date();
}
public Long getPhone() {
return phone;
}
public void setPhone(Long phone) {
this.phone = phone;
}
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 getBirthDate() {
return birthDate;
}
public void setBirthDate(String birthDate) {
this.birthDate = birthDate;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddressClient() {
return addressClient;
}
public void setAddressClient(String addressClient) {
this.addressClient = addressClient;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public Date getInscriptionDate() {
return inscriptionDate;
}
public void setInscriptionDate(Date inscriptionDate) {
this.inscriptionDate = inscriptionDate;
}
public String getPasswordClient() {
return passwordClient;
}
public void setPasswordClient(String passwordClient) {
this.passwordClient = passwordClient;
}
}
And Here s my Repository Interface:
package com.example.demo.repositories;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.stereotype.Repository;
import com.example.demo.entity.Clients;
#Repository
public interface ClientsRepository extends JpaRepository<Clients , Long>{
}
My Controller Class:
package com.example.demo.controllers;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.example.demo.entity.Clients;
import com.example.demo.functions.ClientsFunctionsImpl;
import com.example.demo.repositories.ClientsRepository;
#RestController
public class ClientsController {
#Autowired
private ClientsRepository clientsRepository;
#CrossOrigin("http://localhost:3000")
#GetMapping(path="/clientslist")
public List<Clients> getAllClients(){
return clientsfunctionsimpl.list();
}
#CrossOrigin("http://localhost:3000")
#PostMapping("/clientslist")
public ResponseEntity<Clients> createEmployee(#Valid #RequestBody Clients client) {
Clients client1 = clientsRepository.save(client);
return new ResponseEntity<Clients>(client1,HttpStatus.CREATED);
}
}
Your code is working but I want to add one more thing is that use this type of structure it will prevent SQL injection and improve your creation API response.
#CrossOrigin(origins = "http://localhost:3000")
#PostMapping(value = "/createEmployee")
public ResponseEntity<ClientsMetaModel> createEmployee(#Valid #RequestBody ClintsModel model) {
ClientsMetaModel metaModel = new ClientsMetaModel();
// set all your fields into metamodel by getting it from model
return new ResponseEntity<ClientsMetaModel>(empRepo.save(metaModel), HttpStatus.CREATED);
}
You have to kept your id, token, date all fields into metamodel only and try this.
If this will not work then use #CrossOrigin(/*) as global. Also as #Ananthapadmanabhan said in his answer but I advise you that use model and metamodel concept.
Could you try enabling CORS on all ports and url for your endpoint like :
#CrossOrigin
#PostMapping("/clientslist")
public ResponseEntity<Clients> createEmployee(#Valid #RequestBody Clients client) {
Clients client1 = clientsRepository.save(client);
return new ResponseEntity<Clients>(client1,HttpStatus.CREATED);
}
I guess this is a really simple question, but I am not able to find out any solution! Neither google it.
I am working with Spring Boot JPA repositories, and I have a many to many relation between two tables. Table A --> User, table B --> Role.
The data is already recorded in the database, but how can I get for example all the roles that a specific user has?
I have successfully executed the simple queries. Get all users, get all roles, get user by id, etc. But I cannot get this one.
Any suggestion?
Thank you so much!!
package com.mb.model;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.JoinTable;
import javax.persistence.ManyToMany;
#Entity
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int userId;
private String email;
private String firstName;
private String lastName;
private String password;
private boolean enabled;
private boolean tokenExpired;
#ManyToMany
#JoinTable(name = "user_roles", joinColumns = #JoinColumn(name = "user_userId"), inverseJoinColumns = #JoinColumn(name = "role_roleId"))
private Set<Role> roles;
public User() {
super();
}
public User(String email, String firstName, String lastName, String password) {
super();
this.email = email;
this.firstName = firstName;
this.lastName = lastName;
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 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 boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
public boolean isTokenExpired() {
return tokenExpired;
}
public void setTokenExpired(boolean tokenExpired) {
this.tokenExpired = tokenExpired;
}
public Integer getUserId() {
return userId;
}
public Set<Role> getRoles() {
return roles;
}
public void setRoles(Set<Role> roles) {
this.roles = roles;
}
}
package com.mb.model;
import java.util.Set;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.ManyToMany;
#Entity
public class Role {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private int roleId;
private String name;
#ManyToMany(mappedBy = "roles")
private Set<User> users;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Set<User> getUsers() {
return users;
}
public void setUsers(Set<User> users) {
this.users = users;
}
public int getRoleId() {
return roleId;
}
}
package com.mb.repo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import com.mb.model.Role;
import com.mb.model.User;
public interface IUserRepo extends JpaRepository<User, Integer>{
User findByEmail(String email);
}
package com.mb.repo;
import org.springframework.data.jpa.repository.JpaRepository;
import com.mb.model.Role;
public interface IRoleRepo extends JpaRepository<Role, Integer>{
}
#Autowired
private IUserRepo repo;
User loggedUser = repo.findByEmail(username);
I have stuck on dealing with DB by using hibernate orm in spring mvc environment.
I have some tables; but I'm not gonna tell you my tables(If you want, I will edit this post)
The problem is that when hibernate runs, it generates sql - I can see the sql by configuring "hbm2_ddl auto" - but the sql has invalid identifier.
select newsreplie0_.news_article# as news6_3_4_, newsreplie0_.reply# as reply1_4_,
newsreplie0_.reply# as reply1_4_3_, newsreplie0_.account_account# as account5_4_3_,
newsreplie0_.content as content4_3_, newsreplie0_.dt as dt4_3_,
newsreplie0_.news_article# as news6_4_3_, newsreplie0_.reply_at as reply4_4_3_,
account1_.account# as account1_0_0_, account1_.email as email0_0_,
account1_.passwd as passwd0_0_, accountpro2_.account# as account1_1_1_,
accountpro2_.nickname as nickname1_1_, accountsec3_.account# as account1_2_2_,
accountsec3_.activate_key as activate2_2_2_, accountsec3_.activated as activated2_2_,
accountsec3_.enabled as enabled2_2_, accountsec3_.login_failed as login5_2_2_
from news_reply newsreplie0_
left outer join
cookingstep.account account1_ on newsreplie0_.account_account#=account1_.account#
left outer join
cookingstep.account_profile accountpro2_ on account1_.account#=accountpro2_.account#
left outer join
cookingstep.account_security accountsec3_ on account1_.account#=accountsec3_.account#
where newsreplie0_.news_article#=9
{FAILED after 4 msec}
The above statement is a sql generated by hibernate. And the error is:
java.sql.SQLSyntaxErrorException:
ORA-00904: "NEWSREPLIE0_"."ACCOUNT_ACCOUNT#": Invalid Identifier
In that exception message, there is a column called "ACCOUNT_ACCOUNT#".
It should be just "ACCOUNT#", not following "ACCOUNT_".
So, how to remove the word ?
EDIT:
Thank you all for your reply. I have asked similar question before.
And I checked out that article, it seems the problem was #JoinColumn annotation missing. Now it works out.
Here is my Entities.
Account.java for user information
package com.musicovery12.cookingstep.persistence.model;
import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
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.OneToMany;
import javax.persistence.OneToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.UniqueConstraint;
#Entity
#Table(name="account", catalog="cookingstep", uniqueConstraints= {
#UniqueConstraint(columnNames="email")
})
public class Account implements Serializable{
private static final long serialVersionUID = 1L;
private int accountId;
private String email;
private String password;
private Set<UserRole> userRoles = new HashSet<UserRole>(0);
private AccountProfile profile;
private AccountSecurity security;
private Set<News> newsList;
private Set<NewsReply> newsReplyList;
public Account() {}
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="seq_account")
#SequenceGenerator(name="seq_account", sequenceName="seq_account", allocationSize=1)
#Column(name="account#", unique=true, nullable=false)
public int getAccountId() {
return accountId;
}
public void setAccountId(int accountId) {
this.accountId = accountId;
}
#Column(name="email", unique=true, nullable=false)
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
#Column(name="passwd", nullable=false)
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
#OneToMany(mappedBy="pk.account", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
public Set<UserRole> getUserRoles() {
return userRoles;
}
public void setUserRoles(Set<UserRole> userRoles) {
this.userRoles = userRoles;
}
#OneToOne(mappedBy="account", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
public AccountProfile getProfile() {
return profile;
}
public void setProfile(AccountProfile profile) {
this.profile = profile;
}
#OneToOne(mappedBy="account", fetch=FetchType.EAGER, cascade=CascadeType.ALL)
public AccountSecurity getSecurity() {
return security;
}
public void setSecurity(AccountSecurity security) {
this.security = security;
}
#OneToMany(mappedBy="account", fetch=FetchType.LAZY, cascade=CascadeType.ALL)
public Set<News> getNewsList() {
return newsList;
}
public void setNewsList(Set<News> newsList) {
this.newsList = newsList;
}
#OneToMany(mappedBy="account", fetch=FetchType.LAZY, cascade=CascadeType.ALL)
public Set<NewsReply> getNewsReplyList() {
return newsReplyList;
}
public void setNewsReplyList(Set<NewsReply> newsReplyList) {
this.newsReplyList = newsReplyList;
}
}
and NewsReply.java for news community article's reply list.
package com.musicovery12.cookingstep.persistence.model;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.SequenceGenerator;
import javax.persistence.Table;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
#Entity
#Table(name="news_reply")
public class NewsReply {
private int replyId;
private News news;
private Date date;
private String content;
private Account account;
private int replyAt;
#Id
#GeneratedValue(strategy=GenerationType.SEQUENCE, generator="gen_seq")
#SequenceGenerator(name="gen_seq", sequenceName="gen_seq", allocationSize=1)
#Column(name="reply#", unique=true, nullable=false)
public int getReplyId() {
return replyId;
}
public void setReplyId(int replyId) {
this.replyId = replyId;
}
#Temporal(TemporalType.DATE)
#Column(name="dt")
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
#Column(name="content", nullable=false)
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
#Column(name="reply_at")
public int getReplyAt() {
return replyAt;
}
public void setReplyAt(int replyAt) {
this.replyAt = replyAt;
}
#ManyToOne
public News getNews() {
return news;
}
public void setNews(News news) {
this.news = news;
}
#ManyToOne
#JoinColumn(name="account#", referencedColumnName="account#")
public Account getAccount() {
return account;
}
public void setAccount(Account account) {
this.account = account;
}
}
in NewsReply.java, there was no JoinColumn annotation to point foreing key column name.
Thank you.
#ManyToOne
#JoinColumn(name="account#", referencedColumnName="account#")
public Account getAccount() {
return account;
}
This is the problem, you tell hibernate the table has a technical name of account# what is not allowed.
What you can do is to force hibernate to use that # by defining
#ManyToOne
#JoinColumn(name="`account#`", referencedColumnName="`account#`")
public Account getAccount() {
return account;
}
But this is bad style and you have to do it on the owning-side too.
Why dont you let hibernate create the entitys for you? He is much more precisly!
Hi all i have a small issue with joining two tables using jparepository using #query but i am getting error. please help me with this.
UserAddress.java
package com.surya_spring.example.Model;
import java.io.Serializable;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
#Entity
#Table(name = "user_address")
//#JsonIgnoreProperties({"hibernateLazyInitializer", "handler"})
public class UserAddress implements Serializable {
/**
*
*/
private static final long serialVersionUID = -3570928575182329616L;
/*#ManyToMany(cascade = {CascadeType.ALL},fetch=FetchType.EAGER,mappedBy = "userAddress",targetEntity=UserData.class)*/
#ManyToOne(cascade=CascadeType.ALL)
#JoinColumn(name="user_id")
private UserData userdata;
#Id
#Column(name = "addr_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long addrid;
#Column(name = "dr_no")
#NotNull
private String doorNo;
#Column(name = "strt_name")
#NotNull
private String streetName;
#Column(name = "city")
#NotNull
private String city;
#Column(name = "country")
#NotNull
private String country;
/*#OneToOne(cascade=CascadeType.ALL)
#Column(name="user_id")*/
public UserData getUserdata() {
return userdata;
}
public void setUserdata(UserData userdata) {
this.userdata = userdata;
}
public Long getAddrid() {
return addrid;
}
public void setAddrid(Long addrid) {
this.addrid = addrid;
}
public String getDoorNo() {
return doorNo;
}
public void setDoorNo(String doorNo) {
this.doorNo = doorNo;
}
public String getStreetName() {
return streetName;
}
public void setStreetName(String streetName) {
this.streetName = streetName;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
UserData.java
package com.surya_spring.example.Model;
import java.io.Serializable;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
import lombok.NonNull;
#Entity
#Table(name = "user_data")
public class UserData implements Serializable{
/**
* Serialization ID
*/
private static final long serialVersionUID = 8133309714576433031L;
/*#ManyToMany(targetEntity=UserAddress.class ,cascade= {CascadeType.ALL },fetch=FetchType.EAGER)
#JoinTable(name="userdata",joinColumns= #JoinColumn(name="userid"),inverseJoinColumns = #JoinColumn(name="userid"))
*/
#Id
#Column(name = "user_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long userId;
#Column(name = "user_name")
#NonNull
private String userName;
#Column(name = "user_email")
#NonNull
private String userEmail;
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;
}
}
Repository:
package com.surya_spring.example.Repository;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.surya_spring.example.Model.UserData;
public interface UserDataRepository extends JpaRepository<UserData, Long>{
#Query(" FROM UserData where userId= :id")
public List<UserData> findBySearchTerm(#Param("id") Long id);
}
any one let me know the query to join this both the table to get city name from user_address where user_id=? joining user_data table
If you want to get the city for a user you can do:
#Query("SELECT ua.city FROM UserAddress ua WHERE ua.userdata.userId = ?1")
String findCityByUserId(Long userId);
Note that your entity names are used (like in your java classes) and not the table names in database! You do not have to do the join by yourself as you can use the properties of your domain models to access the related data