I have a table in my database, which contains sportsresults, and I need to select the last result for a competitor on a specific eventstage from a table.
I have this table:
+----------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+---------------+------+-----+---------+-------+
| EventStageID | int(11) | NO | PRI | NULL | |
| CompetitorID | int(11) | NO | PRI | NULL | |
| Lap | int(11) | NO | PRI | NULL | |
| Time | varchar(255) | YES | | NULL | |
| Status | varchar(255) | YES | | NULL | |
| PitstopCount | int(11) | YES | | NULL | |
| Grid | int(11) | YES | | NULL | |
| FastestLapTime | varchar(255) | YES | | NULL | |
| Substatus | varchar(255) | YES | | NULL | |
| Points | decimal(10,2) | YES | | NULL | |
| Position | int(11) | YES | | NULL | |
| StageType | int(11) | YES | | NULL | |
+----------------+---------------+------+-----+---------+-------+
I can select from the table with normal SQL query like this:
SELECT * FROM
(SELECT EventStageID as esi, CompetitorID as cid, Max(Lap) as MaxLap FROM srt_outright_season_event_stage_result_live WHERE EventStageID = 191666 GROUP BY CompetitorID) as y
LEFT JOIN
(SELECT * FROM srt_outright_season_event_stage_result_live) as x
ON x.CompetitorID = y.cid AND x.Lap = y.MaxLap AND x.EventStageID = y.esi;
Which gives the following result:
+--------+--------+--------+--------------+--------------+------+----------+--------+--------------+------+----------------+-----------+--------+----------+-----------+
| esi | cid | MaxLap | EventStageID | CompetitorID | Lap | Time | Status | PitstopCount | Grid | FastestLapTime | Substatus | Points | Position | StageType |
+--------+--------+--------+--------------+--------------+------+----------+--------+--------------+------+----------------+-----------+--------+----------+-----------+
| 191666 | 4521 | 0 | 191666 | 4521 | 0 | Finished | NULL | NULL | NULL | 2:00.175 | NULL | NULL | 4 | 5 |
| 191666 | 4524 | 0 | 191666 | 4524 | 0 | Finished | NULL | NULL | NULL | 2:04.053 | NULL | NULL | 10 | 5 |
| 191666 | 4533 | 0 | 191666 | 4533 | 0 | Finished | NULL | NULL | NULL | NULL | NULL | NULL | 13 | 5 |
| 191666 | 4538 | 0 | 191666 | 4538 | 0 | Finished | NULL | NULL | NULL | 2:01.218 | NULL | NULL | 6 | 5 |
| 191666 | 5769 | 0 | 191666 | 5769 | 0 | Finished | NULL | NULL | NULL | 2:00.050 | NULL | NULL | 3 | 5 |
| 191666 | 7135 | 0 | 191666 | 7135 | 0 | Finished | NULL | NULL | NULL | 1:59.431 | NULL | NULL | 1 | 5 |
| 191666 | 7138 | 0 | 191666 | 7138 | 0 | Finished | NULL | NULL | NULL | NULL | NULL | NULL | 18 | 5 |
| 191666 | 7610 | 0 | 191666 | 7610 | 0 | Finished | NULL | NULL | NULL | 1:59.486 | NULL | NULL | 2 | 5 |
+--------+--------+--------+--------------+--------------+------+----------+--------+--------------+------+----------------+-----------+--------+----------+-----------+
I have this Entity class:
#Entity(name = "event_stage_result_live")
public class EventStageResultLive {
#EmbeddedId
private PKEventStageResultLive pkEventStageResultLive;
// Composite PK contains EventStageID, CompetitorID and Lap
#Column(name = "Time")
private String time;
#Column(name = "Status")
private String status;
#Column(name = "PitstopCount")
private Integer pitstopCount;
#Column(name = "Grid")
private Integer grid;
#Column(name = "Position")
private Integer position;
#Column(name = "FastestLapTime")
private String fastestLapTime;
#Column(name = "Substatus")
private String substatus;
#Column(name = "Points")
private Float points;
#Column(name = "StageType")
private StageType stageType;
// getters and setters...
}
I think in SQL you can do something like this. I dont think join is required.
select * from srt_outright_season_event_stage_result_live c
where c.CompetitorID = :competitorID and c.EventStageID = 191666
and c.Lap = (select max(d.lap) from srt_outright_season_event_stage_result_live d
where d.CompetitorID = :competitorID and d.EventStageID = 191666 )
Passed to JPQL is
select e from EventStageResultLive e
where e.pkEventStageResultLive.CompetitorID = :competitorID and c.pkEventStageResultLive.EventStageID = 191666
and e.pkEventStageResultLive.Lap = (select max(d.pkEventStageResultLive.lap) from EventStageResultLive d
where d.pkEventStageResultLive.CompetitorID = :competitorID and d.pkEventStageResultLive.EventStageID = 191666 )
Assuming
public class PKEventStageResultLive{
private int CompetitorID ;
private int EventStageID ;
private int Lap;
}
If the name of the properties are different correct the name in the JPQL
And competitorID as a named parameter.
Related
When I trying to use Mockito verify to test extral call times of testMethod(indeed this method is just execute 2 times), but I got following message.
verify(XXXXXXX, times(2)).testMethod(any(XXXXXX.class))
| | | | | |
| | | null null class XXXXXX
| | Wanted invocations count: 2
| Mock for XXXXXXX, hashCode: 292294397
Mock for XXXXXXX, hashCode: 292294397
If I change the times to 1, and the error message is:
verify(XXXXXXX, times(1)).testMethod(any(XXXXXX.class))
| | | | | |
| | | | null class XXX
| | | org.mockito.exceptions.verification.TooManyActualInvocations:
| | | XXX.XXXX(
| | | <any XXX>
| | | );
| | | Wanted 1 time:
| | | -> at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
| | | But was 2 times:
| | | -> at XXXX.XXX(XXX.java:129)
| | | -> at XXXXX.XXX(XXX.java:129)
| | |
| | |
| | Wanted invocations count: 1
Does anybody have met this problem before?
Single-job schedule with two vehicles. One vehicle starts close to the job, the other starts far from the job. Seems it should prefer to use the closer vehicle, as there's a cost-per-distance. But it uses the farther one, if there's a non-zero setCostPerWaitingTime(). Why?
public void testUseCloserVehicleWhenCostsAreSet() throws Exception {
VehicleType type = VehicleTypeImpl.Builder.newInstance("generic")
.setCostPerDistance(0.017753)
//.setCostPerTransportTime(1.0)
.setCostPerWaitingTime(1.0)
.build();
double serviceTime = 420.0;
Location pointA = Location.newInstance(100.0, 100.0);
Location pointB = Location.newInstance(100.0, 200.0);
Location closeToPointA = Location.newInstance(110.0, 110.0);
Location farFromPointA = Location.newInstance(500.0, 110.0);
VehicleRoutingProblem vrp = VehicleRoutingProblem.Builder
.newInstance()
.setFleetSize(VehicleRoutingProblem.FleetSize.FINITE)
.addVehicle(VehicleImpl.Builder.newInstance("CloseBy")
.setType(type)
.setStartLocation(closeToPointA)
.build())
.addVehicle(VehicleImpl.Builder.newInstance("FarAway")
.setType(type)
.setStartLocation(farFromPointA)
.build())
.addJob(Shipment.Builder.newInstance("123")
.setPickupLocation(pointA)
.setPickupServiceTime(serviceTime)
.setDeliveryLocation(pointB)
.setDeliveryServiceTime(serviceTime)
.setPickupTimeWindow(new TimeWindow(36000.0, 36360.0))
.setDeliveryTimeWindow(new TimeWindow(36360.0, 36720.0))
.setMaxTimeInVehicle(720.0)
.build())
.build();
VehicleRoutingAlgorithm algorithm = Jsprit.Builder.newInstance(vrp)
.buildAlgorithm();
VehicleRoutingProblemSolution bestSolution = Solutions.bestOf(algorithm.searchSolutions());
SolutionPrinterWithTimes.print(vrp, bestSolution, SolutionPrinterWithTimes.Print.VERBOSE);
System.out.flush();
assertEquals("CloseBy", bestSolution.getRoutes().iterator().next().getVehicle().getId());
}
Result:
+----------------------------------------------------------+
| solution |
+---------------+------------------------------------------+
| indicator | value |
+---------------+------------------------------------------+
| costs | 35616.03246830352 |
| noVehicles | 1 |
| unassgndJobs | 0 |
+----------------------------------------------------------+
+--------------------------------------------------------------------------------------------------------------------------------+
| detailed solution |
+---------+----------------------+-----------------------+-----------------+-----------------+-----------------+-----------------+
| route | vehicle | activity | job | arrTime | endTime | costs |
+---------+----------------------+-----------------------+-----------------+-----------------+-----------------+-----------------+
| 1 | FarAway | start | - | undef | 0 | 0 |
| 1 | FarAway | pickupShipment | 123 | 400 | 36420 | 35607 |
| 1 | FarAway | deliverShipment | 123 | 36520 | 36940 | 35609 |
| 1 | FarAway | end | - | 37350 | undef | 35616 |
+--------------------------------------------------------------------------------------------------------------------------------+
junit.framework.ComparisonFailure:
Expected :CloseBy
Actual :FarAway
I suspect it has something to do with the vehicle arriving at 400 for a job that can't start until 36000. Is there a way to prevent that, so the vehicle starts only as early as needed to reach the first job? Does setCostPerWaitingTime do something other than what I think?
Here's a comparison of the job with only the CloseBy vehicle.
+--------------------------------------------------------------------------------------------------------------------------------+
| detailed solution |
+---------+----------------------+-----------------------+-----------------+-----------------+-----------------+-----------------+
| route | vehicle | activity | job | arrTime | endTime | costs |
+---------+----------------------+-----------------------+-----------------+-----------------+-----------------+-----------------+
| 1 | FarAway | start | - | undef | 0 | 0 |
| 1 | FarAway | pickupShipment | 123 | 400 | 36420 | 35607 |
| 1 | FarAway | deliverShipment | 123 | 36520 | 36940 | 35609 |
| 1 | FarAway | end | - | 37350 | undef | 35616 |
+--------------------------------------------------------------------------------------------------------------------------------+
+--------------------------------------------------------------------------------------------------------------------------------+
| detailed solution |
+---------+----------------------+-----------------------+-----------------+-----------------+-----------------+-----------------+
| route | vehicle | activity | job | arrTime | endTime | costs |
+---------+----------------------+-----------------------+-----------------+-----------------+-----------------+-----------------+
| 1 | CloseBy | start | - | undef | 0 | 0 |
| 1 | CloseBy | pickupShipment | 123 | 14 | 36420 | 35986 |
| 1 | CloseBy | deliverShipment | 123 | 36520 | 36940 | 35988 |
| 1 | CloseBy | end | - | 37031 | undef | 35989 |
+--------------------------------------------------------------------------------------------------------------------------------+
I think the problem is that the CloseBy vehicle arrives sooner, so it pays higher wait costs, while the other vehicle is driving during that time so pays less in wait costs. This would be mitigated if the vehicle didn't start until it needed to, but I'm unsure how to set that up.
I have two tables User and Roles with one-to-one relation as below.
User
_________________________________________
| Id | user_name | full_name | creator |
_________________________________________
| 1 | a | A | a |
| 2 | b | B | a |
| 3 | c | C | a |
| 4 | d | D | c |
| 5 | e | E | c |
| 6 | f | F | e |
| 7 | g | G | e |
| 8 | h | H | e |
| 9 | i | I | e |
|10 | j | J | i |
_________________________________________
Roles
_______________________________________
| id | user_mgmt | others | user_id |
_______________________________________
| 1 | 1 | 1 | 1 |
| 2 | 0 | 1 | 2 |
| 3 | 1 | 0 | 3 |
| 4 | 0 | 1 | 4 |
| 5 | 1 | 1 | 5 |
| 6 | 0 | 1 | 6 |
| 7 | 0 | 0 | 7 |
| 8 | 0 | 0 | 8 |
| 9 | 1 | 0 | 9 |
________________________________________
The Roles table have boolean columns, so if an User have user_mgmt role he can add many users (How many users can be added by an user is not definite). I want to fetch all users created by an user and his child users ( a is parent, c is child of a and e is child of c ..) .
Here is my code to fetch users
public void loadUsers(){
List<Users> users = new ArrayList<>();
String creator = user.getUserName();
List<Users> createdUsers = userService.getUsersByCreator(creator);
for(Users user : createdUsers) {
Roles role = createdUsers.getRoles();
if(role.isEmpMgnt()){
users.add(user);
loadUsers();
}
}
}
This gives me an stack overflow error. If i don't call loadUsers() recursively it returns only a single child result. So is there any solutions to this ? Thanks for any help in advance.
This gives you stack overflow error because a has creator a. So you have infinite loop for user a. For a you should set creator to null or skip self references in code.
Also you should pass current user into loadUsers() method and read only users that are created by it. Like
public void loadUsers(String creator)
and only process users created by that creator. Here
String creator = user.getUserName();
what is user? You should use creator. Question is how do you obtain initial creator. Probably initial creator should be user where creator is null.
I have a before insert trigger in MySQL that works when row is inserted directly (through DB client) into database but DOES NOT work through Hibernate ORM.
Some basic info
MySQL 5.6.26 on Debian Jessie 8.6
MySQL Connector Java 5.1.40
Hibernate ORM 5.2.4
the Product table
+----------------+---------------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+----------------+---------------------+------+-----+---------+----------------+
| id | int(10) unsigned | NO | PRI | NULL | auto_increment |
| prd_no | varchar(6) | YES | UNI | NULL | |
| prd_ty | varchar(20) | NO | | NULL | |
| prd_name | varchar(50) | NO | | NULL | |
| prd_name_short | varchar(10) | NO | | NULL | |
| prd_cat | varchar(20) | NO | | NULL | |
| prd_tax_ty | varchar(20) | NO | | NULL | |
| prd_price_ty | varchar(20) | NO | | NULL | |
| prd_norm_avail | tinyint(3) unsigned | NO | | 1 | |
| ppp_id | int(10) unsigned | YES | MUL | NULL | |
+----------------+---------------------+------+-----+---------+----------------+
My trigger
DELIMITER $$
CREATE TRIGGER tg_product_insPrdNo BEFORE INSERT ON product
FOR EACH ROW
BEGIN
IF NEW.prd_ty = 'ns' THEN
SET NEW.prd_no = fn_getPrdNoNextAI();
END IF;
END $$
DELIMITER ;
Function that gets called by the trigger
DELIMITER //
CREATE FUNCTION fn_getPrdNoNextAI()
RETURNS INTEGER SIGNED
BEGIN
DECLARE last_prd_no INTEGER SIGNED;
SELECT (MAX(CAST(product.prd_no AS SIGNED))) INTO last_prd_no FROM product;
IF last_prd_no IS NULL THEN
SET last_prd_no = 0;
END IF;
RETURN last_prd_no+1;
END //
DELIMITER ;
Java code (abbreviated) for inserting row
Session session = AES_Server.getSessionFactory().openSession();
Transaction tx = null;
int prdID = -1;
try {
tx = session.beginTransaction();
prdID = (int) session.save(prd);
tx.commit();
} catch (HibernateException he) {
if (tx != null)
tx.rollback();
} finally {
session.close();
}
return prdID;
Basically, my DB trigger will only auto-insert value for prd_no field if prd_ty is of value 'ns'. This works fine when inserting directly into the DB but when using hibernate to insert, no value is inserted.
Any pointers would be much appreciated. Cheers.
I am tring the 'not equal' query in hql.
#Override
public Student findStudentsByYear(String year) {
String queryString = "from Student where year<>:year ";
Query query = sessionFactory.getCurrentSession().createQuery(queryString);
query.setParameter("year", year);
return (Student)query.uniqueResult();
}
but it is not working properly.How to write this query correctly
My student table is
+-------------+--------------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+-------------+--------------+------+-----+---------+----------------+
| studentId | bigint(20) | NO | PRI | NULL | auto_increment |
| course | varchar(255) | YES | | NULL | |
| dob | varchar(255) | YES | | NULL | |
| email | varchar(255) | YES | | NULL | |
| faculty | varchar(255) | YES | | NULL | |
| firstName | varchar(255) | YES | | NULL | |
| gender | int(11) | YES | | NULL | |
| homeAddress | varchar(255) | YES | | NULL | |
| lastName | varchar(255) | YES | | NULL | |
| linkedIn | varchar(255) | YES | | NULL | |
| university | varchar(255) | YES | | NULL | |
| year | varchar(255) | YES | | NULL | |
| user_userId | bigint(20) | YES | MUL | NULL | |
+-------------+--------------+------+-----+---------+----------------+
I know it's late but if anyone is having similar problem, you can use this:
Criteria criteria = session.createCriteria(Student.class);
criteria.add(Restrictions.ne("year", year));
List<Student> result = criteria.list();
Or this:
List<Student> result = session.createQuery ("from Student where year!=:year").setParameter("year", year).list();
I'm not sure what the problem is in above example as Samantha did not provide any information what so ever but my guess is that the uniqueResult() is causing trouble because this query returns a list and not one result.