I want to create a view from two tables using annotations in java/JEE,
so after some researching I found that the only way to do it is using #Subselectannotation so I created 3 entities
the test entity:
#Table
#Entity
public class Test {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column
private String nom;
#Column
private String prenom;
#Column
private int age;
#Column
private String adresse;
#Column
private Date dateNaissance;
// getters and setters
}
The compte entity:
#Entity
public class Compte {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private long id;
#Column
private long solde;
#Column
private long numero;
#Column
private String description;
// getters and setters
}
and the entity Compte_Test which has the same role as a view
#Entity
#Subselect("SELECT c2.id as idTest,c1.id as id,c1.solde as solde,c1.numero as numero, c2.nom as nom, c2.prenom as prenom FROM Compte c1 INNER JOIN Test c2 ON c1.id_test= c2.id")
#Synchronize({ "compte", "test" })
public class Compte_Test {
#Id
private long idCompte_Test;
#Column
private long idTest;
#Column
private long id;
#Column
private long solde;
#Column
private long numero;
#Column
private String nom;
#Column
private String prenom;
// getters and setters
}
I'm using spring data #Query annotation to get data from Compte_Test entity
#Query(value = "SELECT c from Compte_Test c ")
List<Compte_Test> fullTextSearch(Pageable pageable);
The problem is that it generates for me an error
org.postgresql.util.PSQLException: ERROR: column compte_tes0_.id_compte_test does not exist
Position : 8
at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2440) ~[postgresql-42.2.5.jar:42.2.5]
at org.postgresql.core.v3.QueryExecutorImpl.processResults(QueryExecutorImpl.java:2183) ~[postgresql-42.2.5.jar:42.2.5]
at org.postgresql.core.v3.QueryExecutorImpl.execute(QueryExecutorImpl.java:308) ~[postgresql-42.2.5.jar:42.2.5]
Related
my company recently decided to switch to using Spring Data JPA instead of Mybatis for new projects, so I am pretty new to using Spring Data JPA in general.
I am trying to execute the following sql query
SELECT ab.status, buyer_rate, buyer_name, buyer_tel, bid_price, ADDTIME(complete_dt,"23:00:0.000000") AS send_time, brand, model
FROM auction_bid ab
INNER JOIN goods_auction ga ON ab.goods_auction_idx=ga.idx
INNER JOIN auction_info ai ON ga.auction_info_idx=ai.idx
WHERE is_success=1 and ab.status='008';
I have created 3 entities each corresponding to the table in my mariadb database
#Entity
#Getter
#Setter
#ToString
public class AuctionBid {
#Id
#Column(name = "auction_bid_idx")
private Long idx;
#Column
private Long userIdx;
#Column
private String status;
#Column
private Long bidPrice;
#Column
private int isSuccess;
#Column
private int rank;
#Column
private Date createdAt;
#Column
private Date updatedAt;
#ManyToOne(fetch = LAZY)
#JoinColumn(name="goods_auction_idx")
private GoodsAuction goodsAuction;
}
#Entity
#Getter
#Setter
public class AuctionInfo {
#Id
#Column(name = "auction_info_idx")
private Long idx;
#Column
private Long goodsIdx;
#Column
private String brand;
#Column
private String model;
#Column
private String pattern;
#Column
private String size;
#Column
private String color;
#Column
private String tag1;
#Column
private String tag2;
#Column
private String tag3;
#Column
private String comment;
#Column
private String korName;
#Column
private String oColor;
#Column
private String iColor;
#Column
private String hColor;
#Column
private String oMaterial;
#Column
private String iMaterial;
#Column
private String origin;
#Column
private String realSize;
#Column
private Long minBid;
#Column
private Double sellerRate;
#Column
private Double buyerRate;
#Column
private Date createdAt;
#Column
private Date updatedAt;
}
#Entity
#ToString
#Getter
#Setter
public class GoodsAuction {
#Id
#Column(name = "goods_auction_idx")
private Long idx;
#Column
private String auctionUid;
#Column
private String status;
#Column
private Date startDt;
#Column
private Date finishDt;
#Column
private Long step;
#Column
private int isReadyActive;
#Column
private int isFinishActive;
#Column
private int isRecommended;
#Column
private String invoice;
#Column
private String buyerName;
#Column
private String buyerTel;
#Column
private String buyerAddr1;
#Column
private String buyerAddr2;
#Column
private String buyerZipcode;
#Column
private Date completeDt;
#Column
private Date deliveryDt;
#Column
private Long returnTaxPrice;
#Column
private String returnInvoice;
#Column
private Date returnReqDt;
#Column
private Date returnCompDt;
#Column
private Date createdAt;
#Column
private Date updatedAt;
#ManyToOne(fetch = LAZY)
#JoinColumn(name="auction_info_idx")
private AuctionInfo auctionInfo;
}
And I am trying to map the info that I got from the query to the following object
public class MessageData {
private String status;
private Double buyerRate;
private String buyerName;
private String buyerTel;
private Long bidPrice;
private Date sendTime;
private String brand;
private String model;
}
I get that I have to make and interface that extends JpaRepository, but the examples that I have seen seems to just fetch the entire table instead of a select few columns, and I am a little bit confused on how I will be able to map the result to List.
Any feedback will be deeply appreciated!
Thank you in advance!!
You can hql joins instead of inner joins through entity models.
like that;
select a from auction_bid ab join ab.goodsAuction gA join auctionInfo aI
You can use 'Data Transfer Objects (DTO)' for fetch specific columns.
For projections, you can try a "select new".
I assume the MessageData is in package com.foo :
select new com.foo.MessageData(ab.status, buyer_rate, buyer_name, buyer_tel, bid_price, ADDTIME(complete_dt,"23:00:0.000000"), brand, model) FROM ...
i don't know how to delete this. Only one thing i noticed that the OrderToProvider will be deleted after deleting all entities in a table named "OrderToProvider-Goods".
Code:
OrderToProvider
public class OrderToProvider {
#GeneratedValue (strategy = GenerationType.IDENTITY)
#Id
private int id;
#Basic
private int price;
#Basic
private Date dataOfOrder;
#Basic
private Date dateOfProcessing;
#ManyToOne(optional = false)
private main.data.Provider provider;
#ManyToMany (cascade = CascadeType.ALL)
private Collection<Good> goods;
Good
public class Good implements Comparable<Good>{
#GeneratedValue (strategy = GenerationType.IDENTITY)
#Id
private int id;
#Basic
private String name;
#Basic
private String model;
#Basic
private int price;
#Basic
private String type;
#Basic
private int amount;
#ManyToOne(optional = false)
private Provider provider;
To delete the OrderToProvider from your DB, first you retrieve it from your DB, then setGoods(null) and setProvider(null), then delete it afterwards. This should work with conditions that you have a properly implemented setters.
I hope this is helpful.
I'm developing a server application in jpa eclipselink.
This is my query that works fine when I run it in my sqlworkbench:
SELECT *
FROM `BuildingsTable` AS Buliding
LEFT JOIN ServiceCallsTable AS Calls ON ( Calls.`buildingId` = Buliding.id )
LEFT JOIN SchedualReviewsTable AS Review ON ( Review.`buildingId` = Buliding.id )
WHERE Buliding.id =1
I have 3 table BuildingsTable, ServiceCallsTable and SchedualReviewsTable
The buildingID variable found in Task class
ServiceCallsTable and SchedualReviewsTable extends from Task class
This is my code :
#Entity
#Table(name = "BuildingsTable")
public class Building extends Base{
#Column(name="description", nullable=false)
private String description;
#Column(name="address", nullable=false)
private String address;
#Column(name="constructYear", nullable=false)
private int constructYear;
#Column(name="constructorName", nullable=false)
private String constructorName;
#Column(name="amountParkings", nullable=false)
private int amountParkings;
#Column(name="amountWarehouses", nullable=false)
private int amountWarehouses;
#Column(name="childrenId", nullable=false)
// getters and setters
}
#MappedSuperclass
public abstract class Task extends Base{
#Column(name="description", nullable=false)
protected String description;
#OneToOne
#Column(name="buildingId", nullable=false)
protected long buildingId;
// getters and setters
}
#Entity
#Table(name = "ServiceCallsTable")
public class ServiceCall extends Task{
#Column(name="reporterId", nullable=false)
private long reporterId;
#Column(name="imageDescription", nullable=false)
private Text imageDescription;
#Column(name="status", nullable=false)
private int status;
// getters and setters
}
#Entity
#Table(name = "SchedualReviewsTable")
public class SchedualReview extends Task{
#Column(name="pivotDate", nullable=false)
private long pivotDate;
#Column(name="lastReviewDate", nullable=false)
private long lastReviewDate;
#Column(name="reviewDaysFrequancy", nullable=false)
private int reviewDaysFrequancy;
#Column(name="buildingFacilityTypeIds", nullable=false)
private List<Integer> buildingFacilityTypeIds;
#Column(name="name", nullable=false)
// getters and setters
}
How can I write this query in JPA?
I'm trying to create OneToOne unidirectional relationship with shared Primary Key. According to this tutorial all I need is a #PrimaryKeyJoinColumn annotation on parent side:
#Entity
#Table(name="cities")
public class City {
#Id
#GeneratedValue
#Column(name = "city_id")
private int id;
#Column
private String name;
#OneToOne(cascade = CascadeType.ALL)
#PrimaryKeyJoinColumn
private Mayor mayor;
}
#Entity
#Table(name="mayors")
public class Mayor {
#Id
#Column
private int id;
#Column
private String firstName;
#Column
private String secondName;
}
Hibernate successfully build tables, but mayors table has no foreign key.
What I'm doing wrong?
For example, I've got a table A with structure:
int id | int ref_id | varchar name
0 - hello
1 0 world
And entity class:
#Entity
#Table(name = "mypack.A")
public class A
{
#Id
#Column(name = "ID")
private int id;
#Column(name = "REF_ID", nullable=true)
private int ref_id;
#Column(name = "NAME")
private String name;
// getters and setters
}
Row with id 1 refers to row with id 0. How can I do this kind of relation using Hibernate? I have an idea to create A class object inside that. Is it ok?
You can use instead of the property ref_id of type int use a reference to another A object.
#Entity
#Table(name = "mypack.A")
public class A implements Serializable {
#Id
#GeneratedValue
#Column(name = "ID")
private Long id;
#ManyToOne(cascade = CascadeType.ALL)
#JoinColumn(name = "REF_ID")
private A refA;
#Column(name = "NAME")
private String name;
// getters and setters
}