JPA Embeddable bidirectional - java

What's the correct way to create bidirectional 1to1 mapping using Embeddable annotation? This one throws error
"EmpId has no persistent id property: Emp.id"
#Entity
public class Per implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "per_id")
private Long id;
#OneToOne
#JoinColumn(name = "per_id", referencedColumnName = "emp_id")
private Emp emp;
}
#Embeddable
public class EmpId implements Serializable {
private static final long serialVersionUID = 1L;
#OneToOne(mappedBy = "emp")
private Per per;
}
#Entity
public class Emp implements Serializable {
#EmbeddedId
private EmpId id;
}
I'd like to operate entities like
per.getEmp();
emp.getId().getPer();

Related

Java JPA - Table per class inheritance - Id collision

I have one Parent class with ID field, and two Child classes. I have applied TABLE PER CLASS inheritance.
Some Rows in these two tables have the same identifiers. (The same Id)
When findAll() of the JpaRepository is called I have org.hibernate.PropertyAccessException
What I can to do to resolve the conflict? I can not to change IDs in these tables, because they have a lot of dependencies and foreign key constraints.
#Entity
#Inheritance(strategy = InheritanceType.TABLE_PER_CLASS)
public abstract class Parent implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#TableGenerator(name = "content_id_generator",
table = "generic_sequences",
pkColumnName = "sequence_name",
valueColumnName = "sequence_value",
pkColumnValue= "content_seq",
allocationSize = 20)
#GeneratedValue(strategy = GenerationType.TABLE, generator = "content_id_generator")
#Column(updatable = false)
private Long id;
#Column(length = 250, nullable = false)
#NotNull
#Size(min = 1, max = 250)
private String title;
...
There are tho child classes Child1 and Child2 extends Parent.
There is another inheritance that dependent from Content.
#Entity
#Table(name = "text_id_changed")
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
#DiscriminatorColumn(name = "type")
public abstract class DependentCalss implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(updatable = false)
private Long id;
...
DependentCalss has two child classes DependentCalssChild1 and DependentCalssChild2.
#Entity
#DiscriminatorValue("DependentCalssChild1")
public class DependentCalssChild1 extends DependentCalss {
private static final long serialVersionUID = 1L;
#ManyToOne
#JoinColumn(name = "child_1_id")
private Child1 child1;
...
AND
#Entity
#DiscriminatorValue("DependentCalssChild2")
public class DependentCalssChild2 extends DependentCalss {
private static final long serialVersionUID = 1L;
#ManyToOne
#JoinColumn(name = "child_2_id")
private Child2 child2;
...
And jpaRepository
#Repository
public interface DependentCalssRepository extends JpaRepository<DependentCalss, Long> {
}
When I call findAll() of DependentCalssRepository I catch org.hibernate.PropertyAccessException that field can not be set etc.
It happens when Child1 and Child2 have the same ID in separate tables.
What can I do to resolve it? I can not change id in tables because of great number dependencies and constraints. Thanks!

How to maintain foreign key relationship in hibernate

I have two classes and I want to have a one to many relation between them, for e.g.:
Home(id<int>, rooms<string>)
Vehicle(id<int>, home_id<int>, name<string>)
I need to have a relation between Home and Vehicle class using Home.id and vehicle.home_id.
Please suggest any example which I can use here for CURD operation to implement REST service.
I need to have a relation between Home and Vehicle class using Home.id
and vehicle.home_id.
Your entities should look like this :
Vehicle Entity
#Entity
#Table(name = "vehicle", catalog = "bd_name", schema = "schema_name")
#XmlRootElement
public class Vehicle implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Column(name = "name")
private String name;
#JoinColumn(name = "home_id", referencedColumnName = "id")
#ManyToOne
private Home homeId;
//constructor getter & setters
}
Home Entity
#Entity
#Table(name = "home", catalog = "bd_name", schema = "schema_name")
#XmlRootElement
public class Home implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Column(name = "room")
private Character room;
#OneToMany(mappedBy = "homeId")
private List<Vehicle> vehicleList;
//constructor getter & setters
}

JPA cascade not inserting foreign key

I have 2 entity classes - Order and OrderDetail. Below are code snippets of these two classes.
#Entity
#Table(name="orders")
#IdClass(OrderPK.class)
public class Order implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private int id;
#Id
private String customerEmail;
#Column(name="advance_order_time")
private Date advanceOrderTime;
#Column(name="amount")
private float amount;
#OneToMany(mappedBy = "order", fetch = FetchType.LAZY, cascade = CascadeType.PERSIST)
private Set<OrderDetail> orderDetailList;
public void addOrderDetail(OrderDetail orderDetail) {
if (orderDetail != null) {
if (orderDetailList == null) {`enter code here`
orderDetailList = new HashSet<OrderDetail>();
}
orderDetailList.add(orderDetail);
orderDetail.setOrder(this);
}
}
}
#Entity
#Table(name="order_details")
public class OrderDetail implements Serializable{
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int id;
#Column(name="item_code")
private String itemCode;
#ManyToOne
#MapsId("id")
private Order order;
}
public class OrderPK implements Serializable {
//default serial version id, required for serializable classes.
private static final long serialVersionUID = 1L;
private int id;
#Column(name="customer_email")
private String customerEmail;
}
Order object and the collection of OrderDetail objects are inserted successfully in the database but the order_id column of OrderDetail in null. Below is the code snippet.
entityManager.persist(kfcOrder);
order table has a composite key id and customer_email. This id is foreign key of table order_details of column order_id.
Please suggest a work around so that while persisting order object in database order_id of order_details table also gets saved.
try this..
#ManyToOne(optional = false)
#JoinColumns({
#JoinColumn(name = "ORDER_ID",referencedColumnName = "id"),
#JoinColumn(name = "EMAIL",referencedColumnName = "customerEmail")
})
#MapsId("id")
private Order order;
optional = false will ensure that no child can exist if parent doesn't exist.

OneToMany Hibernate Failed To Save

I have problem with OneToMany saving problem using hibernate.
#Entity
#Table(name="lecturer")
public class LecturerEntity extends BaseEntity implements Serializable{
private static final long serialVersionUID = 446089492592652000L;
#Id
#Column(name="id")
#GeneratedValue
private int id;
#Column(name="lecturer_name")
private String lecturerName;
#ManyToOne
#JoinColumn(name="department_id")
private DepartmentEntity department;
}
#Entity
#Table(name="Department")
public class DepartmentEntity extends BaseEntity implements Serializable {
private static final long serialVersionUID = -6221599323765325196L;
#Id
#Column(name="id")
#GeneratedValue
private int id;
#Column(name="department_name")
private String departmentName;
#OneToMany(cascade = CascadeType.ALL, mappedBy="department")
private List<LecturerEntity> lecturers;
}
/*
* One to Many Bidirectional DepartmentEntity and LecturerEntity
*/
departmentRepository = ctx.getBean(DepartmentRepository.class);
lecturerRepository = ctx.getBean(LecturerRepository.class);
department = new DepartmentEntity("Department");
List<LecturerEntity> lecturers = new ArrayList();
lecturers.add(new LecturerEntity("Lecturer 1"));
lecturers.add(new LecturerEntity("Lecturer 2"));
department.setDepartments(lecturers);
departmentRepository.saveDepartment(department);
I got this in my table
Result
Why is department_id in Lecturer table null?
please help, I can't spot the problem.
Thanks.

How to use a child association property as a Map key in JPA parent entity

I'm having two entities Car and CarDescription where CarDescription is depending on another foreign key from the table Language.
What I' trying to accomplish is to have a HashMap in Car such that whenever I'm having a Car entity-object I am able to access all descriptions from the language id.
Entity Car.java
#Entity
#Table(name = "Car")
public class Car extends AbstractTimestampEntity implements Serializable {
private static final long serialVersionUID = -5041816842632017838L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "ID", unique = true, nullable = false)
private Long id;
#OneToMany(mappedBy="car")
#MapKeyColumn(name = "language_ID")
// #MapKey(name = "language") // does not work either
private Map<Long, CarDescription> carDescription = new HashMap<>(0);
}
Entity CarDescription.java
#Entity
#Table( name="car_description",
uniqueConstraints = {
#UniqueConstraint(columnNames={"language_id", "name"})
}
)
public class CarDescription extends AbstractTimestampEntity implements Serializable {
private static final long serialVersionUID = 2840651722666001938L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name = "ID", unique = true, nullable = false)
private Long id;
#NotNull
#ManyToOne
private Car car;
#NotNull
#OneToOne
private Language language;
// ..
}
Entity Language.java
#Entity
public class Language implements Serializable {
private static final long serialVersionUID = 3968717758435500381L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="ID")
private Long id;
// ..
}
The problem I am having is that the mapping gives me a map from each CarDescription.id to CarDescription.
How can I accomplish a correct mapping?
In CarDescription you need to add the languageId property:
#Column(name = "language_id", insertable = false, updatable = false)
private Long languageId;
#NotNull
#OneToOne
#JoinColumn(name = "language_id")
private Language language;
public void setLanguage(Language language) {
this.languageId = language.getId();
this.language = language;
}
Then you can use it in the Car entity like this:
#OneToMany(mappedBy="car")
#MapKey(name = "languageId")
private Map<Long, CarDescription> carDescription = new HashMap<>(0);

Categories