我的数据库中有一些数据,并且有一个id列,只要存储数据就会自动递增。
出于某种目的,我想要检索添加的最后一行或具有最大id的行(也是最后一行)。我正在编写以下查询:
List<Student> student = sessionFactory.getCurrentSession().createQuery("SELECT * FROM Student ORDER BY id DESC")
我不知道这是否是正确的方法,但在执行时我收到的错误就像是意外的令牌:*。
提前寻找您宝贵的建议和感谢。
public void storeData(Student student)
{
List<Student> std = sessionFactory.getCurrentSession().createQuery("FROM Student ORDER BY id DESC limit 1").list(); //getting error while executing this statement(unexpected token limit)
System.out.println(std.get(0).getNumber()); //getting error while executing it
}
我通过storeData类中的student对象发送学生数据。我希望在存储数据后我可以访问存储的数据值,就像我想将数值存储在变量中以便进一步处理。但是在执行上述操作时我遇到了错误。
答案 0 :(得分:3)
为什么不是简单的“最高”ID?
svg {
background: #ddd;
font: 10px sans-serif;
cursor: crosshair;
}
.line {
cursor: crosshair;
fill: none;
stroke: #000;
stroke-width: 2px;
stroke-linejoin: round;
}
#output {
position: relative;
top: -2em;
left: 0.67em;
font: 12px/1.4 monospace;
}
使用会话工厂:
<html>
<body>
<div id="sketch"></div>
<div id="output"></div>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script>
(function () { "use strict";
// to suit your point format, run search/replace for '.x' and '.y';
// for 3D version, see 3d branch (configurability would draw significant performance overhead)
// square distance between 2 points
function getSqDist(p1, p2) {
var dx = p1.x - p2.x,
dy = p1.y - p2.y;
return dx * dx + dy * dy;
}
// square distance from a point to a segment
function getSqSegDist(p, p1, p2) {
var x = p1.x,
y = p1.y,
dx = p2.x - x,
dy = p2.y - y;
if (dx !== 0 || dy !== 0) {
var t = ((p.x - x) * dx + (p.y - y) * dy) / (dx * dx + dy * dy);
if (t > 1) {
x = p2.x;
y = p2.y;
} else if (t > 0) {
x += dx * t;
y += dy * t;
}
}
dx = p.x - x;
dy = p.y - y;
return dx * dx + dy * dy;
}
// rest of the code doesn't care about point format
// basic distance-based simplification
function simplifyRadialDist(points, sqTolerance) {
var prevPoint = points[0],
newPoints = [prevPoint],
point;
for (var i = 1, len = points.length; i < len; i++) {
point = points[i];
if (getSqDist(point, prevPoint) > sqTolerance) {
newPoints.push(point);
prevPoint = point;
}
}
if (prevPoint !== point) {
newPoints.push(point);
}
return newPoints;
}
// simplification using optimized Douglas-Peucker algorithm with recursion elimination
function simplifyDouglasPeucker(points, sqTolerance) {
var len = points.length,
MarkerArray = typeof Uint8Array !== 'undefined' ? Uint8Array : Array,
markers = new MarkerArray(len),
first = 0,
last = len - 1,
stack = [],
newPoints = [],
i, maxSqDist, sqDist, index;
markers[first] = markers[last] = 1;
while (last) {
maxSqDist = 0;
for (i = first + 1; i < last; i++) {
sqDist = getSqSegDist(points[i], points[first], points[last]);
if (sqDist > maxSqDist) {
index = i;
maxSqDist = sqDist;
}
}
if (maxSqDist > sqTolerance) {
markers[index] = 1;
stack.push(first, index, index, last);
}
last = stack.pop();
first = stack.pop();
}
for (i = 0; i < len; i++) {
if (markers[i]) {
newPoints.push(points[i]);
}
}
return newPoints;
}
// both algorithms combined for awesome performance
function simplify(points, tolerance, highestQuality) {
var sqTolerance = tolerance !== undefined ? tolerance * tolerance : 1;
//alert(sqTolerance);
points = highestQuality ? points : simplifyRadialDist(points, sqTolerance);
points = simplifyDouglasPeucker(points, sqTolerance);
return points;
}
// export as AMD module / Node module / browser variable
if (typeof define === 'function' && define.amd) {
define(function() {
return simplify;
});
} else if (typeof module !== 'undefined') {
module.exports = simplify;
} else {
window.simplify = simplify;
}
})();
</script>
<script>
var margin = {top: 0, right: 0, bottom: 0, left: 0},
width = 960 - margin.left - margin.right,
height = 500 - margin.top - margin.bottom;
var ptdata = [];
var session = [];
var path;
var drawing = false;
var output = d3.select('#output');
var line = d3.svg.line()
.interpolate("basis")
.tension(1)
.x(function(d, i) { return d.x; })
.y(function(d, i) { return d.y; });
var svg = d3.select("#sketch").append("svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
svg.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
svg
.on("mousedown", listen)
.on("touchstart", listen)
.on("touchend", ignore)
.on("touchleave", ignore)
.on("mouseup", ignore)
.on("mouseleave", ignore);
// ignore default touch behavior
var touchEvents = ['touchstart', 'touchmove', 'touchend'];
touchEvents.forEach(function (eventName) {
document.body.addEventListener(eventName, function(e){
e.preventDefault();
});
});
function listen () {
drawing = true;
output.text('event: ' + d3.event.type);
ptdata = []; // reset point data
path = svg.append("path") // start a new line
.data([ptdata])
.attr("class", "line")
.attr("d", line);
if (d3.event.type === 'mousedown') {
svg.on("mousemove", onmove);
} else {
svg.on("touchmove", onmove);
}
}
function ignore () {
var before, after;
output.text('event: ' + d3.event.type);
svg.on("mousemove", null);
svg.on("touchmove", null);
// skip out if we're not drawing
if (!drawing) return;
drawing = false;
before = ptdata.length;
console.group('Line Simplification');
console.log("Before simplification:", before)
console.log(ptdata);
ptdata = simplify(ptdata, 100, true);
console.log(ptdata);
//ptdata.smooth();
//ptdata.simplify1(10);
after = ptdata.length;
//console.log(ptdata);
console.log("After simplification:", ptdata.length)
console.groupEnd();
var percentage = parseInt(100 - (after/before)*100, 10);
output.html('Points: ' + before + ' => ' + after + '. <b>' + percentage + '% simplification.</b>');
// add newly created line to the drawing session
session.push(ptdata);
// redraw the line after simplification
tick();
}
function onmove (e) {
var type = d3.event.type;
var point;
if (type === 'mousemove') {
point = d3.mouse(this);
output.text('event: ' + type + ': ' + d3.mouse(this));
} else {
// only deal with a single touch input
point = d3.touches(this)[0];
output.text('event: ' + type + ': ' + d3.touches(this)[0]);
}
// push a new data point onto the back
ptdata.push({ x: point[0], y: point[1] });
//alert("x: "+point[0]+" y: "+point[1]);
tick();
}
function tick() {
path.attr("d", function(d) {
console.log("before d:", d.length)
d = simplify(d, 2, true);
console.log("after d:", d.length)
return line(d); }) // Redraw the path:
}
</script>
</body>
</html>
答案 1 :(得分:1)
设置最大结果选项 .setMaxResults(1)
有两种方式
1)使用 .setMaxResults(1).list()
将List作为输出所以你的陈述将成为,你需要迭代它
List <Student> student = sessionFactory.getCurrentSession().createQuery("FROM Student ORDER BY id DESC").setMaxResults(1).list();
2)因为你只需要最后的结果,你也可以去 .setMaxResults(1).uniqueResult()
uniqueResult() : Convenience method to return a single instance that matches the query, or null if the query returns no results.
所以你的陈述将成为
Student student = sessionFactory.getCurrentSession().createQuery("FROM Student ORDER BY id DESC").setMaxResults(1).uniqueResult();
使用任何方法都可以将id(max)保存在int变量
中[注意]:从查询中删除限制1
希望它能帮到你
答案 2 :(得分:0)
SELECT * FROM Student ORDER BY id DESC limit 1
答案 3 :(得分:0)
从您的查询中删除SELECT *
,HQL doesn't need it:
List<Student> student = sessionFactory.getCurrentSession().createQuery("FROM Student ORDER BY id DESC");