Embed complex object in entity - spring

I want to embed the following
#Embeddable
public class BaseEntity implements Serializable {
#Id
#GeneratedValue
private UUID id;
#CreatedDate
#Column(name = "created_date", updatable = false)
private LocalDateTime createdDate;
}
into my room entity
#Entity
#Data
#NoArgsConstructor
#Table(name = "room")
public class room {
#EmbeddedId
private BaseEntity baseEntity;
#Column(length = 80, nullable = false)
private String name;
}
So that my generated table looks like this
room
id
createdDate
name
But id and createdDate are not getting embedded

Instead of #Embeddable just extend your BaseEntity
#MappedSuperclass
#Getter
#Setter
public class BaseEntity implements Serializable {
#Id
#GeneratedValue
private UUID id;
#CreatedDate
#Column(name = "created_date", updatable = false)
private LocalDateTime createdDate;
}
#Entity
#Data
#NoArgsConstructor
#Table(name = "room")
public class room extends BaseEntity{
#Column(length = 80, nullable = false)
private String name;
}

Related

How to implements entity with 2 entity as primary key with jpa annotation and repository

i want to implement a many to many association with quantity information in it . like this :
#Entity
#Table(name = "reserves")
#Getter #Setter #NoArgsConstructor
public class Reserve {
#Id
#ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#JoinColumn(name = "groupe_id")
private GroupeSanguin bloodGroup;
#Id
#ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
private Banque banque;
private int quantity;
}
the GroupSanguin and the Banque are two class stored in the database two . here is the code for the two if you need :
#Entity
#Table(name = "groupe_sanguins")
public class GroupeSanguin {
#Id
private String groupe;
#OneToMany(mappedBy = "groupeSanguin")
private List<Donneur> donneurs;
}
#Entity #Getter #Setter #NoArgsConstructor
public class Banque {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#Column(unique = true,nullable = false)
private String nom;
private String adresse;
#Column(unique = true)
private String telephone;
private String localisation;
}
so my i want to know how to annotate the JpaRepository to take the two as primary key like this and is my annotation good for it to work ?
public interface ReserveRepository extends JpaRepository<
Reserve,
//what to put here ?
>
This isn't a JPA question in fact, it's a relationnal database conception.
If Reserve has is own data and links with other entity it has it own Id
You can add unicity constraint
#Entity
#Table(name = "reserves", uniqueConstraints={
#UniqueConstraint(columnNames = {"banque_id", "groupe_id"})
#Getter #Setter #NoArgsConstructor
public class Reserve {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long id;
#ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#JoinColumn(name = "groupe_id")
private GroupeSanguin bloodGroup;
#ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#JoinColumn(name = "banque_id")
private Banque banque;
private int quantity;
}
i've found this solutions too.
#Entity
#Table(name = "reserves")
#Getter #Setter #NoArgsConstructor
#IdClass(ReserveId.class) //this annotation will tell that id that the
// the id will be represented by a class
public class Reserve {
#Id
#ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#JoinColumn(name = "groupe_id")
private GroupeSanguin groupeSanguin;
#Id
#ManyToOne(cascade = CascadeType.ALL,fetch = FetchType.EAGER)
#JoinColumn(name = "banque_id")
private Banque banque;
private int quantity;
}
and the id class should implements Serializable like this :
#Getter #Setter
public class ReserveId implements Serializable {
private Banque banque;
private GroupeSanguin groupeSanguin;
}
and finally the repository will be like that :
#Repository
public interface ReserveRepo extends JpaRepository<Reserve, ReserveId>{}
See your Reserve class has nowhere mentioned composite primary key. First you need to fix the model, You can refer to the solution here How to create and handle composite primary key in JPA

Add extra custom column to auto mapped Table in Spring JPA ManyToMany

#Getter #Setter #NoArgsConstructor #AllArgsConstructor
#Table(name = "my_users")
public class MyUsers {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(nullable = false)
private Long id;
#Column(nullable = false, unique = true)
private String userName;
private String password;
#ManyToMany
private List<MyUsers> connections;
}
This is my MyUsers Model Class. I am using Hibernate and MySQL.
#ManyToMany
private List<MyUsers> connections;
This ManyToMany relationship is automatically creating the table 'my_users_connections' with 'my_users_id' and 'connections_id' colums. How can I add extra columns to this auto mapped table?
It's not ideal solution...
#Getter
#Setter
#NoArgsConstructor
#AllArgsConstructor
#Entity
#Table(name = "my_users")
public class MyUsers implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(nullable = false)
private Long myUsersId;
#Column(nullable = false, unique = false)
private String userName;
private String password;
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "my_users_connections",
joinColumns = { #JoinColumn(name = "my_users_id") },
inverseJoinColumns = { #JoinColumn(name = "connections_id") })
private List<MyUsers> connections;
}
Create embedded id MyUsersConnectionsPK:
#Data
#Embeddable
public class MyUsersConnectionsPK implements Serializable {
#Column(name = "my_users_id")
private Long myUsersId;
#Column(name = "connections_id")
private Long connectionsId;
}
Create MyUsersConnections, which represent ManyToMany
#Data
#Entity
#Table(name = "my_users_connections")
public class MyUsersConnections implements Serializable {
#EmbeddedId
private MyUsersConnectionsPK id;
#ManyToOne
#MapsId("my_users_id")
#JoinColumn(name = "my_users_id")
private MyUsers myUsersId;
#ManyToOne
#MapsId("connections_id")
#JoinColumn(name = "connections_id")
private MyUsers connectionsId;
#Column(name = "extra_column")
private String extraColumn;
}
Create JPA repository
#Repository
public interface MyUsersConnectionsRepository extends JpaRepository<MyUsersConnections, MyUsersConnectionsPK> {
List<MyUsersConnections> findMyUsersConnectionsByMyUsersIdMyUsersId(Long id);
}
And simple sample for using:
#Service
public class Test {
#Autowired
private MyUsersConnectionsRepository myUsersConnectionsRepository;
#Autowired
private MyUsersRepository myUsersRepository;
public void test() {
MyUsers myUsers = new MyUsers();
myUsers.setUserName("user name");
myUsers.setPassword("password");
MyUsers myUsers2 = new MyUsers();
myUsers2.setUserName("user name 2");
myUsers2.setPassword("password 2");
myUsers.setConnections(Collections.singletonList(myUsers2));
myUsers = myUsersRepository.saveAndFlush(myUsers);
List<MyUsersConnections> myUsersConnections = myUsersConnectionsRepository.findMyUsersConnectionsByMyUsersIdMyUsersId(myUsers.getMyUsersId());
MyUsersConnections item = myUsersConnections.get(0);
item.setExtraColumn("Extra column");
myUsersConnectionsRepository.saveAndFlush(item);
}
}

Jpa Inheritance showing me the superclass fields

My super-class is annotated with #Inheritance(strategy = InheritanceType.SINGLE_TABLE) and my sub-class is inheriting from it, that means when i try to get data in Postman it retrieve also the superclass fields which I don't that to happen, any help please
#Table(name = "SUPER_CLASS-TABLE")
#Entity
#Getter
#Setter
#AllArgsConstructor
#NoArgsConstructor(force = true)
#Inheritance(strategy = InheritanceType.SINGLE_TABLE)
public class SUPERCLASSTABLE implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(nullable = false, updatable = false)
private Long tblId;
#CreatedDate
#CreationTimestamp
private Date publishingDate;
private String name;
}
#Getter
#Setter
#Entity
#AllArgsConstructor
#NoArgsConstructor
#DiscriminatorValue("sub-class")
public class SUBCLASSTABLE extends SUPERCLASSTABLE {
private String cin;
private String firstNname;
private String lastName;
#OneToOne(cascade = CascadeType.ALL, optional = false)
#JsonIgnore
private SUPERCLASSTABLE superclasstable;
This is my response request:
{
"tblId": 1,
"publishingDate" : "2022-03-13",
"name" : "SomeName"
"sub-classtable"{
"tblId": null,
"publishingDate" : null,
"name" : null
"cin": "somedata",
"firstName": "somedata",
"lastName": "somedata"
}
}
So what I want is just the data of subclass

Spring boot #OneToMany association saves id with null value

Hello guys i don't know why but when i tried to define an association
#one to many i get a null in the service_id and question_id.
first entity
#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
#Inheritance(strategy = InheritanceType.JOINED)
public class Services implements Serializable{
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
#Column(nullable = false, updatable = false)
private Long id;
private String serviceName;
private String description;
private String image;
#OneToMany(cascade = CascadeType.ALL)
private List<Questions> questions;
Second entity
#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
public class Questions implements Serializable {
#Id
#GeneratedValue(strategy= GenerationType.IDENTITY)
#Column(nullable = false, updatable = false)
private Long id;
private String question;
#Column(name="service_id")
private String service_id;
#OneToMany(cascade = CascadeType.ALL)
private List<Answers> answers;
third entity
#Entity
#Data
#NoArgsConstructor
#AllArgsConstructor
public class Answers implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(nullable = false, updatable = false)
private Long id;
private String answer;
private double cost;
#Column(name="question_id")
private String question_id;
you can find the image for the tables bellow
enter image description here
All you need to do is remove the following line from Both of your models:
#Column(nullable = false, updatable = false)
After this line: #GeneratedValue(strategy = GenerationType.IDENTITY)
That will solve your problem.

spring jpa join two entities

I'm struggling to join two entity models using jpa crudRepository interface. i can't figure out how to map two entity model and write query inside #Query annotation. these are my entity classes.
I want to execute this query "SELECT dppd.payment_plan_id,dppd.attribute_value,dppd.attribute_id FROM taxi_driver_mapping AS tdm JOIN driver_payment_plan_details AS dppd on dppd.payment_plan"
#Getter
#Setter
#Entity
#ToString
#Table(name = "driver_payment_plan_details")
#NoArgsConstructor
public class DriverPaymentPlanDetails
{
#Id
#Column(name = "id")
private int id ;
#Column(name = "payment_plan_id")
private long paymentPlanId;
#Column(name = "attribute_id")
private int attributeId;
#Column(name = "attribute_value")
private float attributeValue;
}
#Getter
#Setter
#ToString
#Table(name = "taxi_driver_mapping")
#Entity
#NoArgsConstructor
public class TaxiDriverMapping
{
#Column(name = "mapping_id")
#Id
private Long mappingId;
#Column(name = "mapping_driverid")
private Long mappingDriverId;
#Column(name = "mapping_taxi_model_id")
private String mappingTaxiModelId;
#Column(name = "mapping_status")
private String mappingStatus;
#Column(name = "mapping_payment_plan_id")
private Long mappingPaymentPlanId;
}
thank you guys for showing a correct path, this is my code.
#Getter
#Setter
#ToString
#Table(name = "taxi_driver_mapping")
#Entity
#NoArgsConstructor
public class TaxiDriverMapping
{
#Column(name = "mapping_id")
#Id
private Long mappingId;
#Column(name = "mapping_driverid")
private Long mappingDriverId;
#Column(name = "mapping_taxi_model_id")
private String mappingTaxiModelId;
#Column(name = "mapping_status")
private String mappingStatus;
#Column(name = "mapping_payment_plan_id")
private Long mappingPaymentPlanId;
#OneToMany(mappedBy = "taxiDriverMapping")
private List<DriverPaymentPlanDetails> driverPaymentPlanDetails;
}
#Getter
#Setter
#Entity
#ToString
#Table(name = "driver_payment_plan_details")
#NoArgsConstructor
public class DriverPaymentPlanDetails
{
#Id
#Column(name = "id")
private int id ;
#Column(name = "payment_plan_id")
private long paymentPlanId;
#Column(name = "attribute_id")
private int attributeId;
#Column(name = "attribute_value")
private float attributeValue;
#ManyToOne()
#JoinColumn(name="payment_plan_id",insertable = false,updatable = false)
private TaxiDriverMapping taxiDriverMapping;
}

Resources