Ignore Column If Not Present From Spring Entity Manager Stored Procedure ResultList - sql

I'm working with a few different databases that all have the same stored procedure, but some have been updated while others haven't.
Suppose I have this entity:
#NamedStoredProcedureQueries(
NamedStoredProcedureQuery(
name = "getData",
procedureName = "dbo.selClientByStatus",
resultClasses = [MonitorData::class],
parameters = [
StoredProcedureParameter(name = "lowerRange", type = Int::class, mode=ParameterMode.IN),
StoredProcedureParameter(name = "upperRange", type = Int::class, mode=ParameterMode.IN),
StoredProcedureParameter(name = "connectionStatus", type = Int::class, mode=ParameterMode.IN),
StoredProcedureParameter(name = "serverID", type = String::class, mode=ParameterMode.IN),
]
)
)
#Entity
data class MonitorData(
#Id
#Column(name = "serverId")
val serverId: Int? = null,
#Column(name = "displayName")
val displayName: String? = null,
#Column(name = "providerId")
val providerId: Int? = null
)
When I call the stored procedure with:
em?.createNamedStoredProcedureQuery("getData")
?.setParameter("lowerRange", null)
?.setParameter("upperRange", null)
?.setParameter("connectionStatus", null)
?.resultList
Some databases have providerId as a select in the stored procedure, but some don't. It's not really a necessary field, but it can help with sorting, etc. When a stored procedure doesn't select providerId I understandably get a(n) SQLServerException saying The column providerId is not valid.
Is it possible to ignore that field if it doesn't exist in the resultList?

Related

SQLIntegrityConstraintViolationException -> Column "name" can not be null INTRESTING

So, i create Entity in my DB from CommandLineRunner, everything okay.
Then i create some controller one of them give me next Exception, when i going to update my Entity ->
***java.sql.SQLIntegrityConstraintViolationException: Column 'name' cannot be null***
Controller
#PostMapping ("/update")
public String update (Instructor instructor) {
instructorService.updateInstructor(instructor);
return "redirect:/instructors/index";
}
Entity
#Entity
#Table (name = "Instructor")
public class Instructor {
#Id
#GeneratedValue (strategy = GenerationType.IDENTITY)
#Column (name = "instructor_id", nullable = false)
private Long instructorId;
#Basic
#Column (name = "name", nullable = false, length = 45)
private String firstName;
#Basic
#Column (name = "lastName", nullable = false, length = 45)
private String lastName;
#Basic
#Column (name = "summary", nullable = false, length = 45)
private String instructorSummary;
#OneToMany (mappedBy = "instructor", fetch = FetchType.LAZY)
private Set <Course> courses = new HashSet<>();
#OneToOne (cascade = CascadeType.REMOVE)
#JoinColumn (name = "user_id", referencedColumnName = "user_id", nullable = false)
private User user;
When i delete (nullable=false) everything work by Entity does not appear in DB
Instructor Service
Instructor updateInstructor (Instructor instructor);
InstructorImpl
#Override
public Instructor updateInstructor(Instructor instructor) {
return instructorDao.save(instructor);
}
DaoClass only extend JpaRepository
Update: here are the logs
Hibernate: update instructor set name=?, summary=?, last_name=?,
user_id=? where instructor_id=? 2023-01-13T14:41:40.545+02:00 WARN
4176 --- [nio-8071-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper :
SQL Error: 1048, SQLState: 23000 2023-01-13T14:41:40.545+02:00 ERROR
4176 --- [nio-8071-exec-2] o.h.engine.jdbc.spi.SqlExceptionHelper :
Column 'name' cannot be null 2023-01-13T14:41:40.551+02:00 ERROR 4176
--- [nio-8071-exec-2] o.a.c.c.C.[.[.[/].[dispatcherServlet] : Servlet.service() for servlet [dispatcherServlet] in context with path
[] threw exception [Request processing failed:
org.springframework.dao.DataIntegrityViolationException: could not
execute statement; SQL [n/a]; constraint [null]] with root cause

sum of arraylist elements getted by cursor

I've a table of Holidays, I'm trying to check if some specific one took any holidays before
This is my table construction:
db.execSQL("CREATE TABLE IF NOT EXISTS Holidays (HolidayID INTEGER PRIMARY KEY, Department TEXT NOT NULL, Profession TEXT NOT NULL, EmpName TEXT NOT NULL, DaysofHoliday TEXT NOT NULL, StartDay TEXT NOT NULL, StartMonth TEXT NOT NULL, StartYear TEXT NOT NULL, EndDay TEXT, EndMonth TEXT, EndYear TEXT, PresentedDay TEXT NOT NULL, PresentedMonth TEXT NOT NULL, PresentedYear TEXT NOT NULL, Engineer TEXT NOT NULL, ApproveDay TEXT NOT NULL, ApproveMonth TEXT NOT NULL, ApproveYear TEXT NOT NULL)")
My companion object:
companion object {
val DB_Name = "samalout.db"
val TABLE_HOL = "Holidays"
val COL_41 = "HolidayID"
val COL_42 = "Department"
val COL_43 = "Profession"
val COL_44 = "EmpName"
val COL_45 = "DaysofHoliday"
val COL_46 = "StartDay"
val COL_47 = "StartMonth"
val COL_48 = "StartYear"
val COL_49 = "EndDay"
val COL_410 = "EndMonth"
val COL_411 = "EndYear"
val COL_412 = "PresentedDay"
val COL_413 = "PresentedMonth"
val COL_414 = "PresentedYear"
val COL_415 = "Engineer"
val COL_416 = "ApproveDay"
val COL_417 = "ApproveMonth"
val COL_418 = "ApproveYear"
}
This my search function:
fun Game() {
var query1 = ""
var rv = ArrayList<String>()
val db = dbHelper.writableDatabase
query1 = "SELECT * FROM " + DBHelper.TABLE_HOL + " WHERE " + DBHelper.COL_44 + "='" + spin3.selectedItem.toString() + "'"
val c1 = db.rawQuery(query1, null)
while (c1.moveToNext()) {
rv.add(c1.getString(0))
textView13.text = rv.sum().toString()
}
}
Edit:
sum function can't b done to arraylist of strings, so I tried something else:
while (c1.moveToNext()) {
rv.add(c1.getString(0))
for (item in rv)
println(item)
}
but also it didn't get me result
I found the problem, It's the Column that I search .. I performed a select query on adb, it returned different columns .. for clarity: I assigned the following columns (HolidayID, Department, Profession, EmpName), when I made a select * from table Holidays; on adb it returned the following (HolidayID, EmpName, Department, Profession) .. I don't know what happened to reverse my initials but I changed search query in main activity to the second column of table and it worked for me.
Edit: It was the insertion statement, it's all my fault
fun insertDataHol(holid: Int, department: String, profession: String, empname: String, daysofholiday: String, startday: String, startmonth: String, startyear: String, endday: String, endmonth: String, endyear: String, presentedday: String, presentedmonth: String, presentedyear: String, engineer: String, approveday: String, approvemonth: String, approveyear: String) {
val db = this.writableDatabase
val contentValues = ContentValues()
contentValues.put(COL_41, holid)
contentValues.put(COL_42, empname)
contentValues.put(COL_43, department)
contentValues.put(COL_44, profession)
contentValues.put(COL_45, daysofholiday)
contentValues.put(COL_46, startday)
contentValues.put(COL_47, startmonth)
contentValues.put(COL_48, startyear)
contentValues.put(COL_49, endday)
contentValues.put(COL_410, endmonth)
contentValues.put(COL_411, endyear)
contentValues.put(COL_412, presentedday)
contentValues.put(COL_413, presentedmonth)
contentValues.put(COL_414, presentedyear)
contentValues.put(COL_415, engineer)
contentValues.put(COL_416, approveday)
contentValues.put(COL_417, approvemonth)
contentValues.put(COL_418, approveyear)
db.insert(TABLE_HOL, null, contentValues)
}
In the insert statement I defined to insert name as the second column, so it's my fault I tried to retrieve name from the forth column while it's inserted in second column.

EclipseLink- JPQL join tables through query

I have problem with my JPQl. this is a one to many relationship with TrainRoute and TrainRouteStation. I'm trying to create a inner join and fetch the data. native SQL query working when I used mysql workbeanch and I'm trying convert it to JPQL. also, I was trying to fix from 2 days.
Error : Object comparisons can only be used with OneToOneMappings. Other mapping comparisons must be done through query keys or direct attribute level comparisons.
Class: TrainRoute
#Basic(optional = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "train_route_id", unique = true, nullable = false)
public Long getTrainRouteId() {
return this.trainRouteId;
}
public void setTrainRouteId(Long trainRouteId) {
this.trainRouteId = trainRouteId;
}
#OneToMany(cascade = CascadeType.ALL,fetch = FetchType.EAGER, mappedBy = "trainRoute")
public List<TrainRouteStationData> getTrainRouteStations() {
return this.trainRouteStations;
}
public void setTrainRouteStations(List<TrainRouteStationData> trainRouteStations) {
this.trainRouteStations = trainRouteStations;
}
Class: TrainRouteStation
#Basic(optional = false)
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Id
#Column(name = "train_route_station_id", unique = true, nullable = false)
public Long getTrainRouteStationId() {
return this.trainRouteStationId;
}
public void setTrainRouteStationId(Long trainRouteStationId) {
this.trainRouteStationId = trainRouteStationId;
}
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "train_route_id", nullable = false)
public TrainRouteData getTrainRoute() {
return this.trainRoute;
}
JPQL :"SELECT s FROM TrainRouteData t inner join TrainRouteStationData s ON t.trainRouteId=s.trainRoute where s.stationSeqN >=1 AND s.stationSeqN <=3 AND t.trainRouteDescX='Test1-Test2' order by s.stationSeqN asc"
Native SQL : SELECT train_route_station.* FROM train_route inner join train_route_station ON train_route.train_route_id=train_route_station.train_route_id where train_route_station.station_seq_n >= 1 AND train_route_station.station_seq_n <= 3 AND train_route.train_route_desc_x='Test1-Test2' order by train_route_station.station_seq_n asc
And it throw an error:
Exception Description: Object comparisons can only be used with OneToOneMappings. Other mapping comparisons must be done through query keys or direct attribute level comparisons.
Mapping: [org.eclipse.persistence.mappings.DirectToFieldMapping[trainRouteId-->train_route.train_route_id]]
Expression: [
Query Key trainRouteId
How can I change that query?
That's not how joins work in JPQL.
The correct query is
select s from TrainRouteData t inner join t.trainRouteStations s
where s.stationSeqN >= 1
and s.stationSeqN <= 3
and t.trainRouteDescX = 'Test1-Test2'
order by s.stationSeqN asc

Remove item of record without knowing all item

I have this simulation:
init : (Model, Cmd Msg)
init = ({ dog = List Dog }, Cmd.none)
type alias Dog =
{ name : String
, age : Int
, price : Float
, extra = List Extra
}
type alias Extra =
{ allergies : List String
, wishes : List String
}
[{ name = "Hot"
, age = 1
, price = 300.5
, extra = [{...}]
},
{ name = "Dog"
, age = 3
, price = 150.0
, extra = [{...}]
}]
And I want to remove only 'extras' of Dog, in determined part of the code:
[{ name = "Hot"
, age = 1
, price = 300.5
},
{ name = "Dog"
, age = 3
, price = 150.0
}]
I can do this by mapping the entire list and generating a new one by removing 'extra' occurrence:
removeExtraOfDogs dogList =
(dogList |> List.map (\dog ->
{ name = dog.name
, age = dog.age
, price = dog.price
}
))
but I want to make it dynamic to just pass the extra to remove, without having to know what variables there are in the type and recreate it
Elm used to have this feature but it was removed a while ago. But, based on your use case described in a comment, I don't think you need this feature. You can instead use extensible record feature of Elm to allow passing different records into a function as long as they contain a fixed set of fields.
For example, let's say you have two types with name and age fields and having an extra incompatible field:
type alias Foo = { name : String, age : Int, extra : List String }
type alias Bar = { name : String, age : Int, extra : Int }
You can define a function that takes a record with a name field of type String and age of type Int and any extra fields:
encode : { r | name : String, age : Int } -> String
encode record = record.name ++ "," ++ toString record.age
You'll can now pass both Foo and Bar to this function because they both satisfy the requirements of the type signature.

unable to update objects of one to one relation in hibernate

I have relation as shown bellow:
#Entity
#Table(name = "ORDER_", catalog = "smartorder")
public class Order implements Serializable {
/**
* serial version id
*/
private static final long serialVersionUID = 13875615L;
#Id
#Column(name = "ORDER_ID", unique = true, nullable = false)
#SequenceGenerator(name = "ORDER_ID_GEN", sequenceName = "ORDER_ID_SEQ")
#GeneratedValue(generator = "ORDER_ID_GEN")
private long orderId;
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "INVOICE_ID", referencedColumnName = "INVOICE_ID")
private Invoice invoice;
// setters and getters
}
#Entity
#Table(name = "INVOICE_")
public class Invoice implements Serializable {
/**
* serial version id
*/
private static final long serialVersionUID = 13875612L;
#Id
#Column(name = "INVOICE_ID", unique = true, nullable = false)
#SequenceGenerator(name = "INVOICE_ID_GEN", sequenceName = "INVOICE_ID_SEQ")
#GeneratedValue(generator = "INVOICE_ID_GEN")
private int invoiceId;
#OneToOne(cascade = CascadeType.ALL, fetch = FetchType.LAZY)
#JoinColumn(name = "ORDER_ID", referencedColumnName = "ORDER_ID")
private Order order;
#Column(name = "SUB_TOTAL", precision = 6, nullable = false)
private double subTotal;
#Column(name = "SERVICE_TAX", precision = 6, nullable = false)
private double serviceTax;
#Column(name = "VAT", precision = 6, nullable = false)
private double vat;
#Column(name = "SURCHAARGE", precision = 6, nullable = false)
private double surChaarge;
#Column(name = "GRAND_TOTAL", precision = 6, nullable = false)
private double grandTotal;
//setters and getters
}
I am able to save the records properly. But when i am trying to update orders objects by setting invoice object to order object then the order object is nor persisting only invoice object is persisting.
Order o = getSession().load(Order.class,1L);
o.setInvoice(new Invoice(.........));
getSession().update(o);
in console I am able to see one SQL statement only,
insert into INVOICE_ (DISCOUNT, GRAND_TOTAL, ORDER_ID, ROUNDING, SERVICE_TAX, SUB_TOTAL, SURCHAARGE, VAT) values (?, ?, ?, ?, ?, ?, ?, ?)
Invoice Id is not getting update in Order table :(
Can anyone suggest whats the issue is.
Thanks in advance.....
This may depend on your unusual design.
With INVOICE_ID in ORDR_ and ORDER_ID in INVOICE_ you have both tables at the same time as parent and child of each other.
If your database uses foreign keys deleting and inserting will be hard.
You should use one type/table as parent, (e. g. Order, because it's normaly first) and the other as child (order_id will be in invoice_ table).
In your object model you can have both directions (see first example of http://docs.oracle.com/javaee/6/api/javax/persistence/OneToOne.html)
The issue is incorrect scenario in which you used your Entities/Tables and the one-to-one mapping style. The concept of One-To-One does not corresponed with your current design of both tables and entities.
Please, try to read more about one-to-one here: The concept for one-to-one mapping. Explain the mapping
And mostly take a deep look here: Hibernate – One-to-One example (Annotation), where you can find examples of the one-to-one mapping.
If you really would like to continue with one-to-one mapping you have to:
Remove the "INVOICE_ID" column from the "INVOICE_" table (surprising but a fact)
make the "ORDER_ID" column in the "INVOICE_" table as a primary key (another fact)
change the mapping of the Invoice entity to be more submissive (driven by Order entity)
Example of changes of the Invoice mapping:
// just a draft, to give you idea about the
// "submissive" side mapping.
// All the ID stuff of the Invoice is driven by its
// "Master" - Order
#GenericGenerator(name = "generator", strategy = "foreign",
parameters = #Parameter(name = "property", value = "order"))
#Id
#GeneratedValue(generator = "generator")
#Column(name = "ORDER_ID", unique = true, nullable = false)
public Integer getOrderId() {
return this.orderId;
}
public void setOrderId(Integer orderId) {
this.orderId = orderId;
}
#OneToOne(fetch = FetchType.LAZY)
#PrimaryKeyJoinColumn
public Order getOrder() {
return this.order;
}
Please, take it as a draft, to show how different the one-to-one concept is.