Consider scenario user has many address.
Address class
Address class
ackage com.sb.basic.model;
import javax.persistence.Entity;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import org.springframework.data.jpa.domain.AbstractPersistable;
@Entity
public class Address extends AbstractPersistable<Long>{
private String city;
private String state;
private String country;
//We will create one transition for userId
private transient Long userId;
@ManyToOne(targetEntity = User.class)
@JoinColumn(name="user_id") //user_id is table column name
private User user;
//Getter Setter
Update User class
private String userId;
private String userName;
private String password;
@OneToMany(targetEntity = Address.class, mappedBy = "user",fetch= FetchType.LAZY ,cascade =CascadeType.ALL)
private Set<Address> address; //Instead of Set(Unordered collection and not allow duplicates) we can use list(ordered and allow duplicate values) as well
Getter and setter;
Create AddressController class
This like normal UserController class
@RequestMapping("/addressList")
public List<Address> addressList(){
return addressService.addressList();
}
Create AddressServiceImpl class
This also like UserSImpl class
@Override
public List<Address> addressList() {
return addressRepository.findAll();
}
Add data to the generated address table.
Then run project
Method - Get
Link - http://localhost:9080/springbootbasic/address/addressList
Priyantha.samaraweera
Method - Get
Link - http://localhost:9080/springbootbasic/address/addressList
Priyantha.samaraweera
No comments:
Post a Comment