I have three entities and i have one parent class. Tarifa entity has "pvp" column, so I don't want it in "servicio" entity. The problem is that jpa force me to create column "pvp" in "servicio" table because i am using inheritance. Is there some way to avoid creating "pvp" column in "servicio" table?
#Entity
#Table(name="tarifa")
#AttributeOverride(name = "nombre", column = #Column(name = "nombre", insertable = false, updatable = false))
public class Tarifa extends Concepto
{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#OneToMany(mappedBy = "tarifa")
private List<Servicio> servicios = new ArrayList<Servicio>();
/*#Column(name="pvp")
private float pvp;*/
#Column(name="descuento")
private float descuento;
#Column(name="fecha_inicio")
private Date fechaInicio;
#Column(name="fecha_fin")
private Date fechaFin;
#Entity
#Table(name="producto")
public class Producto extends Concepto
{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#Column(name="descripcion")
private String descripcion;
#Column(name="stock")
private int stock;
#Column(name="coste")
private float coste;
/*#Column(name="pvp")
private float pvp;*/
#OneToMany(mappedBy="producto")
private List<DetalleFactura> detalleFactura = new ArrayList<DetalleFactura>();
#Entity
#Table(name="servicio")
#AttributeOverride(name = "pvp", column = #Column(name = "pvp", insertable = false, updatable = false))
public class Servicio extends Concepto
{
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
private Long id;
#ManyToOne(cascade = {CascadeType.ALL})
#JoinColumn(name="id_tarifa")
private Tarifa tarifa;
#ManyToOne(cascade = {CascadeType.ALL})
#JoinColumn(name="id_animal")
private Animal animal;
#OneToOne(mappedBy="servicio", cascade = {CascadeType.ALL})
private CitaServicio citaServicio;
#OneToMany(mappedBy="servicio")
private List<DetalleFactura> detalleFactura = new ArrayList<DetalleFactura>();
#MappedSuperclass
public abstract class Concepto
{
#Column(name="nombre")
private String nombre;
#Column(name="pvp")
private float pvp;
Related
When I'm trying to save the child table, the insert query fired doesn't contain the foreign key field. The insert query that JPA fires doesn't contain the foreign key column. Here are the models and their composite key classes :
#Embeddable
public class EwpPk implements Serializable {
private static final long serialVersionUID = -3231628074628968344L;
#Column(name = "ewp_sid", nullable = false)
private Long sid
#Column(name = "PRTN_KEY", nullable = false)
private Date partitionDate;
#Column(name = "SUB_PRTN_SEQ_NUM", nullable = false)
private int sequenceNumber;
}
#Table(name = "EWP")
public class Ewp implements Serializable {
private static final long serialVersionUID = 7232535288636665348L;
#EmbeddedId
private EwpPk modelid;
#ManyToOne(targetEntity = Eap)
#MapsId("e_modelid")
#joinColumns({
#JoinColumn(name="eap_sid", nullable=false),
#JoinColumn(name="PRTN_KEY", nullable=false),
#JoinColumn(name="SUB_PRTN_SEQ_NUM", nullable=false)
})
private Eap eap;
public class EnrolledAccountRangePartitionedModel implements Serializable {
private static final long serialVersionUID = 700193113967839613L;
#EmbeddedId
private EapPk e_modelid;
#OneToMany(targetEntity = Ewp.class, cascade = {CascadeType.PERSIST, CascadeType.MERGE}, fetch = FetchType.EAGER, mappedBy = "eap")
private list<Ewp> ewpList;
}
#Embeddable
public class EapPk implements Serializable {
private static final long serialVersionUID = -4696018718017450273L;
#Column(name = "Eap_sid", nullable = false)
private Long eapsid;
#Column(name = "PRTN_KEY", nullable = false)
private Date partitionDate;
#Column(name = "SUB_PRTN_SEQ_NUM", nullable = false)
private int sequenceNumber;
I get this error ORA - 01400 : Cannot Insert into null
I have some entity classes and i have a question because I want to clear it in my mind. In case of #ManyToOne relationship where I insert for example #JoinColumn(name = "cardHolderId"), shall I remove the primitive private Long cardHolderId? Because I had a discussion and a programmer explained to me that I can avoid declaring. But if I avoid it I can not use it in test cases like services.
#Entity
#Getter
#Setter
#Builder
#NoArgsConstructor
#AllArgsConstructor
#Table(name = "card")
public class Card {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
#Column(name = "code")
private String code;
#Column(name = "number")
private String number;
#Column(name = "issueDate")
private Date issueDate;
#Column(name = "expireDate")
private Date expireDate;
#Column(name = "elasticDate")
private Date elasticDate;
#Column(name = "pin")
private Long pin;
#Column(name = "isValid")
private Boolean isValid;
#Column(name = "isUsed")
private Boolean isUsed;
#Column(name = "isPin")
private Boolean isPin;
#Column(name = "cardCategoryId")
private Long cardCategoryId;
#Column(name = "hasNumberOfVisits")
private Boolean hasNumberOfVisits;
#Column(name = "numberOfVisits")
private Long numberOfVisits;
#Column(name = "isBlackListed")
private Boolean isBlackListed;
#Column(name = "cardHolderId")
private Long cardHolderId;
//Check Relationships
#ManyToOne
#JoinColumn(name = "cardCategoryId")
private CardCategory cardCategory;
#ManyToOne
#JoinColumn(name = "cardHolderId")
private CardHolder cardHolder;
#Column(name = "companyGroupId")
private Long companyGroupId;
#ManyToOne
#JoinColumn(name = "companyGroupId")
private CompanyGroup companyGroup;
#OneToMany(mappedBy = "card")
private List<AccessControlSubject> accessControlSubjects = new ArrayList<>();
#OneToMany(mappedBy = "card")
private List<Card2Role> card2Roles = new ArrayList<>();
#ManyToOne
#JoinColumn(name = "cardHistoryId")
private CardHistory cardHistory;
#OneToMany(mappedBy = "vehicleCard")
private List<Vehicle> vehicles = new ArrayList<>();
#ManyToOne
#JoinColumn(name = "sharedCardId")
private PatrolSharedCard sharedCard;
#ManyToOne
#JoinColumn(name = "productionWorkId")
private PrdWork productionWork;
#ManyToOne
#JoinColumn(name = "productionWorkHitsId")
private PrdWorkHits productionWorkHits;
#OneToMany(mappedBy = "card")
private List<VisitorCardHistory> visitorCardHistories = new ArrayList<>();
You can remove it and use the id from the referred entity :
this.getCardHolder().getId()
i have a problem
I have two entities:
Entity ALBERO
#Entity
#IdClass(Albero.class)
#Table(schema="organo", name = "albero")
public class Albero implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#JoinColumn(name = "cmu")
#OneToOne
private Struttura cmu;
#Id
#JoinColumn(name = "padre")
#NotFound(action = NotFoundAction.IGNORE)
#ManyToOne
private Struttura padre;
#Column(name = "div")
private Date div;
#Column(name = "dfv")
private Date dfv;
#Column(name = "cso", length=15)
private String cso;
... get and set methods
and Entity STRUTTURA
#Entity
#Table(schema="organo", name="strutture")
#SqlResultSetMapping(
name = "Albero",
classes = #ConstructorResult(
targetClass = Albero.class,
columns = {
#ColumnResult(name="cmu", type=String.class),
#ColumnResult(name="padre", type=String.class)
}
)
)
public class Struttura implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Column(name = "cmu")
private String cmu;
#Column(name = "nome", length=512)
private String nome;
#Column(name = "tipologia")
private String tipologia;
#Column(name = "data_creazione")
private Date data_creazione;
...get and set methods
I have a Repository AlberoRepository with the method:
public List<Albero> findByDfvIsNull();
and other method with native query:
String QUERY = "SELECT a.* FROM ALBERO a WHERE DFV IS NULL";
#Query(nativeQuery = true, value = QUERY)
public List<Albero> findAllWithDfvIsNull();
La query on Oracle DB, give me a result with 802 record.
Each record are full; they have the values.
Instead, the methods Java, give me a List of 802 object
BUT THESE OBJECTS ARE NULL.
Why ?
Can you help me ?
Thank you very much
The problem in #IdClass annotation.
You need a special class for PK:
public class AlberPK implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#JoinColumn(name = "cmu")
#OneToOne
private Struttura cmu;
#Id
#JoinColumn(name = "padre", nullable = true)
#NotFound(action = NotFoundAction.IGNORE)
#ManyToOne
private Struttura padre;
}
... and change a little in Albero.class:
#Entity
#IdClass(AlberPK.class)
#Table(schema = "organo", name = "albero")
public class Albero implements Serializable {
private static final long serialVersionUID = 1L;
#Id
private Struttura cmu;
#Id
private Struttura padre;
...
}
That have to work.
I am really don't understand - why you used complex PK? Re-mind your DB structure if possible. It will help you a lot in future.
Is there a way to join two tables in Spring JPA without using association class.
I have two MySQL DB tables :
employees(id,.....,department_id)
departments(id,.....)
And I'm searching for a way to join these tables using only my employee and department classes.
Currently, I managed to join two tables but with the third association class.
My current implementation is:
Employee class:
#Entity(name = "Employee")
#Table(name = "employees")
#JsonInclude(Include.NON_NULL)
public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#JsonIgnore
#Column(name = "employee_id")
private Long employeeId;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#Column(name = "phone_number")
private String phoneNumber;
#Column(name = "hire_date")
private Double hireDate;
#Column(name = "job_id")
private Long jobId;
#Column(name = "salary")
private Double salary;
#Column(name = "commission_pct")
private Double commissionPct;
#Column(name = "employees")
private Long employees;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id", insertable = false, updatable = false)
#Fetch(FetchMode.JOIN)
private Department department;
}
Department class:
#Entity(name = "Department")
#Table(name = "departments")
#JsonInclude(Include.NON_NULL)
public class Department implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "department_name")
private String departmentName;
#Column(name = "department_id")
private long departmentId;
#Column(name = "manager_id")
private Double managerId;
#Column(name = "location_id")
private Double locationId;
}
Association class:
public class DeptEmpDto {
private long departmentId;
private String departmentName;
private Double managerId;
private Double locationId;
private long employeeId;
private String firstName;
private String lastName;
private String phoneNumber;
private Double hireDate;
private Long jobId;
private Double salary;
private Double commissionPct;
}
Repository:
public interface IEmployeeRepository extends JpaRepository<Employee, Long> {
#Query("SELECT new com.concretepage.entity.DeptEmpDto(d.departmentId,d.departmentName,d.managerId,d.locationId,e.employeeId,e.firstName,e.lastName,e.phoneNumber,e.hireDate,e.jobId,e.salary,e.commissionPct FROM Employee e INNER JOIN Department d ON d.id = e.jobId")
List<DeptEmpDto> fetchEmpDeptDataInnerJoin();
You can use it in Employee class
#ManyToMany(fetch = FetchType.EAGER)
#JoinTable(
name = "DeptEmp",
joinColumns = #JoinColumn(name = "emp_id",referencedColumnName = "id"),
inverseJoinColumns = #JoinColumn(name = "dep_id",referencedColumnName = "id")
)
private Set<Departments> departments = new HashSet<>();
Look at this about JPA
Logically an employee can't work in two departements so your relationship is correct
But you can do that with a #ManyToMany annotation.
I'm new to JPA and trying to do relations between two tables like this:
This is the main class object XParserLinks:
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "link_id")
private Integer linkId;
#OneToMany(mappedBy = "xParserLink", targetEntity = XLinksMedia.class, cascade = CascadeType.ALL)
private List<XLinksMedia> fotos;
...
This is the object class XLinksMedia
public class XLinksMedia implements Serializable {
private static final long serialVersionUID = 1L;
#EmbeddedId
protected XLinksMediaPK xLinksMediaPK;
#ManyToOne #JoinColumn(name = "link_id")
private XParserLinks xParserLink;
and XLinksMediaPK
#Embeddable
public class XLinksMediaPK implements Serializable {
#Basic(optional = false)
#Column(name = "link_id", insertable = false, updatable = false)
private int linkId;
#Basic(optional = false)
#Column(name = "image")
private String image;
Are these relations correct? Because when I want to add new XLinksMedia objects in fotos list, I get LinkId = 0, but I know that LinkId is not 0, I know that LinkId variable have a value.
Here's how I try to set fotos variable in XParseLinks class (preke: is XParseLinks object witch have his primary key LinkId):
XLinksMedia foto = new XLinksMedia();
foto.setXLinksMediaPK(new XLinksMediaPK());
foto.setxParserLink(preke);
foto.getXLinksMediaPK().setImage(e.attr("src"));
preke.getFotos().add(foto);
Even I don't know what is your expectation, When I test your coding, it is OK. I just put some of the OverLoad Constructor for easy data initialization in your classes. But, you use GenerationType.IDENTITY, that's why I set auto increate column for link_id of XParserLinks. The main of the following coding is same as yours.
Your point Here's how I try to set fotos variable in XParseLinks class (preke: is XParseLinks object witch have his primary key LinkId):. Check Test.java
XParserLinks.java
#Entity
public class XParserLinks implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "link_id")
private Integer linkId;
#OneToMany(mappedBy = "xParserLink", targetEntity = XLinksMedia.class, cascade = CascadeType.ALL)
private List<XLinksMedia> fotos;
private String something;
public XParserLinks() {
fotos = new ArrayList<XLinksMedia>();
}
public XParserLinks(String something) {
this.something = something;
fotos = new ArrayList<XLinksMedia>();
}
//getter and setter
}
XLinksMediaPK.java
#Embeddable
public class XLinksMediaPK implements Serializable {
#Basic(optional = false)
#Column(name = "link_id", insertable = false, updatable = false)
private int linkId;
#Basic(optional = false)
#Column(name = "image")
private String image;
public XLinksMediaPK(){
}
public XLinksMediaPK(int linkId, String image) {
this.linkId = linkId;
this.image = image;
}
//getter and setter
}
XParserLinks.java
#Entity
public class XParserLinks implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "link_id")
private Integer linkId;
#OneToMany(mappedBy = "xParserLink", targetEntity = XLinksMedia.class, cascade = CascadeType.ALL)
private List<XLinksMedia> fotos;
private String something;
public XParserLinks() {
fotos = new ArrayList<XLinksMedia>();
}
public XParserLinks(String something) {
this.something = something;
fotos = new ArrayList<XLinksMedia>();
}
//getter and setter
public void add(XLinksMedia media) {
fotos.add(media);
}
}
Test.java
public class Test {
public static void main(String[] args) {
EntityManagerFactory emf = Persistence.createEntityManagerFactory("JPA");
EntityManager em = emf.createEntityManager();
em.getTransaction().begin();
XParserLinks xParserLink = new XParserLinks("something");
XLinksMediaPK pk1 = new XLinksMediaPK(0, "image_1");
XLinksMediaPK pk2 = new XLinksMediaPK(0, "image_2");
XLinksMediaPK pk3 = new XLinksMediaPK(0, "image_3");
xParserLink.add(new XLinksMedia(pk1, xParserLink));
xParserLink.add(new XLinksMedia(pk2, xParserLink));
xParserLink.add(new XLinksMedia(pk3, xParserLink));
em.persist(xParserLink);
System.out.println("Success...");
em.getTransaction().commit();
em.close();
}
}