How to get comma separated value using JPA in Database - database

enter image description here
Currently I've been problem what get my database data.. Because That's fileIdx Column was be Comma Seperated value
Problem is..
Caused by: java.sql.SQLException: Out of range value for column 'fileidx7_4_' : value 322,323
at org.mariadb.jdbc.internal.com.read.resultset.rowprotocol.TextRowProtocol.getInternalLong(TextRowProtocol.java:349)
at org.mariadb.jdbc.internal.com.read.resultset.SelectResultSet.getLong(SelectResultSet.java:1001)
at org.mariadb.jdbc.internal.com.read.resultset.SelectResultSet.getLong(SelectResultSet.java:995)
at com.zaxxer.hikari.pool.HikariProxyResultSet.getLong(HikariProxyResultSet.java)
at org.hibernate.type.descriptor.sql.BigIntTypeDescriptor$2.doExtract(BigIntTypeDescriptor.java:63)
at org.hibernate.type.descriptor.sql.BasicExtractor.extract(BasicExtractor.java:47)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:257)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:253)
at org.hibernate.type.AbstractStandardBasicType.nullSafeGet(AbstractStandardBasicType.java:243)
at org.hibernate.type.AbstractStandardBasicType.hydrate(AbstractStandardBasicType.java:329)
at org.hibernate.type.ManyToOneType.hydrate(ManyToOneType.java:184)
at org.hibernate.persister.entity.AbstractEntityPersister.hydrate(AbstractEntityPersister.java:3088)
at org.hibernate.loader.Loader.loadFromResultSet(Loader.java:1907)
at org.hibernate.loader.Loader.hydrateEntityState(Loader.java:1835)
at org.hibernate.loader.Loader.instanceNotYetLoaded(Loader.java:1808)
at org.hibernate.loader.Loader.getRow(Loader.java:1660)
at org.hibernate.loader.Loader.getRowFromResultSet(Loader.java:745)
at org.hibernate.loader.Loader.getRowsFromResultSet(Loader.java:1044)
at org.hibernate.loader.Loader.processResultSet(Loader.java:995)
at org.hibernate.loader.Loader.doQuery(Loader.java:964)
at org.hibernate.loader.Loader.doQueryAndInitializeNonLazyCollections(Loader.java:350)
at org.hibernate.loader.Loader.doList(Loader.java:2887)
... 108 more
It is my Entity ↓↓↓↓↓
#Entity
public class Board {
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Long idx;
private Long code;
private Long adminIdx;
private String write;
private String title;
private String content;
private String fileIdx;
private String deleted;
#Column(name = "sDate")
private Long sdate;
#Column(name = "eDate")
private Long edate;
private Long regdate;
It is my JpaRepository Method used JPQL ↓↓↓↓↓
#Query(value = "select b from Board b")
List<Board> getTest();
It is my TestCode ↓↓↓↓↓
#Test
public void test(){
List<Board> shopBoardEntity = boardRepository.getTest();
shopBoardEntity.forEach(o -> {
System.out.println("dddd : " + o.getTitle());
});
}
No matter how hard I try, I don't know..
Anyone Idea??

Related

Poor query performance even with proper Indexing

So we have 15million data is this table :allocation_plan_detail. I have put all necessary column in the non-clustered index and rest all other inside Include statement is while querying we are selecting *.
Here is the Index defination :
CREATE NONCLUSTERED INDEX [newNonClusteredIndex] ON [Allocation].[allocation_plan_detail]
(
[tenant_id] ASC,
[item_type] ASC,
[allocation_plan_status] ASC,
[allocation_plan_type] ASC,
[item_nbr] ASC,
[club_nbr] ASC
)
INCLUDE([item_config_id],[club_name],[dept_nbr],[subcat_nbr],[dc_nbr],[total_dc_on_hand_qty],[vc_nbr],[city_addr],[state_addr],[item_status_code],[base_unit_rtl_amt],[item_on_shelf_date],[item_off_shelf_date],[on_hand_qty],[on_order_qty],[total_inventory],[wkly_sales],[total_sales],[days_with_inventory],[avg_wos_planner],[forecast_level],[club_decile_nbr],[decile_rank],[current_wos],[projected_wos],[wos_target],[min_pres_qty],[max_inv_level],[oos_threshold],[moq],[lead_time],[mabd],[unconstrained_need_qty],[true_need_qty],[adjusted_planner_qty],[manual_override_planner_qty],[allocation_seq_nbr],[created_by],[created_on],[last_updated_by],[last_updated_on])
Now I am querying this :
select * from Allocation.allocation_plan_detail --with(index(newNonClusteredIndex))
where
allocation_plan_status='draft' and
item_type ='In season' and tenant_id='sams_us' and
allocation_plan_type='continuous' and
item_nbr in (980109489,326156,678518,980098926,980143632,299324,916205,207317,338064,433702,980427979,....upto 200 elements..)
With explicit index mention the plan:
Now even though I properly mentioned indexes why it scanning table? Now by some research in SO I am assuming its being done because IN clause has too many elements. But even with Index Seeking my query is taking on average to give output of 50k data for 5-6min avg!! Now I am completely clueless what exactly to do optimize the query ? I have tried with storing the IN elements into temporary table but yet I dont see any improvement. Any suggestions ?
Here is the table defination (Model)
public class AllocationPlanDetail extends BaseEntity{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#NotNull(groups = Existing.class)
#Null(groups = New.class)
private Long allocationPlanDetailId;
#NotNull
private Long itemConfigId;
#NotNull
private Long itemNbr;
#NotNull
private Integer clubNbr;
private String clubName;
private Integer deptNbr;
private Integer subcatNbr;
private Integer dcNbr;
private Integer totalDcOnHandQty;
private Integer vcNbr;
private String cityAddr;
private String stateAddr;
private String itemStatusCode;
private Float baseUnitRtlAmt;
private Date itemOnShelfDate;
private Date itemOffShelfDate;
private Integer onHandQty;
private Integer onOrderQty;
private Integer totalInventory;
#Column(name="wkly_sales",columnDefinition="nvarchar")
#Convert(converter = SalesConverterJson.class)
private Map<String,Float> wklySales;
private Float totalSales;
private Integer daysWithInventory;
#Column(name="avg_wos_planner")
private Float avgWOSPlanner;
private String forecastLevel;
private Integer clubDecileNbr;
private Integer decileRank;
#Column(name="current_wos")
private Float currentWOS;
#Column(name="projected_wos")
private Float projectedWOS;
private Integer wosTarget;
#Column(name="min_pres_qty")
private Integer minPres;
#Column(name="max_inv_level")
private Integer maxClubQty;
private Integer oosThreshold;
private Integer moq;
private Integer leadTime;
private Date mabd;
private Integer unconstrainedNeedQty;
private Integer trueNeedQty;
private Integer adjustedPlannerQty;
private Integer manualOverridePlannerQty;
private Integer allocationSeqNbr;
private String allocationPlanType;
private String allocationPlanStatus;
private String itemType;
#NotNull
private String tenantId;
I have asked similar quetion here : Getting Index Scan instead Index Seeking if IN clause larger in Azure Sql
But that time I havent included the INCLUDE clause in my index FYI. And second image got duplicated apology for that..

Retrieving a field on a relation based on the FK

I am taking my first steps into jpa (porting the whole db from jdbc to jpa) and i was wondering how i can achieve the following:
I have two tables, a Users table and a ProfileImages table, the ProfileImages table consists in a FK to user_id and then another field which is a byte array (which holds the image's bytes).
What i am trying to achieve is being able to recover the byte array directly in my User model, something in the lines of:
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "users_userid_seq")
#SequenceGenerator(name = "users_userid_seq", sequenceName = "users_userid_seq", allocationSize = 1)
private Long userId;
#Column
private String name;
#Column
private String surname;
#Column(nullable = false, unique = true)
private String username;
#Column(nullable = false, unique = true)
private String email;
#Column
private String password;
#Column(nullable = false, unique = true)
private Integer fileNumber;
#Column
private boolean isAdmin;
// Map the byte array from the profile_image relation
private byte[] image;
.....
.....
}
Note: It'd be optimal to not change the schema to make the user hold the byte array.
You can use the SecondaryTable annotation to map two tables to one Entity:
#Entity
#Table(name = "users")
#SecondaryTable(name = "profileimages",
pkJoinColumns = #PrimaryKeyJoinColumn(name = "user_id"))
public class User {
#Column(name = "image", table = "profileimages")
private byte[] image;
Please also check out the documentation:
https://docs.jboss.org/hibernate/orm/5.5/userguide/html_single/Hibernate_User_Guide.html#sql-custom-crud-secondary-table-example

Join 3 table using Hibernate Entities with multiple columns

Can someone help me how should I join those three tables using JPA?
I already did 2 of 3 entities but please let me know if are ok:
#Entity
public class Pacienti {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String nume;
private String prenume;
//setters & getters
}
#Entity
public class Chestionare {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
#Id
#Column(name = "id_intrebare")
#GeneratedValue(strategy = GenerationType.AUTO)
private int idIntrebare;
private String intrebare;
//setters & getters
}
As I promise I come back after I'm generating entities automatically. Unfortunately now I have another problem.
Now I have the entity:
#Entity
#Table(name = "pacienti")
#NamedQuery(name = "Pacienti.findAll", query = "SELECT p FROM Pacienti p")
public class Pacienti implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(unique = true, nullable = false)
private int id;
#Column(nullable = false, length = 20)
private String nume;
#Column(nullable = false, length = 20)
private String prenume;
// bi-directional many-to-one association to Consultatii
#OneToMany(mappedBy = "pacienti")
private List<Consultatii> consultatiis;
// bi-directional many-to-one association to DetaliiPacient
#OneToMany(mappedBy = "pacienti")
private List<DetaliiPacient> detaliiPacients;
// bi-directional many-to-one association to Doctori
#ManyToOne(fetch = FetchType.LAZY)
#JoinColumn(name = "id_doctor", nullable = false)
private Doctori doctori;
// bi-directional many-to-one association to RaspunsChestionar
#OneToMany(mappedBy = "pacienti")
private List<RaspunsChestionar> raspunsChestionars;
public Pacienti() {
}
//setters and getters
}
But when I do :
Query queryResult = sessionFactory.getCurrentSession().createQuery("from Pacienti");
I'm getting:
Pacienti is not mapped [from Pacienti] Error.
Can someone tell me why? I also tried "pacienti is not mapped [from pacienti]" but same result
Thank you!
I would recommend you to use the jpa tools/plugins available with the IDEs which will auto generate these jpa entities for you using the database tables rather than manually creating these.
And they will take care of setting the relationship b/w different entities(db tables) in the auto generation process itself.
If you are Eclipse you can achieve this.
The problem is bcz there is no query with the name "from pacienti" in place of that pass the query name "Pacienti.findAll" in your createQuery method.
Plz let ne know once you try this, if you face any problem

Persisting OneToMany relationship Using JPA without Join table

I have the following tableS:
`notification_job_execution`
(`jobId`,
`createdDate`,
`messageBody`)
`notification_task_execution`
(`taskId`,
`jobId`,
`status`,
`createdDate`)
Havin oneToMany relationshop (notification_job_execution ,notification_task_execution)
(1..n)
I have the following entities
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private String jobId;
#Temporal(TemporalType.DATE)
private Date createdDate;
private String messageBody;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "notificationJobEntity", cascade=CascadeType.ALL)
private Set<NotificationTaskEntity> notificationTaskEntities = new HashSet<NotificationTaskEntity>(
0);
and:
#Entity
#Table(name = "notification_task_execution")
public class NotificationTaskEntity implements Serializable{
#Id
#GeneratedValue(strategy= GenerationType.AUTO)
private long taskId;
private int jobId;
private String status;
#Temporal(TemporalType.DATE)
private Date createdDate;
#ManyToOne(optional = false)
private NotificationJobEntity notificationJobEntity;
I am using Spring and JPA in order to persist this way:
NotificationJobEntity notificationJobEntity=new NotificationJobEntity();
notificationJobEntity.setCreatedDate(new Date());
notificationJobEntity.setMessageBody("hello youu");
NotificationTaskEntity notificationTaskEntity=new NotificationTaskEntity();
notificationTaskEntity.setCreatedDate(new Date());
notificationTaskEntity.setStatus("success");
notificationTaskEntity.setNotificationJobEntity(notificationJobEntity);
notificationTaskEntity.setNotificationJobEntity(notificationJobEntity);
notificationJobEntity.getNotificationTaskEntities().add(notificationTaskEntity);
notificationDao.save(notificationJobEntity);
I cant see in the database the child record persisted ( which is notificationTaskEntity).
How could I persist the parent and under the hood having the notificationTaskEntity to be persisted to the database as well?
I think you may just need to add the #JoinColumn annotation to indicate which field in the database table represents the ID of the NotificationTaskEntity.
#ManyToOne(optional = false)
#JoinColumn(name = "jobid")
private NotificationJobEntity notificationJobEntity;
You must specify the CascadeType in the NotificationTaskEntity
#ManyToOne(optional = false,CascadeType.PERSIST)
private NotificationJobEntity notificationJobEntity;

Objectify and email as #Id

I am not sure if I use the #Id in objectify the right way.
Right now I am using the eMail-Address as #Id field. The email field will be set on the server-side only (OAuthService.getCurrentUser.getEmail)
First question: Is this a good idea?
If I create for example an Item-class which has RegistrationTO as it's parent does it make sense to use the email-address as the #Id field in my Item-class or should Item-class have it's own, auto-generated, id and Key parent to specify the relation?
Objectify-Tutorial recommends to avoid #Parent - so, here I think it's not necessary either.
I am right?
Here my RegistrationTO:
public class RegistrationTO implements Serializable {
private static final long serialVersionUID = 1L;
#NotNull
#Size(min = 5, max = 20)
private String firstname;
#NotNull
#Size(min = 5, max = 20)
private String name;
#NotNull
#Size(min = 5, max = 20)
private String country;
#Id
#NotNull
#Size(min = 5, max = 20)
#Pattern(regexp = "\b[A-Z0-9._%-]+#[A-Z0-9.-]+\\.[A-Z]{2,4}\b")
private String email;
public RegistrationTO() {
}
public RegistrationTO(final String firstname, final String name, final String company) {
this.firstname = firstname;
this.name = name;
this.country = country;
email = "will be set on server (Oauth)";
}
public String getFirstname() {
return firstname;
}
public String getName() {
return name;
}
public String getCountry() {
return country;
}
public String getEmail() {
return email;
}
public void setEmail(final String email) {
this.email = email;
}
}
Sample for Item class:
public class Item implements Serializable {
private static final long serialVersionUID = 1L;
#Id
Long id
//or
//#Id
//String email
Key<RegistrationTO> parent;
String itemno;
}
Thank you in advance!
Regarding your question if the use of e-mail as #Id is correct or not, since the email will uniquely identify each object of the class, then you are fine!
Now, regarding the #Id of your Item class, if the email uniquely identifies each object, then there is no need to create a new auto-generated Long as #Id. In general, the criterion for the selection of the #Id is to uniquely identify all the objects of the class.
For the relationship between RegistrationTO and Item classes, use the #Parent annotation only if you need these entities to be the same entity group. The code for this:
#Parent
Key<RegistrationTO> parent;
Otherwise, use a "plain" relationship (as you have it in your example) that allows RegistrationTO and Item entities to be stored in different entity groups in the GAE datastore. For more information about entity groups, take a look at:
http://code.google.com/appengine/docs/java/datastore/entities.html#Entity_Groups_and_Ancestor_Paths
Hope that helps!

Resources