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.
Related
I am trying to persist a user object that has a many-to-many relationship with role objects.
When I save my user, I get the list of a role for that user, but in my ResponseEntity object I got an empty list of roles
My entities
#Entity
#Table(name = "RoleUtilisateur")
public class RoleEntite {
#Id
#Column(name = "role_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String nom;
public RoleEntite() {
super();
// TODO Auto-generated constructor stub
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
}
#Entity
#Table(name = "Utilisateurs")
public class UserEntite {
#Id
#Column(name = "utilisateur_id")
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String nom;
private String prenom;
private String email;
private String password;
// Permettant d'activer ou désactiver le compte
private boolean actived;
// #ManyToMany(cascade = CascadeType.ALL, fetch = FetchType.EAGER)
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(name = "users_roles", joinColumns = #JoinColumn(name = "utilisateur_id"), inverseJoinColumns = #JoinColumn(name = "role_id"))
private List<RoleEntite> roles = new ArrayList<RoleEntite>();
public UserEntite() {
super();
// TODO Auto-generated constructor stub
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
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 isActived() {
return actived;
}
public void setActived(boolean actived) {
this.actived = actived;
}
#JsonIgnore
public List<RoleEntite> getRoles() {
return roles;
}
public void setRoles(List<RoleEntite> roles) {
this.roles = roles;
}
}
My UserServiceImpl
#Service
public class UserServiceImpl implements UserService {
#Autowired
private UserRepository userRepository;
#Autowired
private RoleRepository roleRepository;
#Autowired
private BCryptPasswordEncoder bCryptPasswordEncoder;
#Override
public UserEntite createUser(UserEntite user) {
UserEntite checkUser = userRepository.findByEmail(user.getEmail());
if (checkUser != null)
throw new RuntimeException("L'utilisateur existe deja en Base de donnée !");
user.setPassword(bCryptPasswordEncoder.encode(user.getPassword()));
List<RoleEntite> mesRoles = new ArrayList<RoleEntite>();
if (user.getRoles() != null) {
for (RoleEntite role : user.getRoles()) {
RoleEntite unRole = roleRepository.findByNom(role.getNom());
mesRoles.add(unRole);
}
user.setRoles(mesRoles);
}
UserEntite newUser = userRepository.save(user);
return newUser;
}
}
My DTO
public class UserRequest {
private String nom;
private String prenom;
private String email;
private String password;
#NotNull(message = "Ce champ ne doit etre null !")
private boolean actived;
private List<RoleEntiteRequest> roles;
public UserRequest() {
super();
// TODO Auto-generated constructor stub
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
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 isActived() {
return actived;
}
public void setActived(boolean actived) {
this.actived = actived;
}
public List<RoleEntiteRequest> getRoles() {
return roles;
}
public void setRoles(List<RoleEntiteRequest> roles) {
this.roles = roles;
}
}
public class UserResponse {
private Long id;
private String nom;
private String prenom;
private String email;
boolean actived;
private List<RoleEntiteResponse> roles = new ArrayList<RoleEntiteResponse>();
public UserResponse() {
super();
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public boolean isActived() {
return actived;
}
public void setActived(boolean actived) {
this.actived = actived;
}
public List<RoleEntiteResponse> getRole() {
return roles;
}
public void setRole(List<RoleEntiteResponse> role) {
this.roles = role;
}
}
My controller
#RequestMapping(value="users", method = RequestMethod.POST, produces = "application/json", consumes = "application/json")
public ResponseEntity<UserResponse> saveUser(#Valid #RequestBody UserRequest userRequest) throws Exception {
ModelMapper modelMapper = new ModelMapper();
UserEntite userDto = modelMapper.map(userRequest, UserEntite.class);
UserEntite createUser = userService.createUser(userDto);
int id = createUser.getId().intValue();
UserResponse userResponse = modelMapper.map(createUser, UserResponse.class);
return new ResponseEntity<UserResponse>(userResponse, HttpStatus.CREATED);
}
My problem is when I call my rest API in postman I get the UserResponseEntite with a UserResponse containing an empty role list. But the createUser variable contains a list of roles. When I map this object to UserResponse class, I get an empty role list. Can you help me, please?
I have a application written in Spring, Hibernate and SpringBoot,
I have 2 entities class with one to many mapping,
Here are my LeadUserDb entity class
#Entity
#Table(name="lead_user_db")
#NamedQuery(name="LeadUserDb.findAll", query="SELECT l FROM LeadUserDb l")
public class LeadUserDb implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
#Column(name="branchcode")
private String branchcode;
#Column(name="reporting_level")
private int reportingLevel;
//bi-directional many-to-one association to UserBasicDetailsDb
#ManyToOne
#JoinColumn(name="email_Id")
private UserBasicDetailsDb userBasicDetailsDb;
public LeadUserDb() {
}
public String getBranchcode() {
return this.branchcode;
}
public void setBranchcode(String branchcode) {
this.branchcode = branchcode;
}
public int getReportingLevel() {
return this.reportingLevel;
}
public void setReportingLevel(int reportingLevel) {
this.reportingLevel = reportingLevel;
}
public UserBasicDetailsDb getUserBasicDetailsDb() {
return this.userBasicDetailsDb;
}
public void setUserBasicDetailsDb(UserBasicDetailsDb userBasicDetailsDb) {
this.userBasicDetailsDb = userBasicDetailsDb;
}
And This is my UserBasicDetailsDb Entity Class
#Entity
#Table(name="user_basic_details_db")
public class UserBasicDetailsDb implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private String email;
private String address;
private String city;
private String dob;
private String mobile;
private String name;
private String pan;
private String pincode;
private String state;
#OneToMany(mappedBy="userBasicDetailsDb")
private List<LeadUserDb> leadUserDbs;
public UserBasicDetailsDb() {
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
public String getAddress() {
return this.address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCity() {
return this.city;
}
public void setCity(String city) {
this.city = city;
}
public String getDob() {
return this.dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getMobile() {
return this.mobile;
}
public void setMobile(String mobile) {
this.mobile = mobile;
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getPan() {
return this.pan;
}
public void setPan(String pan) {
this.pan = pan;
}
public String getPincode() {
return this.pincode;
}
public void setPincode(String pincode) {
this.pincode = pincode;
}
public String getState() {
return this.state;
}
public void setState(String state) {
this.state = state;
}
public List<LeadUserDb> getLeadUserDbs() {
return this.leadUserDbs;
}
public void setLeadUserDbs(List<LeadUserDb> leadUserDbs) {
this.leadUserDbs = leadUserDbs;
}
public LeadUserDb addLeadUserDb(LeadUserDb leadUserDb) {
getLeadUserDbs().add(leadUserDb);
leadUserDb.setUserBasicDetailsDb(this);
return leadUserDb;
}
public LeadUserDb removeLeadUserDb(LeadUserDb leadUserDb) {
getLeadUserDbs().remove(leadUserDb);
leadUserDb.setUserBasicDetailsDb(null);
return leadUserDb;
}
what i want to achieve is to create a query like this one
SELECT a.branchcode as branchCode,b.name FROM lead_user_db a
inner join user_basic_details_db b
where b.email = a.email_id and a.reporting_level = 3
here is what I have written my Repository class
public interface GetUserList extends CrudRepository<LeadUserDb, Integer> {
#Query(value = "SELECT a.id, a.branchcode as branchCode,b.name as name,a.reporting_level,a.email_id FROM lead_user_db a\n" +
"inner join user_basic_details_db b\n" +
"where b.email = a.email_id and a.reporting_level = ?1", nativeQuery = true)
List<LeadUserDb> findByReportingLevel(int reportingLevel);
}
and this is how I am calling it
UserBasicDetailsDb details = GetUserList.findByReportingLevel(3);
NOTE
Getting a new error Cannot determine value type from string test#dev.com
I am getting a hell lot of data, and the actual output have only 2 records
My question is how can i fetch the list of user based on reportingLevel
Any help would be appreciated
professionals!
I have a question. What is a better idea to connect 2 tables in spring boot via ID? As an example: we have 2 tables client and books. Each client can borrow a book and the status of book will be changed.
I know how to make it in DB using SQL. But the question is, how to do this in jpa/hibernate.
I have an error of ManyToMany or OneToMany.....
#Entity
public class Book implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#TableGenerator(name = "BOOK_GEN", allocationSize = 1)
#Id
#GeneratedValue(generator = "BOOK_GEN")
private int id;
private String book_name;
private String ISBN;
private String publish_year;
private String publisher;
private Boolean status;
#OneToMany(mappedBy="book" ,cascade=CascadeType.ALL , fetch = FetchType.LAZY)
private Collection<Client> authors =new ArrayList<Client>();
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBook_name() {
return book_name;
}
public void setBook_name(String book_name) {
this.book_name = book_name;
}
public String getISBN() {
return ISBN;
}
public void setISBN(String iSBN) {
ISBN = iSBN;
}
public String getPublish_year() {
return publish_year;
}
public void setPublish_year(String publish_year) {
this.publish_year = publish_year;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Collection<Author> getAuthors() {
return authors;
}
public void setClients(Collection<Client> clients) {
this.clients = clients;
}}
#Entity
public class Client implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#TableGenerator(name = "CLT_GEN", allocationSize = 1)
#Id
#GeneratedValue(generator = "CLT_GEN")
private int id;
private Boolean bookedstatus;
private Boolean bookstatus;
#ManyToOne(fetch = FetchType.LAZY)
private Book book;
private String name ;
private String surname;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Boolean getBookedstatus() {
return bookedstatus;
}
public void setBookedstatus(Boolean bookedstatus) {
this.bookedstatus = bookedstatus;
}
public Boolean getBookstatus() {
return bookstatus;
}
public void setBookstatus(Boolean bookstatus) {
this.bookstatus = bookstatus;
}
}
Since you have mentioned "A client can borrow a book", one-to-one mapping should work the best for you. Please refer to the below code. Also you didn't mention the error you are facing with your current implementation.
#Entity
public class Book implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#TableGenerator(name = "BOOK_GEN", allocationSize = 1)
#Id
#GeneratedValue(generator = "BOOK_GEN")
private int id;
private String book_name;
private String ISBN;
private String publish_year;
private String publisher;
private Boolean status;
#OneToOne(fetch = FetchType.LAZY, mappedBy = "book", cascade = CascadeType.ALL)
private Collection<Client> authors;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getBook_name() {
return book_name;
}
public void setBook_name(String book_name) {
this.book_name = book_name;
}
public String getISBN() {
return ISBN;
}
public void setISBN(String iSBN) {
ISBN = iSBN;
}
public String getPublish_year() {
return publish_year;
}
public void setPublish_year(String publish_year) {
this.publish_year = publish_year;
}
public String getPublisher() {
return publisher;
}
public void setPublisher(String publisher) {
this.publisher = publisher;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Collection<Client> getAuthors() {
return authors;
}
public void setAuthors(Collection<Client> authors) {
this.authors = authors;
}
}
#Entity
public class Client implements java.io.Serializable {
private static final long serialVersionUID = 1L;
#TableGenerator(name = "CLT_GEN", allocationSize = 1)
#Id
#GeneratedValue(generator = "CLT_GEN")
private int id;
private Boolean bookedstatus;
private Boolean bookstatus;
#OneToOne(fetch = FetchType.LAZY)
#PrimaryKeyJoinColumn
private Book book;
private String name ;
private String surname;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public Book getBook() {
return book;
}
public void setBook(Book book) {
this.book = book;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSurname() {
return surname;
}
public void setSurname(String surname) {
this.surname = surname;
}
public Boolean getBookedstatus() {
return bookedstatus;
}
public void setBookedstatus(Boolean bookedstatus) {
this.bookedstatus = bookedstatus;
}
public Boolean getBookstatus() {
return bookstatus;
}
public void setBookstatus(Boolean bookstatus) {
this.bookstatus = bookstatus;
}
}
I want a Bi-Directional mapping on my 2 Entities(PersonDetail,
PassportDetail) but it seems that it doesn't work fine. I want that
PersonDetail has a PassportId and PassportDetail has a PersonId as well.
My PersonDetail java Code
#Entity
#Table(name="persondetail")
public class PersonDetail {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="person_id")
private int id;
#Column(name="person_name")
private String name;
#Column(name="person_phone")
private long phone;
#OneToOne(mappedBy="person",cascade=CascadeType.ALL)
#JoinColumn(name="passport_id")
private PassportDetail passport;
public PassportDetail getPassport() {
return passport;
}
public void setPassport(PassportDetail passport) {
this.passport = passport;
}
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 long getPhone() {
return phone;
}
public void setPhone(long phone) {
this.phone = phone;
}
#Column(name="passport_id")
private int passort_id;
public int getPassort_id() {
return passort_id;
}
public void setPassort_id(int passort_id) {
this.passort_id = passort_id;
}
}
Here is my PassportDetail Java Code
#Entity
#Table(name="PassportDetail")
public class PassportDetail {
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="passport_id")
private int id;
#Column(name="passport_number")
private String passportNumber;
#Column(name="country_name")
private String country;
#Column(name="issue_date")
#Temporal(TemporalType.DATE)
private Date date;
#OneToOne
#JoinColumn(name="person_id")
private PersonDetail person;
public String getPassportNumber() {
return passportNumber;
}
public void setPassportNumber(String passportNumber) {
this.passportNumber = passportNumber;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public PersonDetail getPerson() {
return person;
}
public void setPerson(PersonDetail person) {
this.person = person;
}
}
Here is the Output in MySql
Here is the Output of Both table as you can clearly see the problem i.e PersonDetail has a column named passport_id but it dosesn't have any value
Here is the insertion code
public class MappingMain {
public static void main(String[] args) {
PersonDetail person=new PersonDetail();
PassportDetail passport = new PassportDetail();
SimpleDateFormat sdf=new SimpleDateFormat("yyyy-mm-dd");
person.setName("Ankit");
person.setPhone(790148565);
passport.setCountry("india");
try {
passport.setDate(sdf.parse("2018-04-15"));
}
catch(Exception e)
{
}
passport.setPassportNumber("QUJMZ123");
passport.setPerson(person);
person.setPassport(passport);
PersonDao dao=new PersonDao();
dao.save(person);
}
Here is the DAO class
public class MappingDao {
SessionFactory sf=Util.getSessionFactory();
public void save(UserDemo user)
{
Session session=sf.openSession();
session.beginTransaction();
session.save(user);
session.getTransaction().commit();
session.close();
}
}
I want make a case, when user is authenticated by Spring Security and then he fill adres form I would like to automatically updated a foreign key column "adres_id" in user table. Please give me a tip how implement this in the most popular way
I how somethig like this
Address Table:
User Table:
Adres
#Entity
#Table(name="adres")
public class Adres {
#Id
#GeneratedValue(strategy = GenerationType.AUTO )
int id;
#Column(name="country", nullable=false)
private String country;
private String street;
private String postcode;
private String telephone;
private String pesel;
#OneToOne(mappedBy ="adres")
private User user;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getPostcode() {
return postcode;
}
public void setPostcode(String postcode) {
this.postcode = postcode;
}
public String getTelephone() {
return telephone;
}
public void setTelephone(String telephone) {
this.telephone = telephone;
}
public String getPesel() {
return pesel;
}
public void setPesel(String pesel) {
this.pesel = pesel;
}
public String getStreet() {
return postcode;
}
public void setStreet(String street) {
this.street = street;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
}
User
#Entity
#Table(name="users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO )
int id;
#Column(name="username", nullable=false)
private String username;
private String password;
private String email;
private Boolean enabled;
#OneToOne(cascade = CascadeType.ALL)
private Adres adres;
public Boolean getEnabled() {
return enabled;
}
public void setEnabled(Boolean enabled) {
this.enabled = enabled;
}
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
}
AdresDAO
#Repository
#Transactional
public class AdresDAOImpl implements AdresDAO{
#Autowired
SessionFactory sessionFactory;
public void addAdres(Adres adres) {
sessionFactory.getCurrentSession().save(adres);
}
public List<Adres> listAdres() {
return sessionFactory.getCurrentSession().createQuery("from Adres order by id").list();
}
public void removeAdres(int id) {
Adres adres = (Adres) sessionFactory.getCurrentSession().load(
Adres.class, id);
if (null != adres) {
sessionFactory.getCurrentSession().delete(adres);
}
}
public Adres getAdres(int id) {
return (Adres)sessionFactory.getCurrentSession().get(Adres.class, id);
}
public void editAdres(Adres adres) {
sessionFactory.getCurrentSession().update(adres);
}
}
AdresService
#Service
public class AdresServiceImpl implements AdresService{
#Autowired
AdresDAO adresDAO;
#Transactional
public void addAdres(Adres adres) {
adresDAO.addAdres(adres);
}
#Transactional
public void editAdres(Adres adres) {
adresDAO.editAdres(adres);
}
#Transactional
public List<Adres> listAdres() {
return adresDAO.listAdres();
}
#Transactional
public void removeAdres(int id) {
adresDAO.removeAdres(id);
}
#Transactional
public Adres getAdres(int id) {
return adresDAO.getAdres(id);
}
}
User unidirectional relation between User and Address if Address object does not supposed to know about its owner (generally it does not). I would prefer user id in Address table if a User have more than one Address (one-to-many relation).
But for your question you may design like that,
public class User{
...
#OneToOne(CascadeType.REMOVE)//this is for to remove address when user is removed
#JoinColumn(name="HOME_ADDRESS_ID")
private Address address;
...
}
and
public class Address {
#Id
#GeneratedValue(strategy = GenerationType.AUTO )
int id;
#Column(name="country", nullable=false)
private String country;
private String street;
private String postcode;
private String telephone;
private String pesel;
//no user object here
public int getId() {
return id;
}
...
}