How to persist a property of type List<List<Object>> in JPA? - list

What is the smartest way to get an entity with a field of type List<List> persisted?
#Entity
#Table(name = "Final_Feign_Client_Result")
public class FinalFCResultEntity {
#Id
#Column(name = "id")
#GeneratedValue(strategy = IDENTITY)
private Integer id;
#ElementCollection(targetClass = Object.class)
#CollectionTable(name = "Final_Feign_Client_Result_Columns")
#OnDelete(action = OnDeleteAction.CASCADE)
#JoinColumn(name = "final_feign_client_result_entity_id", nullable = false)
private Set<Object> values;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public Set<Object> getValues() {
return values;
}
public void setValues(Set<Object> values) {
this.values = values;
}
}
I have no problem with columns, but if I try to insert values I get this exception:
Caused by: org.hibernate.MappingException: Could not determine type for: java.util.List, at table: final_feign_client_result_columns, for columns: [org.hibernate.mapping.Column(values)]
How I can solve this problem?

Hi guidop21 please add
#ElementCollection(targetClass = Object.class)
#CollectionTable(name = "Final_Feign_Client_Result_Columns")
#OnDelete(action = OnDeleteAction.CASCADE)
#JoinColumn(name = "final_feign_client_result_entity_id", nullable = false)
#OneToMany
private List<List<<Object>> values;

Related

java.lang.AssertionError: expected:<ON> but was:<com.spacestudy.model.Account#783f5f71>

I am trying to write a JUnit test case for the following search filter method. I am using Querydsl for the search filter. The following method does not depend on Repository; that is why I am not using mockito. This is the first time I am writing a test case for such a method. Please give any suggestions, if you have any?
public List<Tuple> btnSearchClick(String sClientAcctId, String sAcctDesc, String sInvestigatorName,
String sClientDeptId) throws Exception {
QAccount account = QAccount.account;
QDepartment department = QDepartment.department;
QAccountCPCMapping accountCPCMapping = QAccountCPCMapping.accountCPCMapping;
QInvestigator investigator = QInvestigator.investigator;
JPAQuery<Tuple> query = new JPAQuery<Tuple>(em);
query.select(Projections.bean(Account.class, account.sClientAcctId, account.sAcctDesc, account.sLocation,
Projections.bean(Department.class, department.sDeptName, department.sClientDeptId).as("department"),
Projections.bean(Investigator.class, investigator.sInvestigatorName).as("investigator"),
Projections.bean(AccountCPCMapping.class, accountCPCMapping.sCCPCode).as("accountCPC"))).from(account)
.innerJoin(account.department, department).innerJoin(account.accountCPC, accountCPCMapping)
.innerJoin(account.investigator, investigator).where(account.nInstId.eq(60));
Test case
#Test
public void btnSearchClick() throws Exception {
List<Tuple> account= accountService.btnSearchClick("1124100", sAcctDesc, sInvestigatorName, sClientDeptId);
Department dep = new Department();
dep.setsDeptName("Deans Office");
dep.setsClientDeptId("120010");
Investigator invest = new Investigator();
invest.setsInvestigatorName("Ram, Sri");
AccountCPCMapping cpc = new AccountCPCMapping();
cpc.setsCCPCode("RT");
Account acc = new Account();
acc.setsLocation("ON");
acc.setsAcctDesc("SRIRAM");
acc.setsClientAcctId("1124100");
acc.setInvestigator(invest);
acc.setDepartment(dep);
acc.setAccountCPC(cpc);
accountRepo.save(acc);
assertEquals(acc.getsLocation(), account.get(0));
}
Account.java
#Entity
#Table(name = "account")
#JsonInclude(JsonInclude.Include.NON_NULL)
public class Account implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "account_seq_generator")
#SequenceGenerator(name = "account_seq_generator", sequenceName = "account_seq")
#Column(name = "naccount_id")
public Integer nAccountId;
#Column(name = "namount")
public String nAmount;
#Column(name = "sacct_desc")
public String sAcctDesc;
#Column(name = "naccount_cpc_mapping_id")
public Integer nAccountCPCMappingId;
#Column(name = "nindirect_cost_rate")
public Integer nIndiretCostRate;
#Column(name = "nagency_id")
public Integer nAgencyId;
#Column(name = "ndept_id")
public Integer nDeptId;
#Column(name = "sgrant_num")
public String sGrantNum;
#Column(name = "dstart_date")
public Timestamp dStartDate;
#Column(name = "dend_date")
public Timestamp dEndDate;
#Column(name = "slocation")
public String sLocation;
#Column(name = "sclient_acct_id")
public String sClientAcctId;
#Column(name = "ninvestigator_id")
public Integer nInvestigatorId;
#Column(name = "ninst_id")
public Integer nInstId;
#Column(name = "ntemp_account_id")
public Integer nTempAccountId;
#ManyToOne(optional = true, cascade = { CascadeType.MERGE })
#JoinColumn(name = "ndept_id", insertable = false, updatable = false)
public Department department;
#ManyToOne(optional = true, cascade = { CascadeType.ALL })
#JoinColumn(name = "ninvestigator_id", insertable = false, updatable = false)
public Investigator investigator;
#ManyToOne(optional = true, cascade = { CascadeType.ALL })
#JoinColumn(name = "naccount_cpc_mapping_id", insertable = false, updatable = false)
public AccountCPCMapping accountCPC;
// Getter and Setter
Stack Trace
java.lang.AssertionError: expected:<ON> but was:<com.spacestudy.model.Account#783f5f71>
at org.junit.Assert.fail(Assert.java:88)
at org.junit.Assert.failNotEquals(Assert.java:834)
at org.junit.Assert.assertEquals(Assert.java:118)
at org.junit.Assert.assertEquals(Assert.java:144)
at com.spacestudy.service.TestAccountService.btnSearchClick(TestAccountService.java:120)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
Output from postman
[
{
"sAcctDesc": "SRIRAM",
"sLocation": "ON",
"sClientAcctId": "1124100",
"department": {
"sDeptName": "Deans Office",
"sClientDeptId": "120010"
},
"investigator": {
"sInvestigatorName": "Ram, Sri"
},
"accountCPC": {
"sCCPCode": "RT"
}
}
]
Can anyone please tell me what I am doing wrong in my test case, or suggest an alternative to the code above.
Lists are zero-indexed. That means that if your list has only 1 element, it's index will be 0, not 1.
The element with index 1 is actually the second one (which doesn't exist, thus the index out of bounds).
account.get(1)
should be
account.get(0);

Validation of the application resource model has failed during application initialization

I'm trying to create a simple get request using jersey
but got exception
can someone tell me where I got it wrong?
The excption is - "Caused by: org.glassfish.jersey.server.model.ModelValidationException: Validation of the application resource model has failed during application initialization.
"
VersionResource.java
#Path("/versions")
public class VersionResource extends BaseResource<VersionDao, VersionTable>
{
public VersionResource(VersionDao objectDao)
{
super(objectDao);
}
#Override
#Path("/getAppVersions")
#GET
#UnitOfWork
public String getAllRecords(#Context HttpServletRequest req, #QueryParam("callback") String callback) throws JsonProcessingException
{
return super.getAllRecords(req, callback);
}
}
VersionTable.java
#Entity(name = "Versions")
#Table(name = "Versions")
#NamedQueries({ #NamedQuery(name = QueryNames.QUERY_VERSION_GET_ALL, query = "select c from Versions c"), })
public class VersionTable extends baseDataBase implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "VersionId")
private short versionId;
#Column(name = "VersionPlatform")
#JsonProperty
#NotEmpty
private String versionPlatform;
#Column(name = "VersionNumber")
#JsonProperty
#NotEmpty
private String versionNumber;
#Column(name = "VersionDescription")
#JsonProperty
#NotEmpty
private String versionDescription;
public short getVersionId()
{
return versionId;
}
public void setVersionId(short versionId)
{
this.versionId = versionId;
}
public String VersionPlatformEnum()
{
return versionPlatform;
}
public void setVersionPlatform(String versionPlatform)
{
this.versionPlatform = versionPlatform;
}
public String getVersionNumber()
{
return versionNumber;
}
public void setVersionNumber(String versionNumber)
{
this.versionNumber = versionNumber;
}
public String getVersionDescription()
{
return versionDescription;
}
public void setVersionDescription(String versionDescription)
{
this.versionDescription = versionDescription;
}
}
VersionDao.java
public class VersionDao extends baseAbstractDao<VersionTable> implements IDatabaseActions<VersionTable>
{
public VersionDao(SessionFactory sessionFactory)
{
super(sessionFactory);
}
#Override
public ObjectDaoResponse getAllTableRecords() throws JsonProcessingException
{
List<VersionTable> list = list(namedQuery(QueryNames.QUERY_VERSION_GET_ALL));
return ObjectDaoResponse.getAnOkResponse(list);
}
}
I think you need a no arg constructor for your VersionResource class, but if you really need an argument the value should be passed by injection (see: https://eclipse-ee4j.github.io/jersey.github.io/documentation/latest/jaxrs-resources.html#d0e2692)

Hibernate criteria cannot fetch rows could not resolve property

Hi i have these 2 basic entity mapping for postgresql db, and i have wrote criteria for
fetching all activated user which have same key it is showing this error
org.hibernate.QueryException: could not resolve property: key.id of: com.sar.dfsapp.modal.ActivatedUser
#Entity
#Table(name = "activated_user")
public class ActivatedUser implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, length = 11)
private long id;
#ManyToOne
#JoinColumn(name = "key_id", nullable = false)
private Key key;
}
#Entity
#Table(name = "key")
public class Key implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Column(name = "id", nullable = false, length = 11)
private long id;
#Column(name = "key_code", nullable = false)
private String keyCode;
}
Below is my criteria i have tried.
Criteria c = getSession().createCriteria(ActivatedUser.class);
c.add(Restrictions.eq("key.id", id));
List<ActivatedUser> result = c.list();
try this :
Criteria c = getSession().createCriteria(ActivatedUser.class);
Criteria keyCriteria = criteria.createCriteria("key", CriteriaSpecification.INNER_JOIN);
keyCriteria.add(Restrictions.eq("id", id));
List<ActivatedUser> result = c.list();
it there the same error ?

JPA query filtered by a collection's property in a OneToMany relationship

hope somebaody can help me. I have two entities related OneToMany.
First:
#Entity
#Table(name = "repartos")
#XmlRootElement
public class Repartos implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#Basic(optional = false)
#NotNull
#Column(name = "fecha")
#Temporal(TemporalType.DATE)
private Date fecha;
#OneToMany(cascade = {CascadeType.ALL}, mappedBy = "repartoId")
public List<RepartosDetalle> repartosDetalleList;
.....
And then the another one:
#Entity
#Table(name = "repartos_detalle")
#XmlRootElement
public class RepartosDetalle implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "id")
private Integer id;
#JoinColumn(name = "reparto_id", referencedColumnName = "id")
#ManyToOne(optional = false)
private Repartos repartoId;
#Column(name = "descargado")
#Convert(converter = BooleanOneZeroConverter.class)
private boolean descargado;
public RepartosDetalle() {
}
public RepartosDetalle(Repartos repartoId) {
this.repartoId = repartoId;
}
public Repartos getRepartoId() {
return repartoId;
}
public void setRepartoId(Repartos repartoId) {
this.repartoId = repartoId;
}
public boolean isDescargado() {
return descargado;
}
public void setDescargado(boolean descargado) {
this.descargado = descargado;
}
}
What I try to get is all the Repartos given a date and where they have al least one RepartosDetalle with the property descargado=TRUE.
I've been trying with the following query but I do't get any result.
#Override
public List<Repartos> buscarPorFechaDescargados(Date searchDate) {
Query q = em.createQuery("SELECT e FROM Repartos e "
+ "WHERE e.fecha = :searchDate"
+ " AND e.repartosDetalleList.descargado=TRUE");
q.setParameter("searchDate", searchDate);
return q.getResultList();
}
Is there a proper way to make this query using one of the collection's property value?
Thanks a lot and nice weekend.
Try to use JOIN operator on these 2 entities - Repartos and RepartosDetalle :
SELECT e FROM Repartos e JOIN RepartosDetalle d
WHERE e.fecha = :searchDate
AND d.descargado = TRUE

How to set value of list<String> in DynamicJasper

I need to generate dynamic count of columns in me report. So I set to my JasperPrint the massive of Object:
Object[] obj = new Object[selectedUsers.size()];
//fill the massive
JasperPrint jp = DynamicJasperHelper.generateJasperPrint(dr, new ClassicLayoutManager(), new JRBeanArrayDataSource(obj));
My obj is a class:
public class ResultsDTO {
private String login;
private Integer id;
private List<String> list;
private Object[] results;
public Object[] getResults() {
return results;
}
public void setResults(Object[] results) {
this.results = results;
}
public ResultsDTO(){
}
public ResultsDTO(Integer id,String login) {
super();
this.login = login;
this.id = id;
}
public ResultsDTO(String login, Integer id, List<String> list) {
super();
this.login = login;
this.id = id;
this.list = list;
}
public String getLogin() {
return login;
}
public void setLogin(String login) {
this.login = login;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public List<String> getList() {
return list;
}
public void setList(List<String> list) {
this.list = list;
}
public void addToList(String day_result){
this.list.add(day_result);
}
}
and then I try to create columns:
FastReportBuilder firstReport = new FastReportBuilder();
List<AbstractColumn> column_list = new ArrayList<AbstractColumn>();
AbstractColumn columnId = getColumn("id", Integer.class,"№", 30, headerStyle, detailStyle);
AbstractColumn columnLogin = getColumn("login", String.class,"ФИО", 150, headerStyle, detailStyle);
for (int i = 0; i < header.size(); i++){
AbstractColumn column = getColumn("results", Object.class, header.get(i), 80, headerStyle, detailStyle);
column_list.add(column);
}
Eventually I have an exception:
net.sf.jasperreports.engine.design.JRValidationException: Report
design not valid :
1. Class "java.lang.Object" not supported for text field expression.
Please, help! I don' know how to use jasper and list or array
Jasper Reports does not allow Object as a valid type for its elements. I has to be one of the following:
String
Number (or any subclass of it)
Date
Boolean
You should ask each element in the form for its class and pass proper class to the column builder.