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();
}
}
Related
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
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.
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 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;
}
...
}
hello i'm trying to learn one to many mapping but i really having trouble with hibernate. I was able to persist to database but when trying to apply one to many relationship it doesn't persist to DB and also doesn't display the relationship when viewing the response body in postman. I really need help been on this problem since yesterday morning. I have looked on tutorials on youtube and on internet but every tutorial seem basic and when applying same idea no success. I have an entity person and another entity organization. A person can belong up to one organization but different persons can belong to the same organization. So my approach was using a one to many relationship.
Below is my entity of Organization:
#Entity
#Table(name="organization")
public class Organization {
#Id
#Column(name="org_Id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
private String name, description;
#OneToMany(/*fetch = FetchType.EAGER, cascade = CascadeType.ALL*/)
#JoinTable(joinColumns = #JoinColumn(name="org_Id"),
inverseJoinColumns = #JoinColumn(name="person_Id"))
// #JsonIgnore
//#JoinColumn(name="org_Id")
private Collection<Person> personCollection = new ArrayList<Person>();
public Collection<Person> getPersonCollection() {
return personCollection;
}
public void setPersonCollection(Collection<Person> personCollection) {
this.personCollection = personCollection;
}
private Address address;
public Organization() {}
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
}
And below is my Person entity:#Entity
#Table(name = "Person")
public class Person {
#Id
#Column(name="person_Id")
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column(name="Email",unique = true)
private String email;
#Column(name="FirstName")
private String first_name;
#Column(name="LastName")
private String last_name;
#Column(name="Description")
private String description;
//#Embedded
private Address address;
#ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL)
#JsonIgnore
private Organization organization;
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
public Person() {}
public Address getAddress() {
return address;
}
public void setAddress(Address address) {
this.address = address;
}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
when trying to create person. Below is my create method:
public Person createPerson(String f_name, String l_name, String email, String city, String state,
String zipCode, String street, String description, Long id) {
Person person = null;
//f_name, l_name, email are required parameters if empty return null and throws an exception..
if(f_name.isEmpty() || l_name.isEmpty() || email.isEmpty()) {
return person;
}
else {
Session session = null;
Transaction transaction = null;
try {
session = sessionFactory.openSession();
transaction = session.beginTransaction();
person = new Person();
person.setFirst_name(f_name);
person.setLast_name(l_name);
person.setEmail(email);
person.setDescription(description);
Address address = new Address();
address.setStreet(street);
address.setZipCode(zipCode);
address.setState(state);
address.setCity(city);
person.setAddress(address);
/* checks to see if id of organization exist if so add to list if not don't do anything.*/
if(id!=null) {
Organization organization = session.get(Organization.class, id);
if (organization != null) {
/* adds id of organization to person table and vice versa.*/
person.setOrganization(organization);
organization.getPersonCollection().add(person);
} else {
//do nothing
}
}
session.save(person);
transaction.commit();
} catch (HibernateException ex) {
if (transaction != null)
transaction.rollback();
ex.printStackTrace();
} finally {
if (session != null)
session.close();
}
return person;
}
}
I am able to create both person and organization and persist to database. But when i try to add an organization to a person Row in database i cannot add the relationship(verified when i tried looking up database itself) and also no response as i get a lazy initialization collection error as well. Please has anyone encountered this problem
I just executed the code snippet you gave in hibernate with the following simplified structure which works perfectly fine. You should start from here and modify as per your needs.
Entity
#Table(name="organization")
public class Organization {
#Id
#Column(name="org_Id")
private long id;
private String name, description;
#OneToMany(cascade = CascadeType.ALL)
private Collection<Person> personCollection = new ArrayList<Person>();
public Collection<Person> getPersonCollection() {
return personCollection;
}
public void setPersonCollection(Collection<Person> personCollection) {
this.personCollection = personCollection;
}
public Organization() {}
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 String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
and
#Entity
#Table(name = "Person")
public class Person {
#Id
#Column(name="person_Id")
private long id;
#Column(name="Email",unique = true)
private String email;
#Column(name="FirstName")
private String first_name;
#Column(name="LastName")
private String last_name;
#Column(name="Description")
private String description;
#ManyToOne()
private Organization organization;
public Organization getOrganization() {
return organization;
}
public void setOrganization(Organization organization) {
this.organization = organization;
}
public Person() {}
public long getId() {
return id;
}
public void setId(long id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getFirst_name() {
return first_name;
}
public void setFirst_name(String first_name) {
this.first_name = first_name;
}
public String getLast_name() {
return last_name;
}
public void setLast_name(String last_name) {
this.last_name = last_name;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
}
EDIT : The CascadeType.ALL from Person side of the relationship has been moved to the Organization side of the relationship.Because you want when organization is deleted Person should also get deleted, but not the other way round.