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

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.

Related

Id declaration in Spring

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()

JPQL returns all associated Entities

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.

Mysql - JPA no insert into thrid table Many to Many

I have Many-To-Many relation in my project, i can write in my two Entities table, the relational table does not get anything written.
EspecificacionEscenario Class:
public class EspecificacionEscenario implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idespecificacionEscenario")
private Integer idespecificacionEscenario;
#Column(name = "codigo")
private String codigo;
#Column(name = "fecha")
#Temporal(TemporalType.TIMESTAMP)
private Date fecha;
#Column(name = "nombreProceso")
private String nombreProceso;
#Column(name = "nombreEscenario")
private String nombreEscenario;
#Column(name = "objetivoEscenario")
private String objetivoEscenario;
#Column(name = "lugarEscenario")
private String lugarEscenario;
#Column(name = "recursoEscenario")
private String recursoEscenario;
#Column(name = "restriccionEscenario")
private String restriccionEscenario;
#Column(name = "actoresEscenario")
private String actoresEscenario;
#ManyToMany(mappedBy = "especificacionEscenarioList", fetch = FetchType.LAZY)
private List<Elicitacion> elicitacionList;
#ManyToMany(mappedBy = "especificacionEscenarioList", fetch = FetchType.LAZY)
private List<Episodio> episodioList;
#ManyToMany(mappedBy = "especificacionEscenarioList", fetch = FetchType.LAZY)
private List<Educcion> educcionList;
Episodio class:
public class Episodio implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idepisodio")
private Integer idepisodio;
#Column(name = "codigo")
private String codigo;
#Column(name = "objetivoEpisodio")
private String objetivoEpisodio;
#Column(name = "descripcionEpisodio")
private String descripcionEpisodio;
#Column(name = "recursosEpisodio")
private String recursosEpisodio;
#Column(name = "restriccionEpisodio")
private String restriccionEpisodio;
#Column(name = "actor")
private String actor;
#JoinTable(name = "especificacionEscenarioEpisodio", joinColumns = {
#JoinColumn(name = "idepisodio", referencedColumnName = "idepisodio")}, inverseJoinColumns = {
#JoinColumn(name = "idespecificacionEscenario", referencedColumnName = "idespecificacionEscenario")})
#ManyToMany(fetch = FetchType.LAZY)
private List<EspecificacionEscenario> especificacionEscenarioList;
Main code:
public static void main(String[] args) {
EpisodioDao episodioDao = new EpisodioDao();
EspecificacionEscenarioDao escenarioDao = new EspecificacionEscenarioDao();
Episodio episodio = new Episodio();
episodio.setCodigo("e01");
episodio.setDescripcionEpisodio("descripcion episodio");
EspecificacionEscenario ee = new EspecificacionEscenario();
ee.setCodigo("ee-01");
List<Episodio> listaE = new ArrayList<>();
listaE.add(episodio);
ee.setEpisodioList(listaE);
episodioDao.registrarEpisodio(episodio);
System.exit(0);
}
when doing the persistence in the entities the information is saved automatically, but in the table third table it does not insert the primary keys.
I have added CascadeType.ALL on Episodio as it is the owner of this relation.
Following code may help you. I have tested with spring data jpa.
#Setter
#Getter
#Entity
public class Episodio implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idepisodio")
private Integer idepisodio;
#Column(name = "codigo")
private String codigo;
#Column(name = "objetivoEpisodio")
private String objetivoEpisodio;
#Column(name = "descripcionEpisodio")
private String descripcionEpisodio;
#Column(name = "recursosEpisodio")
private String recursosEpisodio;
#Column(name = "restriccionEpisodio")
private String restriccionEpisodio;
#Column(name = "actor")
private String actor;
#JoinTable(name = "especificacionEscenarioEpisodio",
joinColumns = {
#JoinColumn(name = "idepisodio", referencedColumnName = "idepisodio")},
inverseJoinColumns = {
#JoinColumn(name = "idespecificacionEscenario", referencedColumnName = "idespecificacionEscenario")})
#ManyToMany(fetch = FetchType.LAZY, cascade = CascadeType.ALL)
private List<EspecificacionEscenario> especificacionEscenarioList;
}
#Setter
#Getter
#Entity
public class EspecificacionEscenario implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "idespecificacionEscenario")
private Integer idespecificacionEscenario;
#Column(name = "codigo")
private String codigo;
#Column(name = "fecha")
#Temporal(TemporalType.TIMESTAMP)
private Date fecha;
#Column(name = "nombreProceso")
private String nombreProceso;
#Column(name = "nombreEscenario")
private String nombreEscenario;
#Column(name = "objetivoEscenario")
private String objetivoEscenario;
#Column(name = "lugarEscenario")
private String lugarEscenario;
#Column(name = "recursoEscenario")
private String recursoEscenario;
#Column(name = "restriccionEscenario")
private String restriccionEscenario;
#Column(name = "actoresEscenario")
private String actoresEscenario;
#ManyToMany(mappedBy = "especificacionEscenarioList", fetch = FetchType.LAZY)
private List<Episodio> episodioList;
}
EspecificacionEscenario especificacionEscenario = new EspecificacionEscenario();
especificacionEscenario.setCodigo("ee-01");
List<EspecificacionEscenario> especificacionEscenarios = new ArrayList<>();
especificacionEscenarios.add(especificacionEscenario);
Episodio episodio = new Episodio();
episodio.setCodigo("e01");
episodio.setDescripcionEpisodio("descripcion episodio");
episodio.setEspecificacionEscenarioList(especificacionEscenarios);
episodioRepo.save(episodio);

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.

Join table with Primary Key: org.hibernate.mapping.SimpleValue cannot be cast to org.hibernate.mapping.Component

public class Employee implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "employee_id")
private Integer employeeId;
#Column(name = "doj")
#Temporal(TemporalType.DATE)
private Date doj;
#Column(name = "first_name")
private String firstName;
#Column(name = "last_name")
private String lastName;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "id.employee")
private Set<EmployeeProject> employeeProject;
//
Project.java
public class Project implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "project_id")
private Integer projectId;
#Column(name = "exp_end_date")
#Temporal(TemporalType.DATE)
private Date expEndDate;
#Column(name = "project_name")
private String projectName;
#Column(name = "start_date")
#Temporal(TemporalType.DATE)
private Date startDate;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "id.project")
private Set<EmployeeProject> employeeProject;
EmployeeProject.java
#IdClass(EmployeeProjectPK.class)
public class EmployeeProject implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Id
#Column(name = "PROJECT_ID", insertable = false, updatable = false)
private int projectId;
#Id
#Column(name = "employee_id", insertable = false, updatable = false)
private int employeeId;
#ManyToOne
#JoinColumn(name = "employee_id")
private Employee employee;
#ManyToOne
#JoinColumn(name = "project_id")
private Project project;
EmployeeProjectPK.Java
public class EmployeeProjectPK implements Serializable {
private static final long serialVersionUID = 1L;
private Integer id;
private Integer projectId;
private Integer employeeId;
Based on above entity design, when I try to persist an 'Employee', I'm getting bellow exception. Any thought?
Caused by: java.lang.ClassCastException: org.hibernate.mapping.SimpleValue cannot be cast to org.hibernate.mapping.Component
I think your problem in mapped by in Employee entity
can you please try using
#OneToMany(cascade = CascadeType.ALL, mappedBy = "employee")
private Set<EmployeeProject> employeeProject;
instead of
#OneToMany(cascade = CascadeType.ALL, mappedBy = "id.employee")
private Set<EmployeeProject> employeeProject;
Also try to change it too in Project entity and use
#OneToMany(cascade = CascadeType.ALL, mappedBy = "project")
private Set<EmployeeProject> employeeProject;
instead of
#OneToMany(cascade = CascadeType.ALL, mappedBy = "id.project")
private Set<EmployeeProject> employeeProject;
So finally you should replace
mappedBy = "id.project" by mappedBy = "project"
AND
mappedBy = "id.employee" by mappedBy = "employee"

Categories

Resources