Spring MVC + Hibernate one to one mapping - spring

I am trying to develop an application using spring mvc and hibernate.
I have following entity classes
Employee
EmployeePeronellDetails
EmployeeSallaryDetails
EmployeeProfesionalDetails
I have an integer employeeID as a primary key in employee table which further acts as foreign key in other three tables
I have created 4 different forms to fill information to above tables.
4 forms opened one after the other
How my entity classes should look like?
I followed few tutorials they suggested to create Employee class object in other classes.
So after successfully inserting data in employee table. Do I need to save respective Employee object in session?
After this while creating EmployeePeronellDetails bean pass that session's employee object to EmployeePeronellDetails's setter method/constructor.
Below are my employee and EmployeePeronellDetails classes
#Entity
#Table(name="employee")
public class Employee {
#Id
#Column
#GeneratedValue
private int empid;
#Column
private String firstName;
#Column
private String lastName;
#Column
private String email;
#Column
private String password;
#Column
private boolean isAdmin;
#Column
private boolean isActive;
#Column
private boolean isLocked;
//geter setters
========================PersonalDetails class===========================
#Entity
#Table(name="PersonalDetails")
public class PersonalDetails {
#Column
#Id
private int empId;
#Column
private String personalEmail;
#Column
private String mob;
#Column
private String permenantAdress;
#Column
private String currentAddress;
#Column
private String gender;
#Column
private String maritialStatus;
#OneToOne
#JoinColumn(name="empid")
private Employee employee;
Now when I tried to call sessionFactory.getCurrentSession().saveOrUpdate(personalDetails);
It gives
org.hibernate.TransactionException: nested transactions not supported]
Exception.

Related

Want to implement Search function in springboot restapi

So i have two entity classes Employee and Address and they are in #OneToOne Relation I'm able to search a Employee's with different parameter like name,designation,department. But i want to search a employee using address fields like Areaname,pincode, phone etc.. How to implement this functionality i'm currently using JpaRepo with Mysql.
#Entity
public class Employee{
#Id#GeneratedValue(strategy=GenerationType.AUTO)
private int id;
private String Name;
private String Designation;
private String Department;
#OneToOne(cascade=CascadeType.ALL)
private Address address;}
#Entity
public class Address{
private String Streetname;
private String Areaname;
private String City;
private Long pincode;
#Id
private Long phone;
}
try like this:
#Query("FROM Employee AS emp LEFT JOIN emp.address AS adr WHERE adr.areaname= ?1")
public List<Employee > FindAllEmployeeByAreaName(String areaname);

join table and get data based on field value JPA

I have two entities
#Entity
public class Module {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private String name;
private String descr;
#OneToMany(cascade = {CascadeType.ALL})
#JoinColumn(name="ID", referencedColumnName="ID")
private List<Permissions> perms;
}
#Entity
public class Permissions {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Integer id;
private Integer clientId;
private String role;
private Character endorseCreate;
private Character endorseUpdate;
private Character endorseDelete;
private Character endorseView;
I am trying to fetch data by first Module.name and Permissions.clientId and Permissions.role
Something like in sql
select * from Module m, Permissions p where m.id=p.id and p.clientId=1 and p.role='ADMIN'
How can I achieve using JPA, I am using spring data aswell.
Can a method be declared in CRUD Repo provided by spring data?
I think the issue is I am unable to find way to pass values to fetch data.
Any help is greatly appreciated

Spring + hibernate one to one mapping

I am developing web application using spring and hibernate. I am using one to one mapping between two tables employee and PersonelDetails.
below are my bean classes
=======================Employee=====================================
#Entity
#Table(name="employee")
public class Employee {
#Id
#Column
#GeneratedValue
private int empid;
#Column
private String firstName;
#Column
private String lastName;
#Column
private String email;
#Column
private String password;
#Column
private boolean isAdmin;
#Column
private boolean isActive;
#Column
private boolean isLocked;
//getter setters
====================PersonalDetails class====================
#Entity
#Table(name="PersonalDetails")
public class PersonalDetails {
#Column
#Id
private int empid;
#Column
private String personalEmail;
#Column
private String mob;
#Column
private String permenantAdress;
#Column
private String currentAddress;
#Column
private String gender;
#Column
private String maritialStatus;
#MapsId
#OneToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "empid", referencedColumnName = "empid")
#ForeignKey(name="empid")
private Employee employee;
//getter setters
In my application table employee is filled by Admin user while creating new employee after that employyee himself fill personalDetails table by login to his accountCreated by Admin)
Now when I try to send personal details bean to hibernate layer first I have to get the employee bean from employee table then call setEmployee method over personalDetails class and save employee bean in personalDetails and send to hibernate layer for saving in database.
So while getting employee bean from database and again send back through personalDetails bean leads to a performance issue.
Can anyone help here to clarify while saving data in child table(PersonalDetails) is it really mandatory to pass parent object(Employee) ?
=======================code to store personalDetails===============
#RequestMapping(value="addpersonal")
public ModelAndView addPersonalDetails(#ModelAttribute("personalDetails") PersonalDetails personalDetails) {
//personalDetails.setEmpid(1);
personalDetails.setCurrentAddress("niljyoti");
personalDetails.setMob("9405715872");
personalDetails.setPermenantAdress("address");
Employee e = empService.getEmployeebyUserName(uname);
personalDetails.setEmployee(e);
personalDetailsService.addPersonalDetails(personalDetails);
return new ModelAndView("home");
}
On read:
You can change fetch strategy if you are worried.
Based od JPA spec, default fetch type for #OneToOne is EAGER.
By setting fetch = FetchType.LAZY, instead of real PersonalDetails object, an object of a subclass behaving as a proxy is returned. Hence, selecting from employee table starts only after getEmployee is called.
On write:
You need to specify connection between entities, in your model, the only way is the employee field. However, you can specify mappedBy, see answer to this question:
Java: Hibernate #OneToOne mapping

I want to create an entity X

I want to create an entity X with atributes.
Everything is right except the attribute "permissions" :
public class X implements Serializable{
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private Long idNotateur;
#NotEmpty
private String nomNotateur;
#NotEmpty
private String prenomNotateur;
#NotEmpty
private String fonctionNotateur;
#NotEmpty
private String userNotateur;
#NotEmpty
private String passNotateur;
#ManyToOne
#JoinColumn(name="id_poste")
private Poste poste;
#ManyToOne
#JoinColumn(name="id_dir")
private Direction direction;
#OneToMany(mappedBy="notateur")
private Collection<Employe> Employes;
private Collection<Long> permissions;
getters & setters ...
public Collection<Long> getPermissions() {
return permissions;
}
public void setPermissions(Collection<Long> permissions) {
this.permissions = permissions;
}
}
Then I came across the following error: Caused by: org.hibernate.MappingException: Could not determine type for: java.util.Collection, at table: X, for columns: [org.hibernate.mapping.Column(permissions)]
So how to solve it?
I'm using Spring MVC Hibenate

Spring and Hibernate Error -- not-null property references a null or transient value: com.tharaka.model.Employee.designation

im new to Spring and hibernate, i got the error above when trying to persist the transaction data. please try to help this problem
Here's my Entity:
#Entity #NamedQuery(name="Employee.findAll", query="SELECT e FROM Employee e")
public class Employee implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String city;
private String civil;
#Temporal(TemporalType.DATE)
#Column(name="dob", length=11)
private Date dob;
private String email;
private int epf;
private String fname;
private String gender;
private int landtp;
private String lname;
#Temporal(TemporalType.DATE)
#Column(name="salaryincrement", length=11)
//bi-directional many-to-one association to Designation
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name="designation_id", nullable=false)
private Designation designation;
public Employee() { }
#Entity
#NamedQuery(name="Designation.findAll", query="SELECT d FROM Designation d")
public class Designation implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
private String type;
//bi-directional many-to-one association to Employee
#OneToMany(mappedBy="designation")//, cascade=CascadeType.ALL
private List<Employee> employees;
public Designation() {
}
this is my Entity class,
Entities have a getters ans setters
designation is set nullable = false. However employees variable isn't initialized in Designation. So, you'll have to initialize as
#OneToMany(mappedBy="designation")//, cascade=CascadeType.ALL
private List<Employee> employees = new LinkedList<>();
I'm not sure that you can go with primitive type int as your Id - you should probably use Integer - because int has default zero value and cannot be null, your new record can be rather seen as a detached entity with Id ZERO and not as a transient one.
The same mistake is in Designation class.
See Primitive or wrapper for hibernate primary keys

Resources