JPQL returns all associated Entities - java

I am trying to get Order[] Array which includes all Orders where the associated document isn't received.
I tried this query and it returns the right number of rows.
#Query("Select o FROM Order o INNER JOIN o.properties p INNER JOIN p.documents d WHERE d.received = false")
Order[] findUnreceivedOrders();
The problem is, the order objects in my array includes ALL documents not only the unreceived, but I want that the object only includes the unreceived document objects.
Does anyone know how to solve this?
Thanks for help!
Order.java
#Entity
#Table(name = "orders")
#JsonIgnoreProperties(ignoreUnknown = true,
value = {"progress"})
public class Order {
#Id
#Column(name = "id", unique = true)
private String orderid;
#Column(name = "user_id")
private String userid;
#Column(name = "entrydate")
private java.sql.Date entrydate;
#Column(name = "info")
private String info;
#Column
private boolean complete;
#Column(name= "cached")
private boolean cached;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "order")
private List<Property> properties = new ArrayList<>();
#OneToOne(mappedBy = "order", cascade = CascadeType.ALL)
private BillingAdress billingAdress;
// Getter & Setter
Property.java
#Entity
#Table(name = "properties")
#JsonIgnoreProperties(ignoreUnknown = true,
value = {"progress"})
public class Property
{
#Id
#Column(name = "propertyid", unique = true )
private String id;
#Column(name = "name")
private String name;
#Column(name = "street")
private String street;
#Column(name = "zip")
private String zip;
#Column(name = "town")
private String town;
#Column
private String house_number;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "property")
private List<Landregisterfolio> landregisterfolios = new ArrayList<>();
#Column(name = "userid" )
private String userid;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "property")
private List<Document> documents = new ArrayList<>();
#ManyToOne
#JoinColumn(name = "order_id")
#JsonIgnore
private Order order;
#Column(name = "order_id", insertable = false, updatable = false)
private String orderid;
//Getter & Setter
}
Document.java
#Entity
#Table(name = "documents")
public class Document {
#Id
#Column(name="id")
private String docid;
#Column(name="name")
private String docname;
#Column(name = "received")
private Boolean received;
#Column(name = "requested")
private Boolean requested;
#Column(name ="last_contact")
private Date lastContact;
#Column(name ="intern_comment")
private String intern_comment;
#Column(name ="extern_comment")
private String extern_comment;
#Column(name="fees")
private double fees;
#ManyToOne
#JoinColumn(name = "property_propertyid")
#JsonIgnore
private Property property;
#Column(name = "property_propertyid", insertable = false, updatable = false)
private String propertyid;
//Getter & Setter
}

Probably you can map #ManyToOne Order to your Document entity and after use for Order entity
#JoinColumnOrFormula(formula = #JoinFormula("(select d.id from documents d WHERE d.order_id = id AND d.received = false"))
List<Document> unreceivedDocuments;

U have list of Property in Order and list of Document in Property. So if u have one Document with status not received in your list u will have this Order.

Thanks to #pdem !
Used "join fetch", changed my lists to sets and it works fine.

Related

Why Spring JPA Hibernate is fetching all the records individually by id?

I am running following query using Spring JPA in my project. Its internally using Hibernate for connecting to MySql DB. This query is written inside JpaRepository.
#Query(value = "SELECT ipd.* FROM identifier_pool_definition ipd, identifier_definition id WHERE\n" +
"ipd.definition_id = id.definition_id AND id.acquirer_id = :acquirerId AND" +
" id.domain = :domain AND id.definition_type = 'pool' AND id.status IN :statuses AND id.type = :poolType AND id.is_deleted = false",
nativeQuery = true)
List<IdentifierPoolDefinitionEntity> findAllWithPoolTypeAndStatuses(#Param("acquirerId") String processorId,
#Param("domain") String domain,
#Param("poolType") String poolType,
#Param("statuses") Collection<String> statuses);
In the application logs I am observing that after running above query, Hibernate is making individual select DB calls by id for each record fetched in the above query.
Sample logs:
Hibernate:
SELECT
ipd.*
FROM
identifier_pool_definition ipd,
identifier_definition id
WHERE
ipd.definition_id = id.definition_id
AND id.acquirer_id = ?
AND id.domain = ?
AND id.definition_type = 'pool'
AND id.status IN (
?, ?, ?
)
AND id.type = ?
AND id.is_deleted = false
Hibernate:
select
identifier0_.definition_id as definiti1_2_0_,
identifier0_.acquirer_id as acquirer2_2_0_,
identifier0_.created as created3_2_0_,
identifier0_.created_by as created_4_2_0_,
identifier0_.definition_type as definiti5_2_0_,
identifier0_.domain as domain6_2_0_,
identifier0_.is_deleted as is_delet7_2_0_,
identifier0_.merchant_id as merchant8_2_0_,
identifier0_.processor_id as processo9_2_0_,
identifier0_.status as status10_2_0_,
identifier0_.type as type11_2_0_,
identifier0_.updated as updated12_2_0_,
identifier0_.updated_by as updated13_2_0_
from
identifier_definition identifier0_
where
identifier0_.definition_id=?
...
...
after n records
...
...
Hibernate:
select
identifier0_.definition_id as definiti1_2_0_,
identifier0_.acquirer_id as acquirer2_2_0_,
identifier0_.created as created3_2_0_,
identifier0_.created_by as created_4_2_0_,
identifier0_.definition_type as definiti5_2_0_,
identifier0_.domain as domain6_2_0_,
identifier0_.is_deleted as is_delet7_2_0_,
identifier0_.merchant_id as merchant8_2_0_,
identifier0_.processor_id as processo9_2_0_,
identifier0_.status as status10_2_0_,
identifier0_.type as type11_2_0_,
identifier0_.updated as updated12_2_0_,
identifier0_.updated_by as updated13_2_0_
from
identifier_definition identifier0_
where
identifier0_.definition_id=?
Following are my entity classes:
IdentifierPoolDefinitionEntity.java
#Entity
#Table(name = "identifier_pool_definition")
#Getter
#Setter
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class IdentifierPoolDefinitionEntity implements Serializable {
private static final long serialVersionUID = 518449602683891708L;
#Id
#Column(name = "definition_id", columnDefinition = "BINARY(16)")
private UUID definitionId;
#Column(name = "prefix")
private String prefix;
#Column(name = "suffix")
private String suffix;
#Column(name = "formatter")
private String formatter;
#Column(name = "lower_bound")
private Long lowerBound;
#Column(name = "upper_bound")
private Long upperBound;
#Column(name = "`separator`")
private String separator;
#Column(name = "created")
#CreationTimestamp
#JsonSerialize(using = CustomLocalDateTimeSerializer.class)
private LocalDateTime created;
#Column(name = "created_by")
private String createdBy;
#Column(name = "updated")
#JsonSerialize(using = CustomLocalDateTimeSerializer.class)
private LocalDateTime updated;
#Column(name = "updated_by")
private String updatedBy;
#JsonIgnore
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#PrimaryKeyJoinColumn
private IdentifierDefinitionEntity identifierDefinitionEntity;
}
IdentifierDefinitionEntity.java
#Entity
#Table(name = "identifier_definition")
#Getter
#Setter
#Builder
#AllArgsConstructor
#NoArgsConstructor
public class IdentifierDefinitionEntity implements Serializable {
private static final long serialVersionUID = 7809377866509417398L;
#Id
#Column(name = "definition_id", columnDefinition = "BINARY(16)")
private UUID definitionId;
#Column(name = "definition_type")
private String definitionType;
#Column(name = "type")
private String type;
#Column(name = "acquirer_id")
private String acquirerId;
#Column(name = "domain")
private String domain;
#Column(name = "processor_id")
private String processorId;
#Column(name = "merchant_id")
private String merchantId;
#Column(name = "status")
private String status;
#Column(name = "is_deleted")
private boolean isDeleted;
#Column(name = "created")
#CreationTimestamp
#JsonSerialize(using = CustomLocalDateTimeSerializer.class)
private LocalDateTime created;
#Column(name = "created_by")
private String createdBy;
#Column(name = "updated")
#JsonSerialize(using = CustomLocalDateTimeSerializer.class)
private LocalDateTime updated;
#Column(name = "updated_by")
private String updatedBy;
#JsonIgnore
#OneToOne(mappedBy = "identifierDefinitionEntity", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private IdentifierPoolDefinitionEntity identifierPoolDefinitionEntity;
#JsonIgnore
#OneToMany(mappedBy = "identifierDefinitionEntity", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private Set<IdentifierListValuesEntity> listValues;
#JsonIgnore
#OneToMany(mappedBy = "identifierDefinitionEntity", fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<IdentifierAssignmentEntity> identifierAssignmentEntity;
}
Driver code:
val allPoolsForProcessor = identifierPoolDefinitionRepository.findAllWithPoolTypeAndStatuses(acquirerId, domain,
listType.getValue(), Arrays.stream(PoolStatus.values())
.map(PoolStatus::getValue)
.collect(Collectors.toList()));
I want to understand why Hibernate is showing this behaviour? Is there a way to restrict the implicit DB calls done by Hibernate?
I think it's something related to this topic : How can I make a JPA OneToOne relation lazy
Try to make the relation explicitly not-nullable and lazy so that hibernate can knows if it can makes a proxy or have to get the real entity for the field identifierDefinitionEntity on IdentifierPoolDefinitionEntity :
#OneToOne(optional = false, fetch = FetchType.LAZY)

JPA - DeletingMapping - ConstraingViolationException

I'm new on Java. I'm doing a HTTPDeleting with JpaRepository(DeleteById) and i recived the following error: ConstraingViolationException - FK_QUESTION_ID cannot be null.
#Entity
#Data
public class Question {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "QUESTION_ID")
private int id;
#Column(nullable = false)
private String title;
#Column(nullable = false)
private String description;
// QUESTION_ID => FOREING KEY COLUMN
#OneToMany(orphanRemoval = true, fetch = FetchType.LAZY, cascade = CascadeType.ALL)
#JoinColumn(name = "FK_QUESTION_ID")
private List<Answer> answers;
#Column(name = "LIKE_COUNT")
private int likeCount;
#Column(name = "INTEREST_AREA_ID", nullable = false)
private int interestAreaId;
#Column(name = "USER_ID", nullable = false)
private int userId;
#Column
private boolean active;
#Column(name = "CREATED_DT", nullable = false)
private Date createdDate;
}
#Entity
#Data
public class Answer {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "ANSWER_ID")
private int answerId;
#Column
private String description;
#Column(name = "LIKE_COUNT")
private int likeCount;
#Column(name = "USER_ID", nullable = false)
private int userId;
#Column
private boolean active;
#Column(name = "CREATED_DT", nullable = false)
private Date createdDate;
#Column(name = "FK_QUESTION_ID")
private int questionId;
}
I read that use CascadeType.Delete is not a good practice, so i used orphanRemoval but even in this way doesn't worked.
questionRepository.deleteById(id);
Your setup is almost correct, except you need to change couple of things here and there. Two important things are:
mappedBy = "question" in the parent entity (Question) targets question field of child entity (Answer)
#JoinColumn should be placed in the child class, through which you specify the column name FK_QUESTION_ID in the Answer table.
Hope, it helps.
#Entity
#Data
public class Question {
#OneToMany(mappedBy = "question", orphanRemoval = true, fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<Answer> answers;
}
#Entity
#Data
public class Answer {
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "FK_QUESTION_ID", nullable = false)
private Question question;
// since you seem to use lombok, you can also use
// answer.getQuestion().getId() instead of this method
public int getQuestionId() {
return this.question.getId(); // question lazy fetching
}
}

jpa entity mapping couple tables

I had entity for JSON parsing
#Entity
public class Product{
private int productId;
private String productName;
private BigDecimal productPrice;
private int productVendorId;
private String productVendorName;
private int productCategoryId;
private String productCategoryName;
//getters setters here
created 3 tables in dataBase:
products (product_id, product_name,product_price, product_vendor_id), product_category_id);
vendors(vendor_id, vendor_name); categories (category_id, category_name);
in 1st table product_vendor_id fk -> vendor_id pk in vendors and product_category_id fk -> category_id pk in categories
i tried something like this:
#Entity
#Table(name = "products, schema = "market")
public class Product
#Id
#Column(updatable = false, nullable = false, name = "product_id")
private int Id;
#Column(name = "product_name")
private String productName;
#Column(name = "product_price")
private BigDecimal productPrice;
#Column(name = "product_vendor_id")
private int productVendorId;
#Columnt(table = "vendors", name = "vendor_name")
private String vendor_name;
#Column(name = "product_category_id")
private int productCategoryId;
#Column(table = "categories", name = "category_name")
private String productCategorName;
//getters setters here
received alot of errors: like i have not category_name column in products table etc. this error i received when used
#Table(name = "products", schema = "market" )
#SecondaryTables({#SecondaryTable(name = "vendors", schema = "market"),
#SecondaryTable(name = "categories", schema = "market")})
#JsonIgnoreProperties(ignoreUnknown = true)
public class Product {
....
#JoinColumn(name = "product_vendor_id", referencedColumnName = "vendor_id")
private int productVendorID;
#JoinColumn(table = "vendors", name = "vendor_name")
private String productVendorName;
#JoinColumn(name = "product_category_id", referencedColumnName =
"product_category_id")
private int productCategoryID;
#JoinColumn(table = "categories", name = "category_name")
private String productCategoryName;
exception:
Caused by: org.postgresql.util.PSQLException: ERROR: column
product0_1_.product_id doesn't exist
Hint: There may have been a link to the "product0_.product_id" column
Position: 705
how can i map this entity on 3 tables?
upd: i don't want separate this entity, i need this for deserialize my json object too, just want reuse this entity on different operations.
example of json
{"productID":"1111111","productName":"Cool product","productPrice":"99.99","productVendorName":"Some store","productVendorID":"1337","productCategoryName":"Food","productCategoryID":"1"}
Since there are 3 separate tables, you would want to create three separate entity classes.
Also I'm assuming vendors and category tables will have one to many relation to product.
Try below code:
Product:
#Entity
public class Product {
#Id
private int productId;
private String productName;
private BigDecimal productPrice;
private String productVendorName;
private String productCategoryName;
#ManyToOne
#JoinColumn(name = "productCategoryId")
private Category category;
#ManyToOne
#JoinColumn(name = "productVendorId")
private Vendors vendor;
}
Category:
#Entity
public class Category {
#Id
private Integer categoryId;
private String categoryName;
#OneToMany(mappedBy = "category", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
#NotEmpty
private List<Product> products = new ArrayList<>();
}
Vendors:
#Entity
public class Vendors {
#Id
private int vendorId;
private String vendorName;
#OneToMany(mappedBy = "vendor", cascade = CascadeType.ALL, fetch = FetchType.LAZY, orphanRemoval = true)
#NotEmpty
private List<Product> products = new ArrayList<>();
}
Though, I would recommend using above approach, if you still want to have single entity class and 3 separate table with redudant data then use below:
#Entity
#SecondaryTables({ #SecondaryTable(name = "vendors"), #SecondaryTable(name = "categories") })
public class Product {
#Id
private int productId;
private String productName;
private BigDecimal productPrice;
private String productVendorName;
private String productCategoryName;
#Column(table = "categories")
private Integer categoryId;
#Column(table = "categories")
private String categoryName;
#Column(table = "vendors")
private int vendorId;
#Column(table = "vendors")
private String vendorName;
}
The id column of the main table will be present in all the 3 tables and used for joining them.
Sorry for poor wording of the question, just didn't know how to explane what i wanted.
All what i need just add #transient annotations for fields which i don't have in products table, and separate it like accepted answer was suggested.
#Entity
#Table(name = "products", schema = "store" )
#JsonIgnoreProperties(ignoreUnknown = true)
public class Product {
#Id
#Column(updatable = false, nullable = false, name = "product_id")
private int productId;
#Column(name = "product_name")
private String productName;
#Column(name = "product_price")
private BigDecimal productPrice;
#Transient
private String productVendorName;
#Transient
private String productCategoryName;
#Transient
private int vendorId;
#Transient
private int categoryId;
#ManyToOne
#JoinColumn(name = "product_category_id")
private Category category;
#ManyToOne
#JoinColumn(name = "product_vendor_id")
private Vendor vendor;
}
for vendors table entity
#Entity
#Table(name = "vendors", schema = "store")
public class Vendor {
#Id
#Column(name = "vendor_id")
private int vendorId;
#Column(name = "vendor_name")
private String vendorName;
#OneToMany(mappedBy = "vendor", cascade = CascadeType.ALL, fetch = FetchType.LAZY,
orphanRemoval = true)
#NotNull
private List<Product> products = new ArrayList<>();
}
and for categories
#Entity
#Table(name = "categories", schema = "store")
public class Category {
#Id
#Column(name = "category_id")
private Integer categoryId;
#Column(name = "category_name")
private String categoryName;
#OneToMany(mappedBy = "category", cascade = CascadeType.ALL, fetch = FetchType.LAZY,
orphanRemoval = true)
#NotNull
private List<Product> products = new ArrayList<>();
}
Wanted to leave here full answer on my question, maybe someone will need it later
Just check some problems with toString. Use it only in Product.class and better make 2 versions for print json and jpa.

JHipster Spring boot : org.hibernate.HibernateException: Unable to access lob stream

I created my app using JHipster. When i try to get list of tournaments via TournamentQueryService i get this error :
Exception in TournamentQueryService.findByCriteria() with cause =
'org.hibernate.HibernateException: Unable to access lob stream' and
exception = 'Unable to access lob stream; nested exception is
org.hibernate.HibernateException: Unable to access lob stream'
This is filter and Page object :
find by criteria : TournamentCriteria{}, page: Page request [number:
0, size 8, sort: startDate: DESC]
So it just gets 8 first tournaments.
This is tournament class :
#Entity
#Table(name = "tournament")
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#Document(indexName = "tournament")
public class Tournament extends AbstractAuditingEntity implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "sequenceGenerator")
#SequenceGenerator(name = "sequenceGenerator")
private Long id;
#Column(name = "name")
private String name;
#Column(name = "location")
private String location;
#Column(name = "url")
private String url;
#Column(name = "start_date")
private ZonedDateTime startDate;
#Column(name = "end_date")
private ZonedDateTime endDate;
#Column(name = "entry_fee")
private Double entryFee;
#Column(name = "prize")
private Double prize;
#Column(name = "goods")
private String goods;
#Column(name = "favorite_rating")
private Long favoriteRating;
#Column(name = "participants_number")
private Integer participantsNumber;
#Column(name = "finished")
private Boolean finished;
#Column(name = "view_only")
private Boolean viewOnly;
#Column(name = "image")
private String image;
#Column(name = "description")
private String description;
#Column(name = "teams_applied")
private String teamsApplied;
#Lob
#Column(name = "schedule")
private String schedule;
#Lob
#Column(name = "prize_distribution")
private String prizeDistribution;
#Lob
#Column(name = "contacts")
private String contacts;
#Lob
#Column(name = "rules")
private String rules;
#OneToMany(mappedBy = "tournament", fetch = FetchType.LAZY)
#JsonIgnore
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
private Set<Stream> streams = new HashSet<>();
#ManyToMany(fetch = FetchType.EAGER)
#Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE)
#JoinTable(name = "tournament_platforms", joinColumns = #JoinColumn(name = "tournaments_id", referencedColumnName = "id"), inverseJoinColumns = #JoinColumn(name = "platforms_id", referencedColumnName = "id"))
private Set<Platform> platforms = new HashSet<>();
#ManyToOne
private Game game;
#ManyToOne
private TournamentStatus status;
#ManyToOne(fetch = FetchType.LAZY)
private EntryType entryType;
#ManyToOne(fetch = FetchType.LAZY)
private TournamentFormat format;
#ManyToOne
private Region region;
#ManyToOne(fetch = FetchType.LAZY)
private GameMode gameMode;
#ManyToOne(fetch = FetchType.LAZY)
private PrizeType prizeType;
#ManyToOne
private Organizer organizer;
#ManyToOne(fetch = FetchType.LAZY)
private TournamentStage stage;
#ManyToOne
private HostPlatform hostPlatforms;
#ManyToOne(fetch = FetchType.LAZY)
private TournamentType type;
#ManyToOne
private PlayType playType;
#ManyToOne
private Currency currency;
#ManyToOne
private Country country;
Here is the method that calls hibernate :
#Transactional(readOnly = true)
public Page<Tournament> findByCriteria(TournamentCriteria criteria, Pageable page) {
log.info("find by criteria : {}, page: {}", criteria, page);
final Specifications<Tournament> specification = createSpecification(criteria);
Page<Tournament> result = tournamentRepository.findAll(specification, page);
return result;
}
Is it possibile that you are trying to access Lob properties when hiberante session is closed?
Try to replace your #Lob properties with the following:
#Basic(fetch=FetchType.EAGER) #Lob
and check if the error persists.

Referential integrity constraint violation error in JPA

I am trying to parse a web request and save to database. I have 3 models and first node is virtualDocument. This is the uniq table (according to request url). VirtualRequest table has all erquest bodies and HttpHeaderList table has all thhp headers according to their virtualRequest bean id.
when I tried to save the first log I got and error like this;
org.h2.jdbc.JdbcSQLException: Referential integrity constraint violation: "FK1TW2G47F7A47580KQVMDJWGBQ: PUBLIC.T_VIRTUAL_REQUEST FOREIGN KEY(REQUEST_ID) REFERENCES PUBLIC.T_VIRTUAL_DOCUMENT(DOCUMENT_ID) (65)"; SQL statement:
insert into t_virtual_request (request_id, media_type, method_type, request_url) values (null, ?, ?, ?) [23506-192]
at org.h2.message.DbException.getJdbcSQLException(DbException.java:345) ~[h2-1.4.192.jar:1.4.192]
here is VirtualDocument bean
#Entity
#Table(name = "t_virtual_document")
public class VirtualDocument {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "document_id")
private long documentId;
#Column(name = "real_url", unique = true)
private String realURL; //uniq
#Column(name = "virtual_url", unique = true)
private String virtualURL; //uniq
#Column(name = "simulation_mode", columnDefinition = "varchar(10) default 'STOP'")
private String simulationMode;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "request_id")
private List<VirtualRequest> requestList;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "response_id")
private List<VirtualResponse> responseList;
//getter setter without any annotation
}
here is VirtualRequest bean;
#Entity
#Table(name = "t_virtual_request")
public class VirtualRequest {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "request_id")
private long requestId;
#Column(name = "request_url")
private String requestURL;
#Column(name = "method_type")
private String methodType;
#Column(name = "media_type")
private String mediaType;
#OneToMany(cascade = CascadeType.ALL)
#JoinColumn(name = "header_id")
private List<HttpHeaderList> requestHeaders;
//getter setter without any annotation
}
here is HeaderList bean;
#Entity
#Table(name = "t_http_headers")
public class HttpHeaderList {
#Id
#Column(name = "header_id")
private long headerId;
#Column(name = "header_key")
private String headerKey;
#Column(name = "header_value")
private String headerValue;
}
I think this is what you want instead:
#Entity
#Table(name = "t_virtual_document")
public class VirtualDocument {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "document_id")
private long documentId;
#Column(name = "real_url", unique = true)
private String realURL; //uniq
#Column(name = "virtual_url", unique = true)
private String virtualURL; //uniq
#Column(name = "simulation_mode", columnDefinition = "varchar(10) default 'STOP'")
private String simulationMode;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "virtualDocument")
private List<VirtualRequest> requestList;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "virtualDocument")
// Note the mappedBy parameter. This points to the property in the entity that owns the relationship (in this case the VirtualResponse).
private List<VirtualResponse> responseList;
//getter setter without any annotation
}
#Entity
#Table(name = "t_virtual_request")
public class VirtualRequest {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "request_id")
private long requestId;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "document_id")
private VirtualDocument virtualDocument;
#Column(name = "request_url")
private String requestURL;
#Column(name = "method_type")
private String methodType;
#Column(name = "media_type")
private String mediaType;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "virtualRequest")
private List<HttpHeaderList> requestHeaders;
//getter setter without any annotation
}
#Entity
#Table(name = "t_http_headers")
public class HttpHeader { /*Note this is a more appropriate name for the entity since it holds the data of a single header.*/
#Id
#Column(name = "header_id")
private long headerId;
#Column(name = "header_key")
private String headerKey;
#Column(name = "header_value")
private String headerValue;
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "request_id")
private VirtualRequest virtualRequest
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "response_id")
private VirtualResponse virtualResponse;
}
Updated the answer to add mapping the headers to the request entity.

Categories

Resources